code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module D8Spec where
import Test.Hspec
import Test.QuickCheck
import Text.Megaparsec (parse, ParseError, Dec)
import D8Lib
-- `main` is here so that this module can be run from GHCi on its own. It is
-- not needed for automatic spec discovery.
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "todo" $ do
it "todo" $ do
True `shouldBe` True
|
wfleming/advent-of-code-2016
|
2017/D8/test/D8Spec.hs
|
bsd-3-clause
| 372 | 0 | 13 | 81 | 92 | 51 | 41 | 12 | 1 |
{-# LANGUAGE FlexibleInstances, OverlappingInstances, TypeSynonymInstances #-}
-- | Pretty printing typeclass
--
-- Mostly a class-based re-export of "Text.PrettyPrint", with a few conveniences such as precedence.
-- For precedence, we use the (extended) precedences listed at the top of base.duck, which range from 0 (always parethesized) to 110 (never); note that this is exactly 10 times the standand Haskell precedences.
module Pretty
( Pretty(..)
, Doc, Doc'
, (#>), pguard
-- * Composition
, (<>), (<+>), (<&>), (<&+>), ($$), ($+$)
, hcat, hsep, hcons, vcat, sep, vsep
, (<:>)
, punctuate
, nested, nestedPunct
, parens, brackets, quoted
, prettyap
, sPlural, sStatic
-- * Extraction and use
, pout, qout
) where
import qualified Data.Map as Map
import Text.PrettyPrint (Doc, empty, isEmpty)
import qualified Text.PrettyPrint as PP
type PrecDoc = Int -> Doc
type Doc' = PrecDoc
appPrec :: Int
appPrec = 100
instance Show PrecDoc where
showsPrec i p = shows (p (10*i))
-- |Things that can be converted to Doc (formatted text) representation, possibly with precedence.
class Pretty t where
pretty :: t -> Doc
pretty' :: t -> PrecDoc
pretty x = pretty' x 0
pretty' x _ = pretty x
instance Pretty Doc where
pretty = id
instance Pretty PrecDoc where
pretty' p i = p i
pguard :: Pretty t => Int -> t -> Doc
pguard = flip pretty'
prec' :: Pretty t => Int -> t -> PrecDoc
prec' i x o
| o > i = PP.parens d
| otherwise = d
where d = pretty' x i
infixr 1 #>
-- |Create a representation of the given value with at least the given precedence, wrapping in parentheses as necessary.
(#>) :: Pretty t => Int -> t -> PrecDoc
(#>) i = prec' i . pguard (succ i)
infixl 6 <>, <+>, <&>, <&+>
infixl 5 $$
-- these could also take into account precedence somehow
(<>) :: (Pretty a, Pretty b) => a -> b -> PrecDoc
(<>) a b i = pretty' a i PP.<> pretty' b i
(<+>) :: (Pretty a, Pretty b) => a -> b -> PrecDoc
(<+>) a b i = pretty' a i PP.<+> pretty' b i
-- |Just like '(<>)' except remains 'empty' if either side is empty.
(<&>) :: (Pretty a, Pretty b) => a -> b -> PrecDoc
(<&>) a b i
| isEmpty pa || isEmpty pb = empty
| otherwise = pa PP.<> pb
where
pa = pretty' a i
pb = pretty' b i
-- |Just like '(<+>)' except remains 'empty' if either side is empty.
(<&+>) :: (Pretty a, Pretty b) => a -> b -> PrecDoc
(<&+>) a b i
| isEmpty pa || isEmpty pb = empty
| otherwise = pa PP.<+> pb
where
pa = pretty' a i
pb = pretty' b i
($$) :: (Pretty a, Pretty b) => a -> b -> PrecDoc
($$) a b i = pretty' a i PP.$$ pretty' b i
($+$) :: (Pretty a, Pretty b) => a -> b -> PrecDoc
($+$) a b i
| isEmpty pa = pb
| isEmpty pb = pa
| otherwise = pa PP.$+$ pretty " " PP.$+$ pb
where
pa = pretty' a i
pb = pretty' b i
hcat :: Pretty t => [t] -> PrecDoc
hcat l i = PP.hcat $ map (pguard i) l
hsep :: Pretty t => [t] -> PrecDoc
hsep l i = PP.hsep $ map (pguard i) l
hcons :: (Pretty a, Pretty t) => a -> [t] -> PrecDoc
hcons h l i = PP.hsep $ pguard i h : map (pguard i) l
prettyap :: (Pretty a, Pretty t) => a -> [t] -> PrecDoc
prettyap h [] = pretty' h
prettyap h l = appPrec #> hcons h l
vcat :: Pretty t => [t] -> PrecDoc
vcat l i = PP.vcat $ map (pguard i) l
-- | List version of $+$
vsep :: Pretty t => [t] -> PrecDoc
vsep = foldr ($+$) (const empty) . map pretty'
sep :: Pretty t => [t] -> PrecDoc
sep l i = PP.sep $ map (pguard i) l
punct :: Pretty a => Char -> a -> PrecDoc
punct c a i
| isEmpty pa = empty
| otherwise = pa `pc` PP.char c
where
pa = pretty' a i
pc | c `elem` ":;," = (PP.<>)
| otherwise = (PP.<+>)
withPunct :: (Pretty a, Pretty b) => (Doc -> Doc -> PrecDoc) -> Char -> a -> b -> PrecDoc
withPunct f c a b i
| isEmpty pa = pb
| isEmpty pb = pa
| otherwise = f (punct c pa i) pb i
where
pa = pretty' a i
pb = pretty' b i
infixl 6 <:>
(<:>) :: (Pretty a, Pretty b) => a -> b -> PrecDoc
(<:>) = withPunct (<+>) ':'
nested :: (Pretty a, Pretty b) => a -> b -> PrecDoc
nested a b i
| isEmpty pb = pa
| isEmpty pa = pb
| otherwise = PP.hang pa 2 pb
where
pa = pretty' a i
pb = pretty' b i
nestedPunct :: (Pretty a, Pretty b) => Char -> a -> b -> PrecDoc
nestedPunct = withPunct nested
punctuate :: Pretty t => Char -> [t] -> PrecDoc
punctuate _ [] = const empty
punctuate _ [x] = pretty' x
punctuate d (x:l) = punct d x <+> punctuate d l
grouped :: Pretty t => (Doc -> Doc) -> t -> Doc
grouped f x = f $ pretty x
quoted :: Pretty t => t -> Doc
quoted = grouped PP.quotes
parens :: Pretty t => t -> Doc
parens = grouped PP.parens
brackets :: Pretty t => t -> Doc
brackets = grouped PP.brackets
sPlural :: [a] -> Doc
sPlural [_] = empty
sPlural _ = PP.char 's'
sStatic :: Bool -> String -> String
sStatic False = id
sStatic True = ('s':)
class PrettyOut o where
pout :: Pretty t => t -> o
instance PrettyOut Doc where
pout = pretty
instance PrettyOut PrecDoc where
pout = pretty'
instance PrettyOut String where
pout = PP.render . pretty
instance PrettyOut ShowS where
pout = shows . pretty
instance PrettyOut (IO ()) where
pout = putStr . pout
qout :: (Pretty t, PrettyOut o) => t -> o
qout = pout . quoted
instance Pretty () where
pretty () = empty
instance Pretty Int where
pretty = PP.int
instance Pretty Char where
pretty = PP.char
instance Pretty String where
pretty "" = empty
pretty s = PP.text s
instance (Pretty k, Pretty v) => Pretty (Map.Map k v) where
pretty' = vcat . map (uncurry $ nestedPunct '=') . Map.toList
|
girving/duck
|
duck/Pretty.hs
|
bsd-3-clause
| 5,541 | 0 | 11 | 1,349 | 2,310 | 1,213 | 1,097 | 153 | 1 |
-----------------------------------------------
-- This module deals with detecting whether --
-- parameters are changed or used in an LPPE --
-----------------------------------------------
module Usage where
import LPPE
import Expressions
import Auxiliary
import DataSpec
-- When using these types, [(i,j)] means that parameter j is
-- changed / used / directly used in summand i.
type Changed = [(Int, Int)]
type Used = [(Int, Int)]
type DirectlyUsed = [(Int, Int)]
----------------------------------------------------------------
-- Functions for checking whether or not a parameters is used --
----------------------------------------------------------------
-- This function checks whether a parameter is directly used
-- in a summand, meaning that it is used in either the action
-- parameters, the condition, or the probabilistic choices.
isDirectlyUsedInSummand :: PSummand -> Variable -> Bool
isDirectlyUsedInSummand (params, c, reward, a, aps, probChoices, g) name = directlyUsed
where
overwrittenBySum = elem name (map fst params)
usedInActionPars = variableInExpressions name aps
usedInCondition = variableInExpression name c
usedInReward = variableInExpression name reward
overwrittenByProb = elem name (map fst3 probChoices)
usedInProb = variableInExpressions name (map thd3 probChoices)
directlyUsed = not overwrittenBySum && (usedInActionPars || usedInCondition || usedInReward ||
(not overwrittenByProb && usedInProb))
-- This function checks whether a parameter is used either directly,
-- or in the next state expression of another parameter.
--
-- The boolean parameter indicates whether or not a parameter is considered
-- used in a summand when it is only used to update itself.
isUsedInSummand :: PSummand -> Int -> Variable -> Bool -> Bool
isUsedInSummand (params, c, reward, a, aps, probChoices, g) i name self = used
where
overwrittenBySum = elem name (map fst params)
usedInActionPars = variableInExpressions name aps
usedInCondition = variableInExpression name c
usedInReward = variableInExpression name reward
overwrittenByProb = elem name (map fst3 probChoices)
usedInProb = variableInExpressions name (map thd3 probChoices)
usedInNextState = variableInExpressions name ([g!!j | j <- [0..i-1]] ++ [g!!j | j <- [i+1..length(g)-1]])
|| (self && variableInExpression name (g!!i) && not((g!!i) == Variable name))
used = not overwrittenBySum && (usedInActionPars || usedInCondition || usedInReward ||
(not overwrittenByProb && (usedInProb || usedInNextState)))
-- This function checks whether a parameter is changed in a summand.
-- This is the case when either the next state is an expression different
-- from just the parameter name itself, or is the parameter is used in a
-- nondeterministic or probabilistic sum.
isChangedInSummand :: LPPE -> Int -> Int -> Bool
isChangedInSummand lppe summandNr parNr = nextState /= Variable parameter
|| elem parameter (map fst params)
|| elem parameter (map fst3 probChoices)
where
summand = getPSummand lppe summandNr
nextState = getNextState summand parNr
parameter = fst ((getLPPEPars lppe)!!parNr)
(params, c, reward, a, aps, probChoices, g) = summand
-- Provides a list of elements of the form (i,j),
-- indicating that summand i changes parameter j.
-- For every pair (i,j) that is NOT in this list,
-- summand i does not change parameter j.
--
-- Note that the result of this function is an overapproximation
-- of the variables that are actually changed, as heuristics
-- are used to detect whether or not a variable will be changed.
-- It could be the case the a pair (i,j) is present in the
-- result, even though summand i will in fact never actually
-- change parameter j.
getChanged :: LPPE -> Changed
getChanged lppe = [(summandNr, parNr) | summandNr <- getPSummandNrs lppe,
parNr <- [0..length (getLPPEPars lppe) - 1],
isChangedInSummand lppe summandNr parNr]
-- Provides a list of elements of the form (i,j),
-- indicating that summand i uses parameter j.
-- For every pair (i,j) that is NOT in this list,
-- summand i does not uses parameter j.
--
-- Note that the result of this function is an overapproximation
-- of the variables that are actually used, as heuristics
-- are used to detect whether or not a variable will be used.
-- It could be the case the a pair (i,j) is present in the
-- result, even though summand i will in fact never actually
-- use parameter j.
getUsed :: LPPE -> Used
getUsed lppe = [(summandNr, parNr) | summandNr <- getPSummandNrs lppe,
parNr <- getUsedInSummand lppe summandNr
]
-- Provides a list of elements of the form (i,j),
-- indicating that summand i directly uses parameter j.
-- For every pair (i,j) that is NOT in this list,
-- summand i does not directly use parameter j.
--
-- Note that the result of this function is an overapproximation
-- of the variables that are actually directly used, as heuristics
-- are used to detect whether or not a variable will be directly used.
-- It could be the case the a pair (i,j) is present in the
-- result, even though summand i will in fact never actually
-- use parameter j directly.
getDirectlyUsed :: LPPE -> DirectlyUsed
getDirectlyUsed lppe = [(summandNr, parNr) | summandNr <- getPSummandNrs lppe,
parNr <- getDirectlyUsedInSummand lppe summandNr]
getDirectlyUsedInSummand :: LPPE -> Int -> [Int]
getDirectlyUsedInSummand (LPPE name pars summands) i = getDirectlyUsedInSummand2 (summands!!i) (zip [0..length(pars) - 1] (map fst pars))
getDirectlyUsedInSummand2 :: PSummand -> [(Int, Variable)] -> [Int]
getDirectlyUsedInSummand2 summand [] = []
getDirectlyUsedInSummand2 summand ((i,name):is) | isDirectlyUsedInSummand summand name = i:(getDirectlyUsedInSummand2 summand is)
| otherwise = getDirectlyUsedInSummand2 summand is
getChangedInNextStateNums :: PSummand -> [(Int, Variable)] -> [Int]
getChangedInNextStateNums summand [] = []
getChangedInNextStateNums summand ((i,name):is) | isChangedInNextState summand i name = i:(getChangedInNextStateNums summand is)
| otherwise = getChangedInNextStateNums summand is
isChangedInNextState :: PSummand -> Int -> Variable -> Bool
isChangedInNextState (params, c, reward, a, aps, probChoices, g) i name = not((g!!i) == Variable name) || (elem name (map fst params)) || (elem name (map fst3 probChoices))
getUsedInSummand :: LPPE -> Int -> [Int]
getUsedInSummand (LPPE name pars summands) i = getUsedInSummand2 (summands!!i) (zip [0..length(pars) - 1] (map fst pars))
getUsedInSummand2 :: PSummand -> [(Int, Variable)] -> [Int]
getUsedInSummand2 summand [] = []
getUsedInSummand2 summand ((i,name):is) | isUsedInSummand summand i name True = i:(getUsedInSummand2 summand is)
| otherwise = getUsedInSummand2 summand is
getChangedUnchanged :: LPPE -> Int -> [Int]
getChangedUnchanged (LPPE name pars summands) i = getChangedUnchanged2 (summands!!i) (zip [0..length(pars) - 1] (map fst pars))
-- Dit nog verbeteren: hoeft niet perse een getal te zijn. Maar, mag niet in (prob) sum een waarde gekregen hebben.
-- We checken of een variabele alleen maar 'veranderd' wordt in wat ie toch al moest zijn.
getChangedUnchanged2 :: PSummand -> [(Int, Variable)] -> [Int]
getChangedUnchanged2 summand [] = []
getChangedUnchanged2 summand ((i,name):is) | changedUnchanged = i:(getChangedUnchanged2 summand is)
| otherwise = getChangedUnchanged2 summand is
where
next = getNextState summand i
isValue = case next of
Variable val -> isInteger val
otherwise -> False
values = possibleValueForConditionToBeTrue name (getCondition summand)
UniqueValue value = values
changedUnchanged = isValue && values /= Undecided && value == next
getUsedOnlyInGreaterThanCondition :: LPPE -> Int -> [Int]
getUsedOnlyInGreaterThanCondition (LPPE name pars summands) i = getUsedOnlyInGreaterThanCondition2 (summands!!i) (zip [0..length(pars) - 1] (map fst pars))
getUsedOnlyInGreaterThanCondition2 :: PSummand -> [(Int, Variable)] -> [Int]
getUsedOnlyInGreaterThanCondition2 summand [] = []
getUsedOnlyInGreaterThanCondition2 summand ((i,name):is) | usedOnly = i:(getUsedOnlyInGreaterThanCondition2 summand is)
| otherwise = getUsedOnlyInGreaterThanCondition2 summand is
where
usedOnly = variableInExpressionOnlyGreaterEqual name (getCondition summand)
getRestrictedChanged :: LPPE -> Int -> [Int]
getRestrictedChanged (LPPE name pars summands) i = getRestrictedChanged2 (summands!!i) (zip [0..length(pars) - 1] (map fst pars))
getRestrictedChanged2 :: PSummand -> [(Int, Variable)] -> [Int]
getRestrictedChanged2 summand [] = []
getRestrictedChanged2 summand ((i,name):is) | result = i:(getRestrictedChanged2 summand is)
| otherwise = getRestrictedChanged2 summand is
where
(params, c, reward, a, aps, probChoices, g) = summand
nextState = getNextState summand i
result = not(elem name (map fst params)) && not (elem name (map fst3 probChoices))
&& (nextState == Variable name || isAddition nextState name)
isAddition (Function "plus" [var, Variable val]) name | var == Variable name && isInteger val && parseInteger val >= 0 = True
isAddition _ _ = False
isSubtraction (Function "minus" [var, Variable val]) name | var == Variable name && isInteger val && parseInteger val >= 0 = True
isSubtraction _ _ = False
getUsedInAction :: LPPE -> Int -> [Int]
getUsedInAction (LPPE name pars summands) i = getUsedInAction2 (summands!!i) (zip [0..length(pars) - 1] (map fst pars))
getUsedInAction2 :: PSummand -> [(Int, Variable)] -> [Int]
getUsedInAction2 summand [] = []
getUsedInAction2 summand ((i,name):is) | used = i:(getUsedInAction2 summand is)
| otherwise = getUsedInAction2 summand is
where
(params, c, reward, a, aps, probChoices, g) = summand
overwrittenBySum = elem name (map fst params)
used = not(overwrittenBySum) && variableInExpressions name aps
getUsedInReward :: LPPE -> Int -> [Int]
getUsedInReward (LPPE name pars summands) i = getUsedInReward2 (summands!!i) (zip [0..length(pars) - 1] (map fst pars))
getUsedInReward2 :: PSummand -> [(Int, Variable)] -> [Int]
getUsedInReward2 summand [] = []
getUsedInReward2 summand ((i,name):is) | used = i:(getUsedInReward2 summand is)
| otherwise = getUsedInReward2 summand is
where
(params, c, reward, a, aps, probChoices, g) = summand
overwrittenBySum = elem name (map fst params)
used = not(overwrittenBySum) && variableInExpression name reward
getUsedInNext :: LPPE -> Int -> [Int]
getUsedInNext (LPPE name pars summands) i = getUsedInNext2 (summands!!i) (zip [0..length(pars) - 1] (map fst pars))
getUsedInNext2 :: PSummand -> [(Int, Variable)] -> [Int]
getUsedInNext2 summand [] = []
getUsedInNext2 summand ((i,name):is) | used = i:(getUsedInNext2 summand is)
| otherwise = getUsedInNext2 summand is
where
(params, c, reward, a, aps, probChoices, g) = summand
overwrittenBySum = elem name (map fst params)
usedInNextState = variableInExpressions name ([g!!j | j <- [0..i-1]] ++ [g!!j | j <- [i+1..length(g)-1]])
|| (variableInExpression name (g!!i) && not((g!!i) == Variable name))
overwrittenByProb = elem name (map fst3 probChoices)
used = not(overwrittenBySum) && not(overwrittenByProb) && usedInNextState
getUsedInCondition :: LPPE -> Int -> [Int]
getUsedInCondition (LPPE name pars summands) i = getUsedInCondition2 (summands!!i) (zip [0..length(pars) - 1] (map fst pars))
getUsedInCondition2 :: PSummand -> [(Int, Variable)] -> [Int]
getUsedInCondition2 summand [] = []
getUsedInCondition2 summand ((i,name):is) | used = i:(getUsedInCondition2 summand is)
| otherwise = getUsedInCondition2 summand is
where
(params, c, reward, a, aps, probChoices, g) = summand
overwrittenBySum = elem name (map fst params)
used = not(overwrittenBySum) && variableInExpression name c
getChangedLinear :: LPPE -> Int -> [Int]
getChangedLinear (LPPE name pars summands) i = getChangedLinear2 (summands!!i) (zip [0..length(pars) - 1] (map fst pars))
getChangedLinear2 :: PSummand -> [(Int, Variable)] -> [Int]
getChangedLinear2 summand [] = []
getChangedLinear2 summand ((i,name):is) | changedLinear && not(usedElsewhere) = i:(getChangedLinear2 summand is)
| otherwise = getChangedLinear2 summand is
where
(params, c, reward, a, aps, probChoices, g) = summand
nextState = g!!i
changedLinear = isLinear nextState name
overwrittenBySum = elem name (map fst params)
overwrittenByProb = elem name (map fst3 probChoices)
usedInNextState = variableInExpressions name ([g!!j | j <- [0..i-1]] ++ [g!!j | j <- [i+1..length(g)-1]])
usedElsewhere = not(overwrittenBySum) && not(overwrittenByProb) && usedInNextState
isLinear (Function "plus" [Variable l, Variable r]) name = l == name && isNumber r
isLinear (Function "minus" [Variable l, Variable r]) name = l == name && isNumber r
isLinear _ _ = False
getUsedInProbs :: LPPE -> Int -> [Int]
getUsedInProbs (LPPE name pars summands) i = getUsedInProbs2 (summands!!i) (zip [0..length(pars) - 1] (map fst pars))
getUsedInProbs2 :: PSummand -> [(Int, Variable)] -> [Int]
getUsedInProbs2 summand [] = []
getUsedInProbs2 summand ((i,name):is) | used = i:(getUsedInProbs2 summand is)
| otherwise = getUsedInProbs2 summand is
where
(params, c, reward, a, aps, probChoices, g) = summand
overwrittenBySum = elem name (map fst params)
overwrittenByProb = elem name (map fst3 probChoices)
used = not(overwrittenBySum) && not(overwrittenByProb) && variableInExpressions name (map thd3 probChoices)
|
utwente-fmt/scoop
|
src/Usage.hs
|
bsd-3-clause
| 15,318 | 0 | 17 | 4,033 | 4,180 | 2,215 | 1,965 | 165 | 2 |
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[Foreign]{Foreign calls}
-}
{-# LANGUAGE DeriveDataTypeable #-}
module ETA.Prelude.ForeignCall (
ForeignCall(..), isSafeForeignCall,
Safety(..), playSafe, playInterruptible,
CExportSpec(..), CLabelString, isCLabelString, pprCLabelString,
CCallSpec(..),
CCallTarget(..), isDynamicTarget,
CCallConv(..), defaultCCallConv, ccallConvToInt, ccallConvAttribute,
Header(..), CType(..),
) where
import ETA.Utils.FastString
import ETA.Utils.Binary
import ETA.Utils.Outputable
import ETA.BasicTypes.Module
import ETA.BasicTypes.BasicTypes ( SourceText )
import Data.Char
import Data.Data
{-
************************************************************************
* *
\subsubsection{Data types}
* *
************************************************************************
-}
newtype ForeignCall = CCall CCallSpec
deriving Eq
{-! derive: Binary !-}
isSafeForeignCall :: ForeignCall -> Bool
isSafeForeignCall (CCall (CCallSpec _ _ safe)) = playSafe safe
-- We may need more clues to distinguish foreign calls
-- but this simple printer will do for now
instance Outputable ForeignCall where
ppr (CCall cc) = ppr cc
data Safety
= PlaySafe -- Might invoke Haskell GC, or do a call back, or
-- switch threads, etc. So make sure things are
-- tidy before the call. Additionally, in the threaded
-- RTS we arrange for the external call to be executed
-- by a separate OS thread, i.e., _concurrently_ to the
-- execution of other Haskell threads.
| PlayInterruptible -- Like PlaySafe, but additionally
-- the worker thread running this foreign call may
-- be unceremoniously killed, so it must be scheduled
-- on an unbound thread.
| PlayRisky -- None of the above can happen; the call will return
-- without interacting with the runtime system at all
deriving ( Eq, Show, Data, Typeable )
-- Show used just for Show Lex.Token, I think
{-! derive: Binary !-}
instance Outputable Safety where
ppr PlaySafe = ptext (sLit "safe")
ppr PlayInterruptible = ptext (sLit "interruptible")
ppr PlayRisky = ptext (sLit "unsafe")
playSafe :: Safety -> Bool
playSafe PlaySafe = True
playSafe PlayInterruptible = True
playSafe PlayRisky = False
playInterruptible :: Safety -> Bool
playInterruptible PlayInterruptible = True
playInterruptible _ = False
{-
************************************************************************
* *
\subsubsection{Calling C}
* *
************************************************************************
-}
data CExportSpec
= CExportStatic -- foreign export ccall foo :: ty
CLabelString -- C Name of exported function
CCallConv
deriving (Data, Typeable)
{-! derive: Binary !-}
data CCallSpec
= CCallSpec CCallTarget -- What to call
CCallConv -- Calling convention to use.
Safety
deriving( Eq )
{-! derive: Binary !-}
-- The call target:
-- | How to call a particular function in C-land.
data CCallTarget
-- An "unboxed" ccall# to named function in a particular package.
= StaticTarget
CLabelString -- C-land name of label.
(Maybe PackageKey) -- What package the function is in.
-- If Nothing, then it's taken to be in the current package.
-- Note: This information is only used for PrimCalls on Windows.
-- See CLabel.labelDynamic and CoreToStg.coreToStgApp
-- for the difference in representation between PrimCalls
-- and ForeignCalls. If the CCallTarget is representing
-- a regular ForeignCall then it's safe to set this to Nothing.
-- The first argument of the import is the name of a function pointer (an Addr#).
-- Used when importing a label as "foreign import ccall "dynamic" ..."
Bool -- True => really a function
-- False => a value; only
-- allowed in CAPI imports
| DynamicTarget
deriving( Eq, Data, Typeable )
{-! derive: Binary !-}
isDynamicTarget :: CCallTarget -> Bool
isDynamicTarget DynamicTarget = True
isDynamicTarget _ = False
{-
Stuff to do with calling convention:
ccall: Caller allocates parameters, *and* deallocates them.
stdcall: Caller allocates parameters, callee deallocates.
Function name has @N after it, where N is number of arg bytes
e.g. _Foo@8
ToDo: The stdcall calling convention is x86 (win32) specific,
so perhaps we should emit a warning if it's being used on other
platforms.
See: http://www.programmersheaven.com/2/Calling-conventions
-}
-- any changes here should be replicated in the CallConv type in template haskell
data CCallConv = CCallConv | CApiConv | StdCallConv | PrimCallConv | JavaScriptCallConv | JavaCallConv
deriving (Eq, Data, Typeable)
{-! derive: Binary !-}
instance Outputable CCallConv where
ppr StdCallConv = ptext (sLit "stdcall")
ppr CCallConv = ptext (sLit "ccall")
ppr CApiConv = ptext (sLit "capi")
ppr PrimCallConv = ptext (sLit "prim")
ppr JavaScriptCallConv = ptext (sLit "javascript")
ppr JavaCallConv = ptext (sLit "java")
defaultCCallConv :: CCallConv
defaultCCallConv = CCallConv
ccallConvToInt :: CCallConv -> Int
ccallConvToInt StdCallConv = 0
ccallConvToInt CCallConv = 1
ccallConvToInt CApiConv = panic "ccallConvToInt CApiConv"
ccallConvToInt (PrimCallConv {}) = panic "ccallConvToInt PrimCallConv"
ccallConvToInt JavaScriptCallConv = panic "ccallConvToInt JavaScriptCallConv"
ccallConvToInt JavaCallConv = panic "ccallConvToInt JavaCallConv"
{-
Generate the gcc attribute corresponding to the given
calling convention (used by PprAbsC):
-}
ccallConvAttribute :: CCallConv -> SDoc
ccallConvAttribute StdCallConv = text "__attribute__((__stdcall__))"
ccallConvAttribute CCallConv = empty
ccallConvAttribute CApiConv = empty
ccallConvAttribute (PrimCallConv {}) = panic "ccallConvAttribute PrimCallConv"
ccallConvAttribute JavaScriptCallConv = panic "ccallConvAttribute JavaScriptCallConv"
type CLabelString = FastString -- A C label, completely unencoded
pprCLabelString :: CLabelString -> SDoc
pprCLabelString lbl = ftext lbl
isCLabelString :: CLabelString -> Bool -- Checks to see if this is a valid C label
isCLabelString lbl
= all ok (unpackFS lbl)
where
ok c = isAlphaNum c || c == '_' || c == '.'
-- The '.' appears in e.g. "foo.so" in the
-- module part of a ExtName. Maybe it should be separate
-- Printing into C files:
instance Outputable CExportSpec where
ppr (CExportStatic str _) = pprCLabelString str
instance Outputable CCallSpec where
ppr (CCallSpec fun cconv safety)
= hcat [ ifPprDebug callconv, ppr_fun fun ]
where
callconv = text "{-" <> ppr cconv <> text "-}"
gc_suf | playSafe safety = text "_GC"
| otherwise = empty
ppr_fun (StaticTarget fn mPkgId isFun)
= text (if isFun then "__pkg_ccall"
else "__pkg_ccall_value")
<> gc_suf
<+> (case mPkgId of
Nothing -> empty
Just pkgId -> ppr pkgId)
<+> pprCLabelString fn
ppr_fun DynamicTarget
= text "__dyn_ccall" <> gc_suf <+> text "\"\""
-- The filename for a C header file
newtype Header = Header FastString
deriving (Eq, Data, Typeable)
instance Outputable Header where
ppr (Header h) = quotes $ ppr h
-- | A C type, used in CAPI FFI calls
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# CTYPE'@,
-- 'ApiAnnotation.AnnHeader','ApiAnnotation.AnnVal',
-- 'ApiAnnotation.AnnClose' @'\#-}'@,
-- For details on above see note [Api annotations] in ApiAnnotation
data CType = CType SourceText -- Note [Pragma source text] in BasicTypes
(Maybe Header) -- header to include for this type
FastString -- the type itself
deriving (Data, Typeable)
instance Outputable CType where
ppr (CType _ mh ct) = hDoc <+> ftext ct
where hDoc = case mh of
Nothing -> empty
Just h -> ppr h
{-
************************************************************************
* *
\subsubsection{Misc}
* *
************************************************************************
-}
{-* Generated by DrIFT-v1.0 : Look, but Don't Touch. *-}
instance Binary ForeignCall where
put_ bh (CCall aa) = put_ bh aa
get bh = do aa <- get bh; return (CCall aa)
instance Binary Safety where
put_ bh PlaySafe = do
putByte bh 0
put_ bh PlayInterruptible = do
putByte bh 1
put_ bh PlayRisky = do
putByte bh 2
get bh = do
h <- getByte bh
case h of
0 -> do return PlaySafe
1 -> do return PlayInterruptible
_ -> do return PlayRisky
instance Binary CExportSpec where
put_ bh (CExportStatic aa ab) = do
put_ bh aa
put_ bh ab
get bh = do
aa <- get bh
ab <- get bh
return (CExportStatic aa ab)
instance Binary CCallSpec where
put_ bh (CCallSpec aa ab ac) = do
put_ bh aa
put_ bh ab
put_ bh ac
get bh = do
aa <- get bh
ab <- get bh
ac <- get bh
return (CCallSpec aa ab ac)
instance Binary CCallTarget where
put_ bh (StaticTarget aa ab ac) = do
putByte bh 0
put_ bh aa
put_ bh ab
put_ bh ac
put_ bh DynamicTarget = do
putByte bh 1
get bh = do
h <- getByte bh
case h of
0 -> do aa <- get bh
ab <- get bh
ac <- get bh
return (StaticTarget aa ab ac)
_ -> do return DynamicTarget
instance Binary CCallConv where
put_ bh CCallConv = do
putByte bh 0
put_ bh StdCallConv = do
putByte bh 1
put_ bh PrimCallConv = do
putByte bh 2
put_ bh CApiConv = do
putByte bh 3
put_ bh JavaScriptCallConv = do
putByte bh 4
put_ bh JavaCallConv = do
putByte bh 5
get bh = do
h <- getByte bh
case h of
0 -> do return CCallConv
1 -> do return StdCallConv
2 -> do return PrimCallConv
3 -> do return CApiConv
4 -> do return JavaScriptCallConv
_ -> do return JavaCallConv
instance Binary CType where
put_ bh (CType s mh fs) = do put_ bh s
put_ bh mh
put_ bh fs
get bh = do s <- get bh
mh <- get bh
fs <- get bh
return (CType s mh fs)
instance Binary Header where
put_ bh (Header h) = put_ bh h
get bh = do h <- get bh
return (Header h)
|
alexander-at-github/eta
|
compiler/ETA/Prelude/ForeignCall.hs
|
bsd-3-clause
| 11,955 | 0 | 15 | 4,021 | 2,186 | 1,098 | 1,088 | 204 | 1 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
module Fragment.If.Rules (
RIf
) where
import GHC.Exts (Constraint)
import Ast
import Ast.Error.Common
import Rules
import Fragment.Bool.Ast.Type
import Fragment.Bool.Ast.Term
import Fragment.If.Ast
import qualified Fragment.If.Rules.Type.Infer.SyntaxDirected as SD
import qualified Fragment.If.Rules.Type.Infer.Offline as UO
data RIf
instance AstIn RIf where
type KindList RIf = '[]
type TypeList RIf = '[TyFBool]
type PatternList RIf = '[]
type TermList RIf = '[TmFBool, TmFIf]
instance RulesIn RIf where
type InferKindContextSyntax e w s r m ki ty a RIf = (() :: Constraint)
type InferTypeContextSyntax e w s r m ki ty pt tm a RIf = SD.IfInferTypeContext e w s r m ki ty pt tm a
type InferTypeContextOffline e w s r m ki ty pt tm a RIf = UO.IfInferTypeContext e w s r m ki ty pt tm a
type ErrorList ki ty pt tm a RIf = '[ErrUnexpectedType ki ty a, ErrExpectedTypeEq ki ty a]
type WarningList ki ty pt tm a RIf = '[]
inferKindInputSyntax _ = mempty
inferTypeInputSyntax _ = SD.ifInferTypeRules
inferTypeInputOffline _ = UO.ifInferTypeRules
|
dalaing/type-systems
|
src/Fragment/If/Rules.hs
|
bsd-3-clause
| 1,323 | 1 | 8 | 245 | 389 | 219 | 170 | -1 | -1 |
module Main where
import Server (runBlog)
main :: IO ()
main = runBlog
|
yemi/fabian-blog
|
server/Main.hs
|
bsd-3-clause
| 73 | 0 | 6 | 15 | 27 | 16 | 11 | 4 | 1 |
{-# LANGUAGE ScopedTypeVariables, RankNTypes #-}
module Data.ExternalSort.Internal
where
import Control.Exception
import Control.Monad
import Data.IORef
import Pipes
import qualified Pipes.Prelude as P
import Pipes.Interleave
import System.Directory (removeFile)
import System.IO
import System.Posix.Temp
-- friends
-- import Data.ExternalSort.VectorSort (vectorSort)
-- TODO
-- 0. Use handles instead of file paths in the pipes. Makes closing easier.
-- 1. Clean up on Ctrl-C
-- 2. Put temp files /tmp
-- 3. Make concurrent using Pipes.Concurrent
-- 4. Try unchunking. Check performance
data ExternalSortCfg a =
ExternalSortCfg {
-- | @readVal h@ is responsible for reading one value from a handle
readVal :: Handle -> IO a
-- | @writeVal h r@ writes a single value to a handle
, writeVal :: Handle -> a -> IO ()
-- | the number of values in each chunk
, chunkSize :: Int
-- | a function that sorts each chunk
, sorter :: [a] -> [a]
-- | a function that compares two values
, comparer :: a -> a -> Ordering
}
externalSortFile :: ExternalSortCfg a -> FilePath -> FilePath -> IO ()
externalSortFile cfg inFile outFile = do
withFile inFile ReadMode $ \inH ->
withFile outFile WriteMode $ \outH ->
externalSortHandle cfg inH outH
externalSortHandle :: ExternalSortCfg a -> Handle -> Handle -> IO ()
externalSortHandle cfg inH outH = do
-- fileRef is used to clean up intermediate files when exception occurs
fileRef <- newIORef []
finally
(do sortAndWriteToChunks cfg fileRef inH
runEffect $ fileMerger cfg fileRef outH)
(do files <- readIORef fileRef
mapM_ removeFile files)
-- a pipe that reads in a chunk of a file and sorts it
chunkSorter :: (Monad m) => ExternalSortCfg a -> Pipe [a] [a] m ()
chunkSorter = P.map . sorter
chunkReader :: Int -> (Handle -> IO a) -> Handle -> Producer' [a] IO ()
chunkReader chunkSz readF inH = go
where
go = do
etAs <- lift $ readUpToN chunkSz readF inH
case etAs of
Left as -> yield as
Right as -> yield as >> go
--
-- @Left as@ means that EOF has been reached as @as@ returned. May not be @n@ long.
-- @Right as@ means that EOF has not yet been reached as @n@ @as@ have been read.
--
{-# INLINE readUpToN #-}
readUpToN :: Int -> (Handle -> IO a) -> Handle -> IO (Either [a] [a])
readUpToN n rd h = go 0 []
where
go i as
| i < n = do
eof <- hIsEOF h
if eof
then do
return $ Left $ reverse as
else do
a <- rd h
go (i+1) (a:as)
| otherwise = return $ Right $ reverse as
chunkWriter :: ExternalSortCfg a -> IORef [FilePath] -> Consumer [a] IO ()
chunkWriter cfg fileRef = go
where
go = do
as <- await -- [as] is sorted
lift $ do
(file,h) <- mkstemp "sort-chunk."
modifyIORef fileRef (file:)
finally
(mapM_ (writeVal cfg h) as)
(hClose h)
go
--
-- fromHandle' is like fromHandle except that it uses a function @f@ to read from the Handle rather
-- than reading a 'String'
--
{-# INLINE fromHandle' #-}
fromHandle' :: MonadIO m => (Handle -> IO a) -> Handle -> Producer' a m ()
fromHandle' f h = go
where
go = do
eof <- liftIO $ hIsEOF h
when (not eof) $ do
r <- liftIO (f h)
yield r
go
singleReader :: (Handle -> IO a) -> FilePath -> Producer' a IO ()
singleReader reader inFile = do
h <- lift $ openFile inFile ReadMode
fromHandle' reader h
--
-- @sortAndWriteToChunks@ reads a number of chunks from the input handle, sorts them, and
-- writes them out to intermediate files containing @chunkSize cfg@ values.
-- The paths of the intermediate files are stored in @fileRef@.
-- (This is so if there is an exception and the program needs to abort we can clean these files
-- up.)
--
sortAndWriteToChunks :: forall a. ExternalSortCfg a -> IORef [FilePath]
-> Handle -> IO ()
sortAndWriteToChunks cfg fileRef inH = runEffect producer
where
producer :: Effect IO ()
producer = chunkReader (chunkSize cfg) (readVal cfg) inH >->
chunkSorter cfg >-> chunkWriter cfg fileRef
------------
fileMerger :: forall a. ExternalSortCfg a -> IORef [FilePath] -> Handle -> Effect IO ()
fileMerger cfg fileRef outH = do
files <- lift $ readIORef fileRef
producer files >-> consumer outH
where
producer :: [FilePath] -> Producer a IO ()
producer files = interleave (comparer cfg) kReaders
where
kReaders :: [Producer a IO ()]
kReaders = map (singleReader (readVal cfg)) files
consumer h = P.mapM_ (writeVal cfg h)
|
sseefried/external-sort
|
src/Data/ExternalSort/Internal.hs
|
bsd-3-clause
| 4,755 | 0 | 16 | 1,287 | 1,273 | 644 | 629 | 92 | 2 |
module Main where
import Gittins.Config
import Gittins.Main
import Gittins.Process (ProcessResult(..))
import Gittins.Types
import Control.Monad.Free (Free(..))
import System.Exit (ExitCode(..))
import Test.Hspec
main :: IO ()
main = hspec $ do
describe "register" $
it "adds paths to the config" $
interpret (register [] ["baz", "qux"] False) initConfig `shouldBe`
Config [Repository p p [] | p <- ["qux", "baz", "foo", "bar"]]
describe "unregister" $
it "removes paths from the config" $
interpret (unregister ["bar"]) initConfig `shouldBe`
Config [Repository "foo" "foo" []]
describe "add-to-group" $
it "adds repositories to a group" $
interpret (addToGroup ["my-group"] ["foo", "bar"]) initConfig `shouldBe`
Config [Repository p p ["my-group"] | p <- ["foo", "bar"]]
describe "remove-from-group" $
it "removes repositories from a group" $
interpret (removeFromGroup ["my-group"] ["foo", "bar"])
(Config [Repository p p ["my-group"] | p <- ["foo", "bar"]])
`shouldBe` initConfig
initConfig :: Config
initConfig = Config [Repository "foo" "foo" [], Repository "bar" "bar" []]
interpret :: Act a -> Config -> Config
interpret act = case act of
Free (Log _ a) -> interpret a
Free (LoadConfig f) -> \c -> interpret (f c) c
Free (SaveConfig c a) -> \_ -> interpret a c
Free (IsWorkingTree _ f) -> interpret (f True)
Free (Process _ _ _ f) -> interpret (f $ ProcessResult ExitSuccess "" "")
Free (Concurrently _ a2 _) -> interpret a2
Pure _ -> id
|
bmjames/gittins
|
tests/Tests.hs
|
bsd-3-clause
| 1,575 | 0 | 16 | 352 | 610 | 314 | 296 | 38 | 7 |
module Exercises where
-- Exercise 0 --
foo = [1, 2, 3, 4, 5, 6]
bar = [1,2]
baz = []
-- Doesn't compile
-- halveA :: [a] -> ([a], [a])
-- halveA xs = (take n xs, drop n xs)
-- where n = length xs / 2
halveB :: [a] -> ([a], [a])
halveB xs = splitAt (length xs `div` 2) xs
halveC :: [a] -> ([a], [a])
halveC xs = (take (n `div` 2) xs, drop (n `div` 2) xs)
where n = length xs
-- Doesn't compile
-- halveD :: [a] -> ([a], [a])
-- halveD xs = splitAt (length xs `div` 2)
-- Yields incorrect output
halveE :: [a] -> ([a], [a])
halveE xs = (take n xs, drop (n + 1) xs)
where n = length xs `div` 2
halveF :: [a] -> ([a], [a])
halveF xs = splitAt (div (length xs) 2) xs
-- Doesn't compile
-- halveG :: [a] -> ([a], [a])
-- halveG xs = splitAt (length xs / 2) xs
halveH :: [a] -> ([a], [a])
halveH xs = (take n xs, drop n xs)
where n = length xs `div` 2
-- Exercise 1 --
safetailA :: [a] -> [a]
safetailA xs = if null xs then [] else tail xs
safetailB :: [a] -> [a]
safetailB [] = []
safetailB (_ : xs) = xs
-- Doesn't work; non-exhaustive pattern match
safetailC :: [a] -> [a]
safetailC (_ : xs)
| null xs = [] -- this will never be true
| otherwise = tail xs
safetailD :: [a] -> [a]
safetailD xs
| null xs = []
| otherwise = tail xs
safetailE :: [a] -> [a]
safetailE xs
| length xs == 0 = []
| otherwise = tail xs
-- Doesn't work since the first pattern always matches
-- Commented out since this causes compiler warnings due to the overlapping
-- pattern.
-- safetailF :: [a] -> [a]
-- safetailF xs = tail xs
-- safetailF [] = [] -- this will never match
safetailG :: [a] -> [a]
safetailG [] = []
safetailG xs = tail xs
-- Doesn't work; non-exhaustive pattern match
safetailH :: [a] -> [a]
safetailH [x] = [x]
safetailH (_ : xs) = xs
-- Exercise 2 --
False `orA` False = False
_ `orA` _ = True
False `orB` b = b
True `orB` _ = True
-- This is the definition for xnor not or
b `orC` c
| b == c = True
| otherwise = False
b `orD` c
| b == c = b
| otherwise = True
b `orE` False = b
_ `orE` True = True
b `orF` c
| b == c = c
| otherwise = True
-- Incorrect logic and non-exhaustive pattern matching
-- b `orG` True = b
-- _ `orG` True = True
False `orH` False = False
False `orH` True = True
True `orH` False = True
True `orH` True = True
-- Exercise 3 --
True `andA` True = True
_ `andA` _ = False
a `andB` b = if a then if b then True else False else False
-- Incorrect output on False `andC` False
a `andC` b = if not (a) then not (b) else True
-- Doesn't compile
-- a `andD` b = if a then b
-- Incorrect output on True `andE` True
a `andE` b = if a then if b then False else True else False
a `andF` b = if a then b else False
a `andG` b = if b then a else False
-- Exercise 4 --
mult :: Num a => a -> a -> a -> a
mult x y z = x * y * z
multLambda :: Num a => a -> (a -> (a -> a))
multLambda = \x -> (\y -> (\z -> x * y * z))
mult2 :: Num a => a -> (a -> a)
mult2 x = \y -> x * y
-- Exercise 7 --
remove :: Int -> [a] -> [a]
remove n xs = take n xs ++ drop (n + 1) xs
-- Exercise 8 --
funct :: Int -> [a] -> [a]
funct x xs = take (x + 1) xs ++ drop x xs
|
paulkeene/FP101x
|
chapter03/Exercises.hs
|
bsd-3-clause
| 3,126 | 0 | 11 | 789 | 1,336 | 737 | 599 | 76 | 3 |
{-# LANGUAGE UnicodeSyntax #-}
import Prelude.Unicode
import Data.List
data Tree a = Node a [Tree a]
deriving (Eq, Show)
tree1 = Node 'a' []
tree2 = Node 'a' [Node 'b' []]
tree3 = Node 'a' [Node 'b' [Node 'c' []]]
tree4 = Node 'b' [Node 'd' [], Node 'e' []]
tree5 = Node 'a' [
Node 'f' [Node 'g' []],
Node 'c' [],
Node 'b' [Node 'd' [], Node 'e' []]
]
display ∷ Tree Char → String
display t@(Node e []) = [e]
display t@(Node e childrens) =
"(" ++ [e,' ']++ (concat $ intersperse " " (map display childrens)) ++ ")"
|
m00nlight/99-problems
|
haskell/p-73.hs
|
bsd-3-clause
| 609 | 0 | 11 | 193 | 290 | 150 | 140 | 17 | 1 |
--------------------------------------------------------------------------------
-- | Fast axis-aligned boxes
module Firefly.Math.Box
( Box (..)
, appendBox
, fitBox
, insideBox
, boxBoxCollision
, moveBox
, boxCenter
) where
--------------------------------------------------------------------------------
import Firefly.Math.XY
--------------------------------------------------------------------------------
-- | Axis-aligned bounding box defined by its top-left coordinate and size
data Box = Box
{ boxPosition :: {-# UNPACK #-} !XY
, boxSize :: {-# UNPACK #-} !XY
} deriving (Show)
--------------------------------------------------------------------------------
-- | Create a new box which fits around two boxes
appendBox :: Box -> Box -> Box
appendBox (Box (XY x1 y1) (XY w1 h1)) (Box (XY x2 y2) (XY w2 h2)) =
Box (XY left top) (XY (right - left) (bottom - top))
where
top = min y1 y2
right = max (x1 + w1) (x2 + w2)
bottom = max (y1 + h1) (y2 + h2)
left = min x1 x2
{-# INLINE appendBox #-}
--------------------------------------------------------------------------------
-- | Create a box which fits around all the points in the given list. Returns
-- nothing if an empty list is given.
fitBox :: [XY] -> Maybe Box
fitBox [] = Nothing
fitBox ps = Just $
Box (XY left top) (XY (right - left) (bottom - top))
where
top = minimum $ map y ps
right = maximum $ map x ps
bottom = maximum $ map y ps
left = minimum $ map x ps
--------------------------------------------------------------------------------
-- | Check if a point lies inside a box
insideBox :: XY -> Box -> Bool
insideBox (XY px py) (Box (XY bx by) (XY bw bh)) =
px >= bx && px < bx + bw && py >= by && py < by + bh
{-# INLINE insideBox #-}
--------------------------------------------------------------------------------
-- | Check if a box intersects with another box
boxBoxCollision :: Box -> Box -> Bool
boxBoxCollision (Box (XY x1 y1) (XY w1 h1)) (Box (XY x2 y2) (XY w2 h2))
| x1 + w1 < x2 = False
| x1 > x2 + w2 = False
| y1 + h1 < y2 = False
| y1 > y2 + h2 = False
| otherwise = True
{-# INLINE boxBoxCollision #-}
--------------------------------------------------------------------------------
-- | Move a box by a given offset
moveBox :: XY -> Box -> Box
moveBox offset (Box pos size) = Box (pos .+. offset) size
{-# INLINE moveBox #-}
--------------------------------------------------------------------------------
boxCenter :: Box -> XY
boxCenter (Box pos size) = pos .+. size .* 0.5
{-# INLINE boxCenter #-}
|
jaspervdj/firefly
|
src/Firefly/Math/Box.hs
|
bsd-3-clause
| 2,647 | 0 | 13 | 556 | 712 | 380 | 332 | 47 | 1 |
{- ------------------------------------------------------------------------
(c) The GHC Team, 1992-2012
DeriveConstants is a program that extracts information from the C
declarations in the header files (primarily struct field offsets)
and generates various files, such as a header file that can be #included
into non-C source containing this information.
------------------------------------------------------------------------ -}
import Control.Monad
import Data.Bits
import Data.Char
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Numeric
import System.Environment
import System.Exit
import System.FilePath
import System.IO
import System.Info
import System.Process
main :: IO ()
main = do opts <- parseArgs
let getOption descr opt = case opt opts of
Just x -> return x
Nothing -> die ("No " ++ descr ++ " given")
mode <- getOption "mode" o_mode
fn <- getOption "output filename" o_outputFilename
case mode of
Gen_Haskell_Type -> writeHaskellType fn haskellWanteds
Gen_Haskell_Wrappers -> writeHaskellWrappers fn haskellWanteds
Gen_Haskell_Exports -> writeHaskellExports fn haskellWanteds
Gen_Computed cm ->
do tmpdir <- getOption "tmpdir" o_tmpdir
gccProg <- getOption "gcc program" o_gccProg
nmProg <- getOption "nm program" o_nmProg
let verbose = o_verbose opts
gccFlags = o_gccFlags opts
rs <- getWanted verbose tmpdir gccProg gccFlags nmProg
let haskellRs = [ what
| (wh, what) <- rs
, wh `elem` [Haskell, Both] ]
cRs = [ what
| (wh, what) <- rs
, wh `elem` [C, Both] ]
case cm of
ComputeHaskell -> writeHaskellValue fn haskellRs
ComputeHeader -> writeHeader fn cRs
where haskellWanteds = [ what | (wh, what) <- wanteds,
wh `elem` [Haskell, Both] ]
data Options = Options {
o_verbose :: Bool,
o_mode :: Maybe Mode,
o_tmpdir :: Maybe FilePath,
o_outputFilename :: Maybe FilePath,
o_gccProg :: Maybe FilePath,
o_gccFlags :: [String],
o_nmProg :: Maybe FilePath
}
parseArgs :: IO Options
parseArgs = do args <- getArgs
opts <- f emptyOptions args
return (opts {o_gccFlags = reverse (o_gccFlags opts)})
where emptyOptions = Options {
o_verbose = False,
o_mode = Nothing,
o_tmpdir = Nothing,
o_outputFilename = Nothing,
o_gccProg = Nothing,
o_gccFlags = [],
o_nmProg = Nothing
}
f opts [] = return opts
f opts ("-v" : args')
= f (opts {o_verbose = True}) args'
f opts ("--gen-haskell-type" : args')
= f (opts {o_mode = Just Gen_Haskell_Type}) args'
f opts ("--gen-haskell-value" : args')
= f (opts {o_mode = Just (Gen_Computed ComputeHaskell)}) args'
f opts ("--gen-haskell-wrappers" : args')
= f (opts {o_mode = Just Gen_Haskell_Wrappers}) args'
f opts ("--gen-haskell-exports" : args')
= f (opts {o_mode = Just Gen_Haskell_Exports}) args'
f opts ("--gen-header" : args')
= f (opts {o_mode = Just (Gen_Computed ComputeHeader)}) args'
f opts ("--tmpdir" : dir : args')
= f (opts {o_tmpdir = Just dir}) args'
f opts ("-o" : fn : args')
= f (opts {o_outputFilename = Just fn}) args'
f opts ("--gcc-program" : prog : args')
= f (opts {o_gccProg = Just prog}) args'
f opts ("--gcc-flag" : flag : args')
= f (opts {o_gccFlags = flag : o_gccFlags opts}) args'
f opts ("--nm-program" : prog : args')
= f (opts {o_nmProg = Just prog}) args'
f _ (flag : _) = die ("Unrecognised flag: " ++ show flag)
data Mode = Gen_Haskell_Type
| Gen_Haskell_Wrappers
| Gen_Haskell_Exports
| Gen_Computed ComputeMode
data ComputeMode = ComputeHaskell | ComputeHeader
type Wanteds = [(Where, What Fst)]
type Results = [(Where, What Snd)]
type Name = String
newtype CExpr = CExpr String
newtype CPPExpr = CPPExpr String
data What f = GetFieldType Name (f CExpr Integer)
| GetClosureSize Name (f CExpr Integer)
| GetWord Name (f CExpr Integer)
| GetInt Name (f CExpr Integer)
| GetNatural Name (f CExpr Integer)
| GetBool Name (f CPPExpr Bool)
| StructFieldMacro Name
| ClosureFieldMacro Name
| ClosurePayloadMacro Name
| FieldTypeGcptrMacro Name
data Fst a b = Fst a
data Snd a b = Snd b
data Where = C | Haskell | Both
deriving Eq
constantInt :: Where -> Name -> String -> Wanteds
constantInt w name expr = [(w, GetInt name (Fst (CExpr expr)))]
constantWord :: Where -> Name -> String -> Wanteds
constantWord w name expr = [(w, GetWord name (Fst (CExpr expr)))]
constantNatural :: Where -> Name -> String -> Wanteds
constantNatural w name expr = [(w, GetNatural name (Fst (CExpr expr)))]
constantBool :: Where -> Name -> String -> Wanteds
constantBool w name expr = [(w, GetBool name (Fst (CPPExpr expr)))]
fieldOffset :: Where -> String -> String -> Wanteds
fieldOffset w theType theField = fieldOffset_ w nameBase theType theField
where nameBase = theType ++ "_" ++ theField
fieldOffset_ :: Where -> Name -> String -> String -> Wanteds
fieldOffset_ w nameBase theType theField = [(w, GetWord name (Fst (CExpr expr)))]
where name = "OFFSET_" ++ nameBase
expr = "offsetof(" ++ theType ++ ", " ++ theField ++ ")"
-- FieldType is for defining REP_x to be b32 etc
-- These are both the C-- types used in a load
-- e.g. b32[addr]
-- and the names of the CmmTypes in the compiler
-- b32 :: CmmType
fieldType' :: Where -> String -> String -> Wanteds
fieldType' w theType theField
= fieldType_' w nameBase theType theField
where nameBase = theType ++ "_" ++ theField
fieldType_' :: Where -> Name -> String -> String -> Wanteds
fieldType_' w nameBase theType theField
= [(w, GetFieldType name (Fst (CExpr expr)))]
where name = "REP_" ++ nameBase
expr = "FIELD_SIZE(" ++ theType ++ ", " ++ theField ++ ")"
structField :: Where -> String -> String -> Wanteds
structField = structFieldHelper C
structFieldH :: Where -> String -> String -> Wanteds
structFieldH w = structFieldHelper w w
structField_ :: Where -> Name -> String -> String -> Wanteds
structField_ w nameBase theType theField
= fieldOffset_ w nameBase theType theField
++ fieldType_' C nameBase theType theField
++ structFieldMacro nameBase
structFieldMacro :: Name -> Wanteds
structFieldMacro nameBase = [(C, StructFieldMacro nameBase)]
-- Outputs the byte offset and MachRep for a field
structFieldHelper :: Where -> Where -> String -> String -> Wanteds
structFieldHelper wFT w theType theField = fieldOffset w theType theField
++ fieldType' wFT theType theField
++ structFieldMacro nameBase
where nameBase = theType ++ "_" ++ theField
closureFieldMacro :: Name -> Wanteds
closureFieldMacro nameBase = [(C, ClosureFieldMacro nameBase)]
closurePayload :: Where -> String -> String -> Wanteds
closurePayload w theType theField
= closureFieldOffset_ w nameBase theType theField
++ closurePayloadMacro nameBase
where nameBase = theType ++ "_" ++ theField
closurePayloadMacro :: Name -> Wanteds
closurePayloadMacro nameBase = [(C, ClosurePayloadMacro nameBase)]
-- Byte offset and MachRep for a closure field, minus the header
closureField_ :: Where -> Name -> String -> String -> Wanteds
closureField_ w nameBase theType theField
= closureFieldOffset_ w nameBase theType theField
++ fieldType_' C nameBase theType theField
++ closureFieldMacro nameBase
closureField :: Where -> String -> String -> Wanteds
closureField w theType theField = closureField_ w nameBase theType theField
where nameBase = theType ++ "_" ++ theField
closureFieldOffset_ :: Where -> Name -> String -> String -> Wanteds
closureFieldOffset_ w nameBase theType theField
= defOffset w nameBase (CExpr ("offsetof(" ++ theType ++ ", " ++ theField ++ ") - TYPE_SIZE(StgHeader)"))
-- Size of a closure type, minus the header, named SIZEOF_<type>_NoHdr
-- Also, we #define SIZEOF_<type> to be the size of the whole closure for .cmm.
closureSize :: Where -> String -> Wanteds
closureSize w theType = defSize w (theType ++ "_NoHdr") (CExpr expr)
++ defClosureSize C theType (CExpr expr)
where expr = "TYPE_SIZE(" ++ theType ++ ") - TYPE_SIZE(StgHeader)"
-- Byte offset and MachRep for a closure field, minus the header
closureFieldGcptr :: Where -> String -> String -> Wanteds
closureFieldGcptr w theType theField
= closureFieldOffset_ w nameBase theType theField
++ fieldTypeGcptr nameBase
++ closureFieldMacro nameBase
where nameBase = theType ++ "_" ++ theField
fieldTypeGcptr :: Name -> Wanteds
fieldTypeGcptr nameBase = [(C, FieldTypeGcptrMacro nameBase)]
closureFieldOffset :: Where -> String -> String -> Wanteds
closureFieldOffset w theType theField
= defOffset w nameBase (CExpr expr)
where nameBase = theType ++ "_" ++ theField
expr = "offsetof(" ++ theType ++ ", " ++ theField ++ ") - TYPE_SIZE(StgHeader)"
thunkSize :: Where -> String -> Wanteds
thunkSize w theType
= defSize w (theType ++ "_NoThunkHdr") (CExpr expr)
++ closureSize w theType
where expr = "TYPE_SIZE(" ++ theType ++ ") - TYPE_SIZE(StgThunkHeader)"
defIntOffset :: Where -> Name -> String -> Wanteds
defIntOffset w nameBase cExpr = [(w, GetInt ("OFFSET_" ++ nameBase) (Fst (CExpr cExpr)))]
defOffset :: Where -> Name -> CExpr -> Wanteds
defOffset w nameBase cExpr = [(w, GetWord ("OFFSET_" ++ nameBase) (Fst cExpr))]
structSize :: Where -> String -> Wanteds
structSize w theType = defSize w theType (CExpr ("TYPE_SIZE(" ++ theType ++ ")"))
defSize :: Where -> Name -> CExpr -> Wanteds
defSize w nameBase cExpr = [(w, GetWord ("SIZEOF_" ++ nameBase) (Fst cExpr))]
defClosureSize :: Where -> Name -> CExpr -> Wanteds
defClosureSize w nameBase cExpr = [(w, GetClosureSize ("SIZEOF_" ++ nameBase) (Fst cExpr))]
haskellise :: Name -> Name
haskellise (c : cs) = toLower c : cs
haskellise "" = ""
wanteds :: Wanteds
wanteds = concat
[-- Closure header sizes.
constantWord Both "STD_HDR_SIZE"
-- grrr.. PROFILING is on so we need to
-- subtract sizeofW(StgProfHeader)
"sizeofW(StgHeader) - sizeofW(StgProfHeader)"
,constantWord Both "PROF_HDR_SIZE" "sizeofW(StgProfHeader)"
-- Size of a storage manager block (in bytes).
,constantWord Both "BLOCK_SIZE" "BLOCK_SIZE"
,constantWord C "MBLOCK_SIZE" "MBLOCK_SIZE"
-- blocks that fit in an MBlock, leaving space for the block
-- descriptors
,constantWord Both "BLOCKS_PER_MBLOCK" "BLOCKS_PER_MBLOCK"
-- could be derived, but better to save doing the calculation twice
,fieldOffset Both "StgRegTable" "rR1"
,fieldOffset Both "StgRegTable" "rR2"
,fieldOffset Both "StgRegTable" "rR3"
,fieldOffset Both "StgRegTable" "rR4"
,fieldOffset Both "StgRegTable" "rR5"
,fieldOffset Both "StgRegTable" "rR6"
,fieldOffset Both "StgRegTable" "rR7"
,fieldOffset Both "StgRegTable" "rR8"
,fieldOffset Both "StgRegTable" "rR9"
,fieldOffset Both "StgRegTable" "rR10"
,fieldOffset Both "StgRegTable" "rF1"
,fieldOffset Both "StgRegTable" "rF2"
,fieldOffset Both "StgRegTable" "rF3"
,fieldOffset Both "StgRegTable" "rF4"
,fieldOffset Both "StgRegTable" "rF5"
,fieldOffset Both "StgRegTable" "rF6"
,fieldOffset Both "StgRegTable" "rD1"
,fieldOffset Both "StgRegTable" "rD2"
,fieldOffset Both "StgRegTable" "rD3"
,fieldOffset Both "StgRegTable" "rD4"
,fieldOffset Both "StgRegTable" "rD5"
,fieldOffset Both "StgRegTable" "rD6"
,fieldOffset Both "StgRegTable" "rXMM1"
,fieldOffset Both "StgRegTable" "rXMM2"
,fieldOffset Both "StgRegTable" "rXMM3"
,fieldOffset Both "StgRegTable" "rXMM4"
,fieldOffset Both "StgRegTable" "rXMM5"
,fieldOffset Both "StgRegTable" "rXMM6"
,fieldOffset Both "StgRegTable" "rYMM1"
,fieldOffset Both "StgRegTable" "rYMM2"
,fieldOffset Both "StgRegTable" "rYMM3"
,fieldOffset Both "StgRegTable" "rYMM4"
,fieldOffset Both "StgRegTable" "rYMM5"
,fieldOffset Both "StgRegTable" "rYMM6"
,fieldOffset Both "StgRegTable" "rZMM1"
,fieldOffset Both "StgRegTable" "rZMM2"
,fieldOffset Both "StgRegTable" "rZMM3"
,fieldOffset Both "StgRegTable" "rZMM4"
,fieldOffset Both "StgRegTable" "rZMM5"
,fieldOffset Both "StgRegTable" "rZMM6"
,fieldOffset Both "StgRegTable" "rL1"
,fieldOffset Both "StgRegTable" "rSp"
,fieldOffset Both "StgRegTable" "rSpLim"
,fieldOffset Both "StgRegTable" "rHp"
,fieldOffset Both "StgRegTable" "rHpLim"
,fieldOffset Both "StgRegTable" "rCCCS"
,fieldOffset Both "StgRegTable" "rCurrentTSO"
,fieldOffset Both "StgRegTable" "rCurrentNursery"
,fieldOffset Both "StgRegTable" "rHpAlloc"
,structField C "StgRegTable" "rRet"
,structField C "StgRegTable" "rNursery"
,defIntOffset Both "stgEagerBlackholeInfo"
"FUN_OFFSET(stgEagerBlackholeInfo)"
,defIntOffset Both "stgGCEnter1" "FUN_OFFSET(stgGCEnter1)"
,defIntOffset Both "stgGCFun" "FUN_OFFSET(stgGCFun)"
,fieldOffset Both "Capability" "r"
,fieldOffset C "Capability" "lock"
,structField C "Capability" "no"
,structField C "Capability" "mut_lists"
,structField C "Capability" "context_switch"
,structField C "Capability" "interrupt"
,structField C "Capability" "sparks"
,structField_ Both "Capability_replay_hp" "Capability" "replay.hp"
,structField_ Both "Capability_replay_hp_adjust" "Capability" "replay.hp_adjust"
,structField_ C "Capability_replay_hp_alloc" "Capability" "replay.hp_alloc"
,structField_ Both "Capability_replay_bd" "Capability" "replay.bd"
,structField Both "bdescr" "start"
,structField Both "bdescr" "free"
,structField Both "bdescr" "blocks"
,structField C "bdescr" "gen_no"
,structField C "bdescr" "link"
,structSize C "generation"
,structField C "generation" "n_new_large_words"
,structField C "generation" "weak_ptr_list"
,structSize Both "CostCentreStack"
,structField C "CostCentreStack" "ccsID"
,structFieldH Both "CostCentreStack" "mem_alloc"
,structFieldH Both "CostCentreStack" "scc_count"
,structField C "CostCentreStack" "prevStack"
,structField C "CostCentre" "ccID"
,structField C "CostCentre" "link"
,structField C "StgHeader" "info"
,structField_ Both "StgHeader_ccs" "StgHeader" "prof.ccs"
,structField_ Both "StgHeader_ldvw" "StgHeader" "prof.hp.ldvw"
,structSize Both "StgSMPThunkHeader"
,closurePayload C "StgClosure" "payload"
,structFieldH Both "StgEntCounter" "allocs"
,structFieldH Both "StgEntCounter" "allocd"
,structField Both "StgEntCounter" "registeredp"
,structField Both "StgEntCounter" "link"
,structField Both "StgEntCounter" "entry_count"
,closureSize Both "StgUpdateFrame"
,closureSize C "StgCatchFrame"
,closureSize C "StgStopFrame"
,closureSize Both "StgMutArrPtrs"
,closureField Both "StgMutArrPtrs" "ptrs"
,closureField Both "StgMutArrPtrs" "size"
,closureSize Both "StgArrWords"
,closureField C "StgArrWords" "bytes"
,closurePayload C "StgArrWords" "payload"
,closureField C "StgTSO" "_link"
,closureField C "StgTSO" "global_link"
,closureField C "StgTSO" "what_next"
,closureField C "StgTSO" "why_blocked"
,closureField C "StgTSO" "block_info"
,closureField C "StgTSO" "blocked_exceptions"
,closureField C "StgTSO" "id"
,closureField C "StgTSO" "cap"
,closureField C "StgTSO" "saved_errno"
,closureField C "StgTSO" "trec"
,closureField C "StgTSO" "flags"
,closureField C "StgTSO" "dirty"
,closureField C "StgTSO" "bq"
,closureField_ Both "StgTSO_cccs" "StgTSO" "prof.cccs"
,closureField Both "StgTSO" "stackobj"
,closureField Both "StgStack" "sp"
,closureFieldOffset Both "StgStack" "stack"
,closureField C "StgStack" "stack_size"
,closureField C "StgStack" "dirty"
,structSize C "StgTSOProfInfo"
,closureField Both "StgUpdateFrame" "updatee"
,closureField C "StgCatchFrame" "handler"
,closureField C "StgCatchFrame" "exceptions_blocked"
,closureSize C "StgPAP"
,closureField C "StgPAP" "n_args"
,closureFieldGcptr C "StgPAP" "fun"
,closureField C "StgPAP" "arity"
,closurePayload C "StgPAP" "payload"
,thunkSize C "StgAP"
,closureField C "StgAP" "n_args"
,closureFieldGcptr C "StgAP" "fun"
,closurePayload C "StgAP" "payload"
,thunkSize C "StgAP_STACK"
,closureField C "StgAP_STACK" "size"
,closureFieldGcptr C "StgAP_STACK" "fun"
,closurePayload C "StgAP_STACK" "payload"
,thunkSize C "StgSelector"
,closureFieldGcptr C "StgInd" "indirectee"
,closureSize C "StgMutVar"
,closureField C "StgMutVar" "var"
,closureSize C "StgAtomicallyFrame"
,closureField C "StgAtomicallyFrame" "code"
,closureField C "StgAtomicallyFrame" "next_invariant_to_check"
,closureField C "StgAtomicallyFrame" "result"
,closureField C "StgInvariantCheckQueue" "invariant"
,closureField C "StgInvariantCheckQueue" "my_execution"
,closureField C "StgInvariantCheckQueue" "next_queue_entry"
,closureField C "StgAtomicInvariant" "code"
,closureField C "StgTRecHeader" "enclosing_trec"
,closureSize C "StgCatchSTMFrame"
,closureField C "StgCatchSTMFrame" "handler"
,closureField C "StgCatchSTMFrame" "code"
,closureSize C "StgCatchRetryFrame"
,closureField C "StgCatchRetryFrame" "running_alt_code"
,closureField C "StgCatchRetryFrame" "first_code"
,closureField C "StgCatchRetryFrame" "alt_code"
,closureField C "StgTVarWatchQueue" "closure"
,closureField C "StgTVarWatchQueue" "next_queue_entry"
,closureField C "StgTVarWatchQueue" "prev_queue_entry"
,closureSize C "StgTVar"
,closureField C "StgTVar" "current_value"
,closureField C "StgTVar" "first_watch_queue_entry"
,closureField C "StgTVar" "num_updates"
,closureSize C "StgWeak"
,closureField C "StgWeak" "link"
,closureField C "StgWeak" "key"
,closureField C "StgWeak" "value"
,closureField C "StgWeak" "finalizer"
,closureField C "StgWeak" "cfinalizers"
,closureSize C "StgCFinalizerList"
,closureField C "StgCFinalizerList" "link"
,closureField C "StgCFinalizerList" "fptr"
,closureField C "StgCFinalizerList" "ptr"
,closureField C "StgCFinalizerList" "eptr"
,closureField C "StgCFinalizerList" "flag"
,closureSize C "StgMVar"
,closureField C "StgMVar" "head"
,closureField C "StgMVar" "tail"
,closureField C "StgMVar" "value"
,closureSize C "StgMVarTSOQueue"
,closureField C "StgMVarTSOQueue" "link"
,closureField C "StgMVarTSOQueue" "tso"
,closureSize C "StgBCO"
,closureField C "StgBCO" "instrs"
,closureField C "StgBCO" "literals"
,closureField C "StgBCO" "ptrs"
,closureField C "StgBCO" "arity"
,closureField C "StgBCO" "size"
,closurePayload C "StgBCO" "bitmap"
,closureSize C "StgStableName"
,closureField C "StgStableName" "sn"
,closureSize C "StgBlockingQueue"
,closureField C "StgBlockingQueue" "bh"
,closureField C "StgBlockingQueue" "owner"
,closureField C "StgBlockingQueue" "queue"
,closureField C "StgBlockingQueue" "link"
,closureSize C "MessageBlackHole"
,closureField C "MessageBlackHole" "link"
,closureField C "MessageBlackHole" "tso"
,closureField C "MessageBlackHole" "bh"
,structField_ C "RtsFlags_ProfFlags_showCCSOnException"
"RTS_FLAGS" "ProfFlags.showCCSOnException"
,structField_ C "RtsFlags_DebugFlags_apply"
"RTS_FLAGS" "DebugFlags.apply"
,structField_ C "RtsFlags_DebugFlags_sanity"
"RTS_FLAGS" "DebugFlags.sanity"
,structField_ C "RtsFlags_DebugFlags_weak"
"RTS_FLAGS" "DebugFlags.weak"
,structField_ C "RtsFlags_GcFlags_initialStkSize"
"RTS_FLAGS" "GcFlags.initialStkSize"
,structField_ C "RtsFlags_MiscFlags_tickInterval"
"RTS_FLAGS" "MiscFlags.tickInterval"
,structSize C "StgFunInfoExtraFwd"
,structField C "StgFunInfoExtraFwd" "slow_apply"
,structField C "StgFunInfoExtraFwd" "fun_type"
,structFieldH Both "StgFunInfoExtraFwd" "arity"
,structField_ C "StgFunInfoExtraFwd_bitmap" "StgFunInfoExtraFwd" "b.bitmap"
,structSize Both "StgFunInfoExtraRev"
,structField C "StgFunInfoExtraRev" "slow_apply_offset"
,structField C "StgFunInfoExtraRev" "fun_type"
,structFieldH Both "StgFunInfoExtraRev" "arity"
,structField_ C "StgFunInfoExtraRev_bitmap" "StgFunInfoExtraRev" "b.bitmap"
,structField C "StgLargeBitmap" "size"
,fieldOffset C "StgLargeBitmap" "bitmap"
,structSize C "snEntry"
,structField C "snEntry" "sn_obj"
,structField C "snEntry" "addr"
,structSize C "spEntry"
,structField C "spEntry" "addr"
-- Note that this conditional part only affects the C headers.
-- That's important, as it means we get the same PlatformConstants
-- type on all platforms.
,if os == "mingw32"
then concat [structSize C "StgAsyncIOResult"
,structField C "StgAsyncIOResult" "reqID"
,structField C "StgAsyncIOResult" "len"
,structField C "StgAsyncIOResult" "errCode"]
else []
-- pre-compiled thunk types
,constantWord Haskell "MAX_SPEC_SELECTEE_SIZE" "MAX_SPEC_SELECTEE_SIZE"
,constantWord Haskell "MAX_SPEC_AP_SIZE" "MAX_SPEC_AP_SIZE"
-- closure sizes: these do NOT include the header (see below for
-- header sizes)
,constantWord Haskell "MIN_PAYLOAD_SIZE" "MIN_PAYLOAD_SIZE"
,constantInt Haskell "MIN_INTLIKE" "MIN_INTLIKE"
,constantWord Haskell "MAX_INTLIKE" "MAX_INTLIKE"
,constantWord Haskell "MIN_CHARLIKE" "MIN_CHARLIKE"
,constantWord Haskell "MAX_CHARLIKE" "MAX_CHARLIKE"
,constantWord Haskell "MUT_ARR_PTRS_CARD_BITS" "MUT_ARR_PTRS_CARD_BITS"
-- A section of code-generator-related MAGIC CONSTANTS.
,constantWord Haskell "MAX_Vanilla_REG" "MAX_VANILLA_REG"
,constantWord Haskell "MAX_Float_REG" "MAX_FLOAT_REG"
,constantWord Haskell "MAX_Double_REG" "MAX_DOUBLE_REG"
,constantWord Haskell "MAX_Long_REG" "MAX_LONG_REG"
,constantWord Haskell "MAX_XMM_REG" "MAX_XMM_REG"
,constantWord Haskell "MAX_Real_Vanilla_REG" "MAX_REAL_VANILLA_REG"
,constantWord Haskell "MAX_Real_Float_REG" "MAX_REAL_FLOAT_REG"
,constantWord Haskell "MAX_Real_Double_REG" "MAX_REAL_DOUBLE_REG"
,constantWord Haskell "MAX_Real_XMM_REG" "MAX_REAL_XMM_REG"
,constantWord Haskell "MAX_Real_Long_REG" "MAX_REAL_LONG_REG"
-- This tells the native code generator the size of the spill
-- area is has available.
,constantWord Haskell "RESERVED_C_STACK_BYTES" "RESERVED_C_STACK_BYTES"
-- The amount of (Haskell) stack to leave free for saving
-- registers when returning to the scheduler.
,constantWord Haskell "RESERVED_STACK_WORDS" "RESERVED_STACK_WORDS"
-- Continuations that need more than this amount of stack
-- should do their own stack check (see bug #1466).
,constantWord Haskell "AP_STACK_SPLIM" "AP_STACK_SPLIM"
-- Size of a word, in bytes
,constantWord Haskell "WORD_SIZE" "SIZEOF_HSWORD"
-- Size of a double in StgWords.
,constantWord Haskell "DOUBLE_SIZE" "SIZEOF_DOUBLE"
-- Size of a C int, in bytes. May be smaller than wORD_SIZE.
,constantWord Haskell "CINT_SIZE" "SIZEOF_INT"
,constantWord Haskell "CLONG_SIZE" "SIZEOF_LONG"
,constantWord Haskell "CLONG_LONG_SIZE" "SIZEOF_LONG_LONG"
-- Number of bits to shift a bitfield left by in an info table.
,constantWord Haskell "BITMAP_BITS_SHIFT" "BITMAP_BITS_SHIFT"
-- Amount of pointer bits used for semi-tagging constructor closures
,constantWord Haskell "TAG_BITS" "TAG_BITS"
,constantBool Haskell "WORDS_BIGENDIAN" "defined(WORDS_BIGENDIAN)"
,constantBool Haskell "DYNAMIC_BY_DEFAULT" "defined(DYNAMIC_BY_DEFAULT)"
,constantWord Haskell "LDV_SHIFT" "LDV_SHIFT"
,constantNatural Haskell "ILDV_CREATE_MASK" "LDV_CREATE_MASK"
,constantNatural Haskell "ILDV_STATE_CREATE" "LDV_STATE_CREATE"
,constantNatural Haskell "ILDV_STATE_USE" "LDV_STATE_USE"
]
getWanted :: Bool -> FilePath -> FilePath -> [String] -> FilePath -> IO Results
getWanted verbose tmpdir gccProgram gccFlags nmProgram
= do let cStuff = unlines (headers ++ concatMap (doWanted . snd) wanteds)
cFile = tmpdir </> "tmp.c"
oFile = tmpdir </> "tmp.o"
writeFile cFile cStuff
execute verbose gccProgram (gccFlags ++ ["-c", cFile, "-o", oFile])
xs <- readProcess nmProgram ["-P", oFile] ""
let ls = lines xs
ms = map parseNmLine ls
m = Map.fromList $ catMaybes ms
rs <- mapM (lookupResult m) wanteds
return rs
where headers = ["#define IN_STG_CODE 0",
"",
"/*",
" * We need offsets of profiled things...",
" * better be careful that this doesn't",
" * affect the offsets of anything else.",
" */",
"",
"#define PROFILING",
"#define THREADED_RTS",
"#define REPLAY",
"",
"#include \"PosixSource.h\"",
"#include \"Rts.h\"",
"#include \"Stable.h\"",
"#include \"Capability.h\"",
"",
"#include <inttypes.h>",
"#include <stddef.h>",
"#include <stdio.h>",
"#include <string.h>",
"",
"#define FIELD_SIZE(s_type, field) ((size_t)sizeof(((s_type*)0)->field))",
"#define TYPE_SIZE(type) (sizeof(type))",
"#define FUN_OFFSET(sym) (offsetof(Capability,f.sym) - offsetof(Capability,r))",
"",
"#pragma GCC poison sizeof"
]
prefix = "derivedConstant"
mkFullName name = prefix ++ name
-- We add 1 to the value, as some platforms will make a symbol
-- of size 1 when for
-- char foo[0];
-- We then subtract 1 again when parsing.
doWanted (GetFieldType name (Fst (CExpr cExpr)))
= ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"]
doWanted (GetClosureSize name (Fst (CExpr cExpr)))
= ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"]
doWanted (GetWord name (Fst (CExpr cExpr)))
= ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"]
doWanted (GetInt name (Fst (CExpr cExpr)))
= ["char " ++ mkFullName name ++ "Mag[1 + ((intptr_t)(" ++ cExpr ++ ") >= 0 ? (" ++ cExpr ++ ") : -(" ++ cExpr ++ "))];",
"char " ++ mkFullName name ++ "Sig[(intptr_t)(" ++ cExpr ++ ") >= 0 ? 3 : 1];"]
doWanted (GetNatural name (Fst (CExpr cExpr)))
= -- These casts fix "right shift count >= width of type"
-- warnings
let cExpr' = "(uint64_t)(size_t)(" ++ cExpr ++ ")"
in ["char " ++ mkFullName name ++ "0[1 + ((" ++ cExpr' ++ ") & 0xFFFF)];",
"char " ++ mkFullName name ++ "1[1 + (((" ++ cExpr' ++ ") >> 16) & 0xFFFF)];",
"char " ++ mkFullName name ++ "2[1 + (((" ++ cExpr' ++ ") >> 32) & 0xFFFF)];",
"char " ++ mkFullName name ++ "3[1 + (((" ++ cExpr' ++ ") >> 48) & 0xFFFF)];"]
doWanted (GetBool name (Fst (CPPExpr cppExpr)))
= ["#if " ++ cppExpr,
"char " ++ mkFullName name ++ "[1];",
"#else",
"char " ++ mkFullName name ++ "[2];",
"#endif"]
doWanted (StructFieldMacro {}) = []
doWanted (ClosureFieldMacro {}) = []
doWanted (ClosurePayloadMacro {}) = []
doWanted (FieldTypeGcptrMacro {}) = []
-- parseNmLine parses "nm -P" output that looks like
-- "derivedConstantMAX_Vanilla_REG C 0000000b 0000000b" (GNU nm)
-- "_derivedConstantMAX_Vanilla_REG C b 0" (Mac OS X)
-- "_derivedConstantMAX_Vanilla_REG C 000000b" (MinGW)
-- "derivedConstantMAX_Vanilla_REG D 1 b" (Solaris)
-- and returns ("MAX_Vanilla_REG", 11)
parseNmLine line
= case words line of
('_' : n) : "C" : s : _ -> mkP n s
n : "C" : s : _ -> mkP n s
[n, "D", _, s] -> mkP n s
_ -> Nothing
where mkP r s = case (stripPrefix prefix r, readHex s) of
(Just name, [(size, "")]) -> Just (name, size)
_ -> Nothing
-- If an Int value is larger than 2^28 or smaller
-- than -2^28, then fail.
-- This test is a bit conservative, but if any
-- constants are roughly maxBound or minBound then
-- we probably need them to be Integer rather than
-- Int so that -- cross-compiling between 32bit and
-- 64bit platforms works.
lookupSmall :: Map String Integer -> Name -> IO Integer
lookupSmall m name
= case Map.lookup name m of
Just v
| v > 2^(28 :: Int) ||
v < -(2^(28 :: Int)) ->
die ("Value too large for GetWord: " ++ show v)
| otherwise -> return v
Nothing -> die ("Can't find " ++ show name)
lookupResult :: Map String Integer -> (Where, What Fst)
-> IO (Where, What Snd)
lookupResult m (w, GetWord name _)
= do v <- lookupSmall m name
return (w, GetWord name (Snd (v - 1)))
lookupResult m (w, GetInt name _)
= do mag <- lookupSmall m (name ++ "Mag")
sig <- lookupSmall m (name ++ "Sig")
return (w, GetWord name (Snd ((mag - 1) * (sig - 2))))
lookupResult m (w, GetNatural name _)
= do v0 <- lookupSmall m (name ++ "0")
v1 <- lookupSmall m (name ++ "1")
v2 <- lookupSmall m (name ++ "2")
v3 <- lookupSmall m (name ++ "3")
let v = (v0 - 1)
+ shiftL (v1 - 1) 16
+ shiftL (v2 - 1) 32
+ shiftL (v3 - 1) 48
return (w, GetWord name (Snd v))
lookupResult m (w, GetBool name _)
= do v <- lookupSmall m name
case v of
1 -> return (w, GetBool name (Snd True))
2 -> return (w, GetBool name (Snd False))
_ -> die ("Bad boolean: " ++ show v)
lookupResult m (w, GetFieldType name _)
= do v <- lookupSmall m name
return (w, GetFieldType name (Snd (v - 1)))
lookupResult m (w, GetClosureSize name _)
= do v <- lookupSmall m name
return (w, GetClosureSize name (Snd (v - 1)))
lookupResult _ (w, StructFieldMacro name)
= return (w, StructFieldMacro name)
lookupResult _ (w, ClosureFieldMacro name)
= return (w, ClosureFieldMacro name)
lookupResult _ (w, ClosurePayloadMacro name)
= return (w, ClosurePayloadMacro name)
lookupResult _ (w, FieldTypeGcptrMacro name)
= return (w, FieldTypeGcptrMacro name)
writeHaskellType :: FilePath -> [What Fst] -> IO ()
writeHaskellType fn ws = writeFile fn xs
where xs = unlines (headers ++ body ++ footers)
headers = ["data PlatformConstants = PlatformConstants {"
-- Now a kludge that allows the real entries to
-- all start with a comma, which makes life a
-- little easier
," pc_platformConstants :: ()"]
footers = [" } deriving Read"]
body = concatMap doWhat ws
doWhat (GetClosureSize name _) = [" , pc_" ++ name ++ " :: Int"]
doWhat (GetFieldType name _) = [" , pc_" ++ name ++ " :: Int"]
doWhat (GetWord name _) = [" , pc_" ++ name ++ " :: Int"]
doWhat (GetInt name _) = [" , pc_" ++ name ++ " :: Int"]
doWhat (GetNatural name _) = [" , pc_" ++ name ++ " :: Integer"]
doWhat (GetBool name _) = [" , pc_" ++ name ++ " :: Bool"]
doWhat (StructFieldMacro {}) = []
doWhat (ClosureFieldMacro {}) = []
doWhat (ClosurePayloadMacro {}) = []
doWhat (FieldTypeGcptrMacro {}) = []
writeHaskellValue :: FilePath -> [What Snd] -> IO ()
writeHaskellValue fn rs = writeFile fn xs
where xs = unlines (headers ++ body ++ footers)
headers = ["PlatformConstants {"
," pc_platformConstants = ()"]
footers = [" }"]
body = concatMap doWhat rs
doWhat (GetClosureSize name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetFieldType name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetWord name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetInt name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetNatural name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetBool name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (StructFieldMacro {}) = []
doWhat (ClosureFieldMacro {}) = []
doWhat (ClosurePayloadMacro {}) = []
doWhat (FieldTypeGcptrMacro {}) = []
writeHaskellWrappers :: FilePath -> [What Fst] -> IO ()
writeHaskellWrappers fn ws = writeFile fn xs
where xs = unlines body
body = concatMap doWhat ws
doWhat (GetFieldType {}) = []
doWhat (GetClosureSize {}) = []
doWhat (GetWord name _) = [haskellise name ++ " :: DynFlags -> Int",
haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"]
doWhat (GetInt name _) = [haskellise name ++ " :: DynFlags -> Int",
haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"]
doWhat (GetNatural name _) = [haskellise name ++ " :: DynFlags -> Integer",
haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"]
doWhat (GetBool name _) = [haskellise name ++ " :: DynFlags -> Bool",
haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"]
doWhat (StructFieldMacro {}) = []
doWhat (ClosureFieldMacro {}) = []
doWhat (ClosurePayloadMacro {}) = []
doWhat (FieldTypeGcptrMacro {}) = []
writeHaskellExports :: FilePath -> [What Fst] -> IO ()
writeHaskellExports fn ws = writeFile fn xs
where xs = unlines body
body = concatMap doWhat ws
doWhat (GetFieldType {}) = []
doWhat (GetClosureSize {}) = []
doWhat (GetWord name _) = [" " ++ haskellise name ++ ","]
doWhat (GetInt name _) = [" " ++ haskellise name ++ ","]
doWhat (GetNatural name _) = [" " ++ haskellise name ++ ","]
doWhat (GetBool name _) = [" " ++ haskellise name ++ ","]
doWhat (StructFieldMacro {}) = []
doWhat (ClosureFieldMacro {}) = []
doWhat (ClosurePayloadMacro {}) = []
doWhat (FieldTypeGcptrMacro {}) = []
writeHeader :: FilePath -> [What Snd] -> IO ()
writeHeader fn rs = writeFile fn xs
where xs = unlines (headers ++ body)
headers = ["/* This file is created automatically. Do not edit by hand.*/", ""]
body = concatMap doWhat rs
doWhat (GetFieldType name (Snd v)) = ["#define " ++ name ++ " b" ++ show (v * 8)]
doWhat (GetClosureSize name (Snd v)) = ["#define " ++ name ++ " (SIZEOF_StgHeader+" ++ show v ++ ")"]
doWhat (GetWord name (Snd v)) = ["#define " ++ name ++ " " ++ show v]
doWhat (GetInt name (Snd v)) = ["#define " ++ name ++ " " ++ show v]
doWhat (GetNatural name (Snd v)) = ["#define " ++ name ++ " " ++ show v]
doWhat (GetBool name (Snd v)) = ["#define " ++ name ++ " " ++ show (fromEnum v)]
doWhat (StructFieldMacro nameBase) =
["#define " ++ nameBase ++ "(__ptr__) REP_" ++ nameBase ++ "[__ptr__+OFFSET_" ++ nameBase ++ "]"]
doWhat (ClosureFieldMacro nameBase) =
["#define " ++ nameBase ++ "(__ptr__) REP_" ++ nameBase ++ "[__ptr__+SIZEOF_StgHeader+OFFSET_" ++ nameBase ++ "]"]
doWhat (ClosurePayloadMacro nameBase) =
["#define " ++ nameBase ++ "(__ptr__,__ix__) W_[__ptr__+SIZEOF_StgHeader+OFFSET_" ++ nameBase ++ " + WDS(__ix__)]"]
doWhat (FieldTypeGcptrMacro nameBase) =
["#define REP_" ++ nameBase ++ " gcptr"]
die :: String -> IO a
die err = do hPutStrLn stderr err
exitFailure
execute :: Bool -> FilePath -> [String] -> IO ()
execute verbose prog args
= do when verbose $ putStrLn $ showCommandForUser prog args
ec <- rawSystem prog args
unless (ec == ExitSuccess) $
die ("Executing " ++ show prog ++ " failed")
|
hferreiro/replay
|
utils/deriveConstants/DeriveConstants.hs
|
bsd-3-clause
| 41,237 | 199 | 19 | 13,373 | 9,490 | 4,914 | 4,576 | 703 | 26 |
module MGRSRef.Tests where
import Test.HUnit
import HUnitExtensions
import Equals
import Datum
import MGRSRef
import UTMRef
mgrsrefTests = TestList [
TestLabel "mgrsref - to show with precision" testToShowWithPrecision
, TestLabel "mgrsref - to show" testToMGRSRef
, TestLabel "mgrsref - to mkMGRSRef" testToMkMGRSRef
, TestLabel "mgrsref - to mkMGRSRef'" testToMkMGRSRef'
, TestLabel "mgrsref - to UTMRef" testToUTMRef
]
testToShowWithPrecision = TestList [
(showWithPrecision $ MGRSRef 10000 78000 'M' 'U' 32 'U' M1000 False wgs84Datum) M1 ~?= "32UMU1000078000"
]
testToMGRSRef = TestList [
(show $ toMGRSRef (extract $ mkUTMRef 443575.71 4349755.98 'S' 13) False) ~?= "13SDD4357649756"
, (show $ toMGRSRef (extract $ mkUTMRef 500000.0 0.0 'N' 1) False) ~?= "01NEA0000000000"
, (show $ toMGRSRef (extract $ mkUTMRef 500000.0 0.0 'N' 1) True) ~?= "01NEL0000000000"
, (show $ toMGRSRef (extract $ mkUTMRef 500000.0 0.0 'N' 2) False) ~?= "02NNF0000000000"
, (show $ toMGRSRef (extract $ mkUTMRef 500000.0 0.0 'N' 2) True) ~?= "02NNR0000000000"
, (show $ toMGRSRef (extract $ mkUTMRef 500000.0 0.0 'N' 3) False) ~?= "03NWA0000000000"
, (show $ toMGRSRef (extract $ mkUTMRef 500000.0 0.0 'N' 3) True) ~?= "03NWL0000000000"
, (show $ toMGRSRef (extract $ mkUTMRef 500000.0 1999999.0 'Q' 1) False) ~?= "01QEV0000099999"
, (show $ toMGRSRef (extract $ mkUTMRef 500000.0 1999999.0 'Q' 1) True) ~?= "01QEK0000099999"
, (show $ toMGRSRef (extract $ mkUTMRef 800000.0 0.0 'N' 1) False) ~?= "01NHA0000000000"
, (show $ toMGRSRef (extract $ mkUTMRef 800000.0 0.0 'N' 1) True) ~?= "01NHL0000000000"
, (show $ toMGRSRef (extract $ mkUTMRef 199999.0 0.0 'N' 2) False) ~?= "02NJF9999900000"
, (show $ toMGRSRef (extract $ mkUTMRef 199999.0 0.0 'N' 2) True) ~?= "02NJR9999900000"
]
testToMkMGRSRef = TestList [
(show $ extract $ mkMGRSRef 0 16300 'E' 'U' 10 'U' M1 False) ~?= "10UEU0000016300"
, (show $ extract $ mkMGRSRef 43575 49756 'D' 'D' 13 'S' M1 False) ~?= "13SDD4357549756"
]
testToUTMRef = TestList [
(MGRSRef.toUTMRef $ extract $ mkMGRSRef' "13SDD4357649756") `shouldReturn` (UTMRef 443576.0 4349756.0 'S' 13 wgs84Datum)
, (MGRSRef.toUTMRef $ extract $ mkMGRSRef' "32UMU1078") `shouldReturn` (UTMRef 410000.0 5378000.0 'U' 32 wgs84Datum)
, (MGRSRef.toUTMRef $ MGRSRef 0 16300 'E' 'U' 10 'U' M1 False wgs84Datum) `shouldReturn` (UTMRef 500000.0 5316300.0 'U' 10 wgs84Datum)
, (MGRSRef.toUTMRef $ MGRSRef 43575 49756 'D' 'D' 13 'S' M1 False wgs84Datum) `shouldReturn` (UTMRef 443575.0 4349756.0 'S' 13 wgs84Datum)
]
testToMkMGRSRef' = TestList [
(show $ extract $ mkMGRSRef' "32UMU1078") ~?= "32UMU1078"
, (showWithPrecision (extract $ mkMGRSRef' "32UMU1078") M1) ~?= "32UMU1000078000"
, (showWithPrecision (extract $ mkMGRSRef' "32UMU1078") M10) ~?= "32UMU10007800"
, (showWithPrecision (extract $ mkMGRSRef' "32UMU1078") M100) ~?= "32UMU100780"
, (showWithPrecision (extract $ mkMGRSRef' "32UMU1078") M1000) ~?= "32UMU1078"
, (showWithPrecision (extract $ mkMGRSRef' "32UMU1078") M10000) ~?= "32UMU17"
]
|
danfran/hcoord
|
test/MGRSRef/Tests.hs
|
bsd-3-clause
| 3,158 | 0 | 13 | 588 | 1,001 | 521 | 480 | 44 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Database.DBCleaner.PostgreSQLSimpleSpec where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (void)
import Data.Text (Text)
import Database.PostgreSQL.Simple (Connection,
connectPostgreSQL,
execute, query_)
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.ToRow
import Test.Hspec
import Database.DBCleaner.PostgreSQLSimple (withConnection)
import Database.DBCleaner.Types (Strategy (..))
data User = User
{ userName :: Text
, userEmail :: Text
} deriving (Show, Eq)
instance FromRow User where
fromRow = User <$> field
<*> field
instance ToRow User where
toRow User{..} = [ toField userName
, toField userEmail
]
withTestConnection :: Strategy -> (Connection -> IO a) -> IO a
withTestConnection s f = connectPostgreSQL "dbname=dbcleaner" >>= withConnection s f
createUser :: Connection -> User -> IO ()
createUser c = void . execute c "INSERT INTO users (name, email) VALUES (?, ?)"
listUsers :: Connection -> IO [User]
listUsers c = query_ c "SELECT name, email FROM users"
spec :: Spec
spec =
describe "withPGConnection" $ do
context "when strategy is Transaction" $
it "deletes all records create inside the transaction" $ do
withTestConnection Transaction $ \c -> do
let user1 = User "user1" "[email protected]"
user2 = User "user2" "[email protected]"
mapM_ (createUser c) [user1, user2]
listUsers c >>= shouldMatchList [user1, user2]
withTestConnection Transaction listUsers `shouldReturn` []
context "when strategy is Truncation" $
it "truncates all the tables of the schema" $ do
withTestConnection Truncation $ \c -> do
let user1 = User "user1" "[email protected]"
user2 = User "user2" "[email protected]"
mapM_ (createUser c) [user1, user2]
listUsers c >>= shouldMatchList [user1, user2]
withTestConnection Truncation listUsers `shouldReturn` []
|
stackbuilders/dbcleaner
|
test/Database/DBCleaner/PostgreSQLSimpleSpec.hs
|
mit
| 2,431 | 0 | 18 | 765 | 555 | 293 | 262 | 50 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- | Description : @ToJSON@ for Messages
--
-- This module contains the @ToJSON@ instance for @Message@.
module IHaskell.IPython.Message.Writer (ToJSON(..)) where
import Data.Aeson
import Data.Map (Map)
import Data.Text (Text, pack)
import Data.Monoid (mempty)
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString as B
import Data.Text.Encoding
import IHaskell.IPython.Types
instance ToJSON LanguageInfo where
toJSON info = object
[ "name" .= languageName info
, "version" .= languageVersion info
, "file_extension" .= languageFileExtension info
, "codemirror_mode" .= languageCodeMirrorMode info
]
-- Convert message bodies into JSON.
instance ToJSON Message where
toJSON rep@KernelInfoReply{} =
object
[ "protocol_version" .= string "5.0" -- current protocol version, major and minor
, "implementation" .= implementation rep
, "implementation_version" .= implementationVersion rep
, "language_info" .= languageInfo rep
]
toJSON ExecuteReply { status = status, executionCounter = counter, pagerOutput = pager } =
object
[ "status" .= show status
, "execution_count" .= counter
, "payload" .=
if null pager
then []
else map mkObj pager
, "user_variables" .= emptyMap
, "user_expressions" .= emptyMap
]
where
mkObj o = object
[ "source" .= string "page"
, "line" .= Number 0
, "data" .= object [displayDataToJson o]
]
toJSON PublishStatus { executionState = executionState } =
object ["execution_state" .= executionState]
toJSON PublishStream { streamType = streamType, streamContent = content } =
object ["data" .= content, "name" .= streamType]
toJSON PublishDisplayData { source = src, displayData = datas } =
object
["source" .= src, "metadata" .= object [], "data" .= object (map displayDataToJson datas)]
toJSON PublishOutput { executionCount = execCount, reprText = reprText } =
object
[ "data" .= object ["text/plain" .= reprText]
, "execution_count" .= execCount
, "metadata" .= object []
]
toJSON PublishInput { executionCount = execCount, inCode = code } =
object ["execution_count" .= execCount, "code" .= code]
toJSON (CompleteReply _ matches start end metadata status) =
object
[ "matches" .= matches
, "cursor_start" .= start
, "cursor_end" .= end
, "metadata" .= metadata
, "status" .= if status
then string "ok"
else "error"
]
toJSON i@InspectReply{} =
object
[ "status" .= if inspectStatus i
then string "ok"
else "error"
, "data" .= object (map displayDataToJson . inspectData $ i)
, "metadata" .= object []
, "found" .= inspectStatus i
]
toJSON ShutdownReply { restartPending = restart } =
object ["restart" .= restart]
toJSON ClearOutput { wait = wait } =
object ["wait" .= wait]
toJSON RequestInput { inputPrompt = prompt } =
object ["prompt" .= prompt]
toJSON req@CommOpen{} =
object
[ "comm_id" .= commUuid req
, "target_name" .= commTargetName req
, "target_module" .= commTargetModule req
, "data" .= commData req
]
toJSON req@CommData{} =
object ["comm_id" .= commUuid req, "data" .= commData req]
toJSON req@CommClose{} =
object ["comm_id" .= commUuid req, "data" .= commData req]
toJSON req@HistoryReply{} =
object ["history" .= map tuplify (historyReply req)]
where
tuplify (HistoryReplyElement sess linum res) = (sess, linum, case res of
Left inp -> toJSON inp
Right (inp, out) -> toJSON out)
toJSON body = error $ "Do not know how to convert to JSON for message " ++ show body
-- | Print an execution state as "busy", "idle", or "starting".
instance ToJSON ExecutionState where
toJSON Busy = String "busy"
toJSON Idle = String "idle"
toJSON Starting = String "starting"
-- | Print a stream as "stdin" or "stdout" strings.
instance ToJSON StreamType where
toJSON Stdin = String "stdin"
toJSON Stdout = String "stdout"
-- | Convert a MIME type and value into a JSON dictionary pair.
displayDataToJson :: DisplayData -> (Text, Value)
displayDataToJson (DisplayData mimeType dataStr) =
pack (show mimeType) .= String dataStr
----- Constants -----
emptyMap :: Map String String
emptyMap = mempty
emptyList :: [Int]
emptyList = []
ints :: [Int] -> [Int]
ints = id
string :: String -> String
string = id
|
artuuge/IHaskell
|
ipython-kernel/src/IHaskell/IPython/Message/Writer.hs
|
mit
| 4,918 | 0 | 13 | 1,450 | 1,261 | 668 | 593 | 108 | 1 |
module Test.Lamdu.FreshDb (readFreshDb) where
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Lazy as LBS
import Lamdu.Data.Export.JSON.Codec (Entity)
import qualified Lamdu.Paths as Paths
import Test.Lamdu.Prelude
readFreshDb :: IO [Entity]
readFreshDb =
Paths.getDataFileName "freshdb.json"
>>= LBS.readFile <&> Aeson.eitherDecode
>>= either fail pure
<&> Aeson.fromJSON
>>=
\case
Aeson.Error str -> fail str
Aeson.Success x -> pure x
|
lamdu/lamdu
|
test/Test/Lamdu/FreshDb.hs
|
gpl-3.0
| 514 | 0 | 11 | 109 | 138 | 79 | 59 | -1 | -1 |
module BgImplicitVarBind where
f = True
g = if f then 3 else f
|
roberth/uu-helium
|
test/typeerrors/Examples/BgImplicitVarBind.hs
|
gpl-3.0
| 64 | 0 | 5 | 15 | 22 | 14 | 8 | 3 | 2 |
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
import Language.C.Clang
import Language.C.Clang.Cursor.Typed
import Control.Lens
import qualified Data.ByteString.Char8 as BS
import System.Environment
import Data.Monoid ((<>))
main :: IO ()
main = do
args <- getArgs
case args of
path : clangArgs -> do
idx <- createIndex
tu <- parseTranslationUnit idx path clangArgs
let funDecs =
cursorDescendantsF -- fold over cursors recursively
. folding (matchKind @'FunctionDecl) -- find only FunctionDecls...
. filtered (isFromMainFile . rangeStart . cursorExtent) -- ...that are actually in the given file
. to (\funDec -> cursorSpelling funDec <> " :: " <> typeSpelling (cursorType funDec))
BS.putStrLn $ BS.unlines (translationUnitCursor tu ^.. funDecs)
_ -> putStrLn "usage: list-fun-types path [clang opts]"
|
chpatrick/clang-lens
|
examples/ListTypes.hs
|
apache-2.0
| 1,044 | 0 | 22 | 308 | 224 | 118 | 106 | 23 | 2 |
module Cassandra_Client(get_slice,get_column,get_column_count,insert,batch_insert,batch_insert_blocking,remove,get_slice_super,get_superColumn,batch_insert_superColumn,batch_insert_superColumn_blocking) where
import FacebookService_Client
import Data.IORef
import Thrift
import Data.Generics
import Control.Exception
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Int
import Cassandra_Types
import Cassandra
seqid = newIORef 0
get_slice (ip,op) arg_tablename arg_key arg_columnFamily_column arg_start arg_count = do
send_get_slice op arg_tablename arg_key arg_columnFamily_column arg_start arg_count
recv_get_slice ip
send_get_slice op arg_tablename arg_key arg_columnFamily_column arg_start arg_count = do
seq <- seqid
seqn <- readIORef seq
writeMessageBegin op ("get_slice", M_CALL, seqn)
write_Get_slice_args op (Get_slice_args{f_Get_slice_args_tablename=Just arg_tablename,f_Get_slice_args_key=Just arg_key,f_Get_slice_args_columnFamily_column=Just arg_columnFamily_column,f_Get_slice_args_start=Just arg_start,f_Get_slice_args_count=Just arg_count})
writeMessageEnd op
tflush (getTransport op)
recv_get_slice ip = do
(fname, mtype, rseqid) <- readMessageBegin ip
if mtype == M_EXCEPTION then do
x <- readAppExn ip
readMessageEnd ip
throwDyn x
else return ()
res <- read_Get_slice_result ip
readMessageEnd ip
case f_Get_slice_result_success res of
Just v -> return v
Nothing -> do
throwDyn (AppExn AE_MISSING_RESULT "get_slice failed: unknown result")
get_column (ip,op) arg_tablename arg_key arg_columnFamily_column = do
send_get_column op arg_tablename arg_key arg_columnFamily_column
recv_get_column ip
send_get_column op arg_tablename arg_key arg_columnFamily_column = do
seq <- seqid
seqn <- readIORef seq
writeMessageBegin op ("get_column", M_CALL, seqn)
write_Get_column_args op (Get_column_args{f_Get_column_args_tablename=Just arg_tablename,f_Get_column_args_key=Just arg_key,f_Get_column_args_columnFamily_column=Just arg_columnFamily_column})
writeMessageEnd op
tflush (getTransport op)
recv_get_column ip = do
(fname, mtype, rseqid) <- readMessageBegin ip
if mtype == M_EXCEPTION then do
x <- readAppExn ip
readMessageEnd ip
throwDyn x
else return ()
res <- read_Get_column_result ip
readMessageEnd ip
case f_Get_column_result_success res of
Just v -> return v
Nothing -> do
throwDyn (AppExn AE_MISSING_RESULT "get_column failed: unknown result")
get_column_count (ip,op) arg_tablename arg_key arg_columnFamily_column = do
send_get_column_count op arg_tablename arg_key arg_columnFamily_column
recv_get_column_count ip
send_get_column_count op arg_tablename arg_key arg_columnFamily_column = do
seq <- seqid
seqn <- readIORef seq
writeMessageBegin op ("get_column_count", M_CALL, seqn)
write_Get_column_count_args op (Get_column_count_args{f_Get_column_count_args_tablename=Just arg_tablename,f_Get_column_count_args_key=Just arg_key,f_Get_column_count_args_columnFamily_column=Just arg_columnFamily_column})
writeMessageEnd op
tflush (getTransport op)
recv_get_column_count ip = do
(fname, mtype, rseqid) <- readMessageBegin ip
if mtype == M_EXCEPTION then do
x <- readAppExn ip
readMessageEnd ip
throwDyn x
else return ()
res <- read_Get_column_count_result ip
readMessageEnd ip
case f_Get_column_count_result_success res of
Just v -> return v
Nothing -> do
throwDyn (AppExn AE_MISSING_RESULT "get_column_count failed: unknown result")
insert (ip,op) arg_tablename arg_key arg_columnFamily_column arg_cellData arg_timestamp = do
send_insert op arg_tablename arg_key arg_columnFamily_column arg_cellData arg_timestamp
send_insert op arg_tablename arg_key arg_columnFamily_column arg_cellData arg_timestamp = do
seq <- seqid
seqn <- readIORef seq
writeMessageBegin op ("insert", M_CALL, seqn)
write_Insert_args op (Insert_args{f_Insert_args_tablename=Just arg_tablename,f_Insert_args_key=Just arg_key,f_Insert_args_columnFamily_column=Just arg_columnFamily_column,f_Insert_args_cellData=Just arg_cellData,f_Insert_args_timestamp=Just arg_timestamp})
writeMessageEnd op
tflush (getTransport op)
batch_insert (ip,op) arg_batchMutation = do
send_batch_insert op arg_batchMutation
send_batch_insert op arg_batchMutation = do
seq <- seqid
seqn <- readIORef seq
writeMessageBegin op ("batch_insert", M_CALL, seqn)
write_Batch_insert_args op (Batch_insert_args{f_Batch_insert_args_batchMutation=Just arg_batchMutation})
writeMessageEnd op
tflush (getTransport op)
batch_insert_blocking (ip,op) arg_batchMutation = do
send_batch_insert_blocking op arg_batchMutation
recv_batch_insert_blocking ip
send_batch_insert_blocking op arg_batchMutation = do
seq <- seqid
seqn <- readIORef seq
writeMessageBegin op ("batch_insert_blocking", M_CALL, seqn)
write_Batch_insert_blocking_args op (Batch_insert_blocking_args{f_Batch_insert_blocking_args_batchMutation=Just arg_batchMutation})
writeMessageEnd op
tflush (getTransport op)
recv_batch_insert_blocking ip = do
(fname, mtype, rseqid) <- readMessageBegin ip
if mtype == M_EXCEPTION then do
x <- readAppExn ip
readMessageEnd ip
throwDyn x
else return ()
res <- read_Batch_insert_blocking_result ip
readMessageEnd ip
case f_Batch_insert_blocking_result_success res of
Just v -> return v
Nothing -> do
throwDyn (AppExn AE_MISSING_RESULT "batch_insert_blocking failed: unknown result")
remove (ip,op) arg_tablename arg_key arg_columnFamily_column = do
send_remove op arg_tablename arg_key arg_columnFamily_column
send_remove op arg_tablename arg_key arg_columnFamily_column = do
seq <- seqid
seqn <- readIORef seq
writeMessageBegin op ("remove", M_CALL, seqn)
write_Remove_args op (Remove_args{f_Remove_args_tablename=Just arg_tablename,f_Remove_args_key=Just arg_key,f_Remove_args_columnFamily_column=Just arg_columnFamily_column})
writeMessageEnd op
tflush (getTransport op)
get_slice_super (ip,op) arg_tablename arg_key arg_columnFamily_superColumnName arg_start arg_count = do
send_get_slice_super op arg_tablename arg_key arg_columnFamily_superColumnName arg_start arg_count
recv_get_slice_super ip
send_get_slice_super op arg_tablename arg_key arg_columnFamily_superColumnName arg_start arg_count = do
seq <- seqid
seqn <- readIORef seq
writeMessageBegin op ("get_slice_super", M_CALL, seqn)
write_Get_slice_super_args op (Get_slice_super_args{f_Get_slice_super_args_tablename=Just arg_tablename,f_Get_slice_super_args_key=Just arg_key,f_Get_slice_super_args_columnFamily_superColumnName=Just arg_columnFamily_superColumnName,f_Get_slice_super_args_start=Just arg_start,f_Get_slice_super_args_count=Just arg_count})
writeMessageEnd op
tflush (getTransport op)
recv_get_slice_super ip = do
(fname, mtype, rseqid) <- readMessageBegin ip
if mtype == M_EXCEPTION then do
x <- readAppExn ip
readMessageEnd ip
throwDyn x
else return ()
res <- read_Get_slice_super_result ip
readMessageEnd ip
case f_Get_slice_super_result_success res of
Just v -> return v
Nothing -> do
throwDyn (AppExn AE_MISSING_RESULT "get_slice_super failed: unknown result")
get_superColumn (ip,op) arg_tablename arg_key arg_columnFamily = do
send_get_superColumn op arg_tablename arg_key arg_columnFamily
recv_get_superColumn ip
send_get_superColumn op arg_tablename arg_key arg_columnFamily = do
seq <- seqid
seqn <- readIORef seq
writeMessageBegin op ("get_superColumn", M_CALL, seqn)
write_Get_superColumn_args op (Get_superColumn_args{f_Get_superColumn_args_tablename=Just arg_tablename,f_Get_superColumn_args_key=Just arg_key,f_Get_superColumn_args_columnFamily=Just arg_columnFamily})
writeMessageEnd op
tflush (getTransport op)
recv_get_superColumn ip = do
(fname, mtype, rseqid) <- readMessageBegin ip
if mtype == M_EXCEPTION then do
x <- readAppExn ip
readMessageEnd ip
throwDyn x
else return ()
res <- read_Get_superColumn_result ip
readMessageEnd ip
case f_Get_superColumn_result_success res of
Just v -> return v
Nothing -> do
throwDyn (AppExn AE_MISSING_RESULT "get_superColumn failed: unknown result")
batch_insert_superColumn (ip,op) arg_batchMutationSuper = do
send_batch_insert_superColumn op arg_batchMutationSuper
send_batch_insert_superColumn op arg_batchMutationSuper = do
seq <- seqid
seqn <- readIORef seq
writeMessageBegin op ("batch_insert_superColumn", M_CALL, seqn)
write_Batch_insert_superColumn_args op (Batch_insert_superColumn_args{f_Batch_insert_superColumn_args_batchMutationSuper=Just arg_batchMutationSuper})
writeMessageEnd op
tflush (getTransport op)
batch_insert_superColumn_blocking (ip,op) arg_batchMutationSuper = do
send_batch_insert_superColumn_blocking op arg_batchMutationSuper
recv_batch_insert_superColumn_blocking ip
send_batch_insert_superColumn_blocking op arg_batchMutationSuper = do
seq <- seqid
seqn <- readIORef seq
writeMessageBegin op ("batch_insert_superColumn_blocking", M_CALL, seqn)
write_Batch_insert_superColumn_blocking_args op (Batch_insert_superColumn_blocking_args{f_Batch_insert_superColumn_blocking_args_batchMutationSuper=Just arg_batchMutationSuper})
writeMessageEnd op
tflush (getTransport op)
recv_batch_insert_superColumn_blocking ip = do
(fname, mtype, rseqid) <- readMessageBegin ip
if mtype == M_EXCEPTION then do
x <- readAppExn ip
readMessageEnd ip
throwDyn x
else return ()
res <- read_Batch_insert_superColumn_blocking_result ip
readMessageEnd ip
case f_Batch_insert_superColumn_blocking_result_success res of
Just v -> return v
Nothing -> do
throwDyn (AppExn AE_MISSING_RESULT "batch_insert_superColumn_blocking failed: unknown result")
|
toddlipcon/cassandra
|
interface/hs/Cassandra_Client.hs
|
apache-2.0
| 9,818 | 0 | 14 | 1,313 | 2,514 | 1,189 | 1,325 | 209 | 3 |
-- | Build instance tycons for the PData and PDatas type families.
--
-- TODO: the PData and PDatas cases are very similar.
-- We should be able to factor out the common parts.
module Vectorise.Generic.PData
( buildPDataTyCon
, buildPDatasTyCon )
where
import GhcPrelude
import Vectorise.Monad
import Vectorise.Builtins
import Vectorise.Generic.Description
import Vectorise.Utils
import Vectorise.Env( GlobalEnv( global_fam_inst_env ) )
import BasicTypes ( SourceText(..) )
import BuildTyCl
import DataCon
import TyCon
import Type
import FamInst
import FamInstEnv
import TcMType
import Name
import Util
import MonadUtils
import Control.Monad
-- buildPDataTyCon ------------------------------------------------------------
-- | Build the PData instance tycon for a given type constructor.
buildPDataTyCon :: TyCon -> TyCon -> SumRepr -> VM FamInst
buildPDataTyCon orig_tc vect_tc repr
= fixV $ \fam_inst ->
do let repr_tc = dataFamInstRepTyCon fam_inst
name' <- mkLocalisedName mkPDataTyConOcc orig_name
rhs <- buildPDataTyConRhs orig_name vect_tc repr_tc repr
pdata <- builtin pdataTyCon
buildDataFamInst name' pdata vect_tc rhs
where
orig_name = tyConName orig_tc
buildDataFamInst :: Name -> TyCon -> TyCon -> AlgTyConRhs -> VM FamInst
buildDataFamInst name' fam_tc vect_tc rhs
= do { axiom_name <- mkDerivedName mkInstTyCoOcc name'
; (_, tyvars') <- liftDs $ freshenTyVarBndrs tyvars
; let ax = mkSingleCoAxiom Representational axiom_name tyvars' [] fam_tc pat_tys rep_ty
tys' = mkTyVarTys tyvars'
rep_ty = mkTyConApp rep_tc tys'
pat_tys = [mkTyConApp vect_tc tys']
rep_tc = mkAlgTyCon name'
(mkTyConBindersPreferAnon tyvars' liftedTypeKind)
liftedTypeKind
(map (const Nominal) tyvars')
Nothing
[] -- no stupid theta
rhs
(DataFamInstTyCon ax fam_tc pat_tys)
False -- not GADT syntax
; liftDs $ newFamInst (DataFamilyInst rep_tc) ax }
where
tyvars = tyConTyVars vect_tc
buildPDataTyConRhs :: Name -> TyCon -> TyCon -> SumRepr -> VM AlgTyConRhs
buildPDataTyConRhs orig_name vect_tc repr_tc repr
= do data_con <- buildPDataDataCon orig_name vect_tc repr_tc repr
return $ mkDataTyConRhs [data_con]
buildPDataDataCon :: Name -> TyCon -> TyCon -> SumRepr -> VM DataCon
buildPDataDataCon orig_name vect_tc repr_tc repr
= do let tvs = tyConTyVars vect_tc
dc_name <- mkLocalisedName mkPDataDataConOcc orig_name
comp_tys <- mkSumTys repr_sel_ty mkPDataType repr
fam_envs <- readGEnv global_fam_inst_env
rep_nm <- liftDs $ newTyConRepName dc_name
let univ_tvbs = mkTyVarBinders Specified tvs
tag_map = mkTyConTagMap repr_tc
liftDs $ buildDataCon fam_envs dc_name
False -- not infix
rep_nm
(map (const no_bang) comp_tys)
(Just $ map (const HsLazy) comp_tys)
[] -- no field labels
tvs
[] -- no existentials
univ_tvbs
[] -- no eq spec
[] -- no context
comp_tys
(mkFamilyTyConApp repr_tc (mkTyVarTys tvs))
repr_tc
tag_map
where
no_bang = HsSrcBang NoSourceText NoSrcUnpack NoSrcStrict
-- buildPDatasTyCon -----------------------------------------------------------
-- | Build the PDatas instance tycon for a given type constructor.
buildPDatasTyCon :: TyCon -> TyCon -> SumRepr -> VM FamInst
buildPDatasTyCon orig_tc vect_tc repr
= fixV $ \fam_inst ->
do let repr_tc = dataFamInstRepTyCon fam_inst
name' <- mkLocalisedName mkPDatasTyConOcc orig_name
rhs <- buildPDatasTyConRhs orig_name vect_tc repr_tc repr
pdatas <- builtin pdatasTyCon
buildDataFamInst name' pdatas vect_tc rhs
where
orig_name = tyConName orig_tc
buildPDatasTyConRhs :: Name -> TyCon -> TyCon -> SumRepr -> VM AlgTyConRhs
buildPDatasTyConRhs orig_name vect_tc repr_tc repr
= do data_con <- buildPDatasDataCon orig_name vect_tc repr_tc repr
return $ mkDataTyConRhs [data_con]
buildPDatasDataCon :: Name -> TyCon -> TyCon -> SumRepr -> VM DataCon
buildPDatasDataCon orig_name vect_tc repr_tc repr
= do let tvs = tyConTyVars vect_tc
dc_name <- mkLocalisedName mkPDatasDataConOcc orig_name
comp_tys <- mkSumTys repr_sels_ty mkPDatasType repr
fam_envs <- readGEnv global_fam_inst_env
rep_nm <- liftDs $ newTyConRepName dc_name
let univ_tvbs = mkTyVarBinders Specified tvs
tag_map = mkTyConTagMap repr_tc
liftDs $ buildDataCon fam_envs dc_name
False -- not infix
rep_nm
(map (const no_bang) comp_tys)
(Just $ map (const HsLazy) comp_tys)
[] -- no field labels
tvs
[] -- no existentials
univ_tvbs
[] -- no eq spec
[] -- no context
comp_tys
(mkFamilyTyConApp repr_tc (mkTyVarTys tvs))
repr_tc
tag_map
where
no_bang = HsSrcBang NoSourceText NoSrcUnpack NoSrcStrict
-- Utils ----------------------------------------------------------------------
-- | Flatten a SumRepr into a list of data constructor types.
mkSumTys
:: (SumRepr -> Type)
-> (Type -> VM Type)
-> SumRepr
-> VM [Type]
mkSumTys repr_selX_ty mkTc repr
= sum_tys repr
where
sum_tys EmptySum = return []
sum_tys (UnarySum r) = con_tys r
sum_tys d@(Sum { repr_cons = cons })
= liftM (repr_selX_ty d :) (concatMapM con_tys cons)
con_tys (ConRepr _ r) = prod_tys r
prod_tys EmptyProd = return []
prod_tys (UnaryProd r) = liftM singleton (comp_ty r)
prod_tys (Prod { repr_comps = comps }) = mapM comp_ty comps
comp_ty r = mkTc (compOrigType r)
{-
mk_fam_inst :: TyCon -> TyCon -> (TyCon, [Type])
mk_fam_inst fam_tc arg_tc
= (fam_tc, [mkTyConApp arg_tc . mkTyVarTys $ tyConTyVars arg_tc])
-}
|
shlevy/ghc
|
compiler/vectorise/Vectorise/Generic/PData.hs
|
bsd-3-clause
| 6,840 | 0 | 14 | 2,363 | 1,390 | 695 | 695 | 132 | 5 |
{-
(c) The University of Glasgow, 2004-2006
Module
~~~~~~~~~~
Simply the name of a module, represented as a FastString.
These are Uniquable, hence we can build Maps with Modules as
the keys.
-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Eta.BasicTypes.Module
(
-- * The ModuleName type
ModuleName,
pprModuleName,
moduleNameFS,
moduleNameString,
moduleNameSlashes, moduleNameColons,
moduleStableString,
moduleFreeHoles,
moduleIsDefinite,
mkModuleName,
mkModuleNameFS,
stableModuleNameCmp,
-- * The UnitId type
ComponentId(..),
UnitId(..),
unitIdFS,
unitIdKey,
IndefUnitId(..),
IndefModule(..),
indefUnitIdToUnitId,
indefModuleToModule,
InstalledUnitId(..),
toInstalledUnitId,
ShHoleSubst,
unitIdIsDefinite,
unitIdString,
unitIdFreeHoles,
newUnitId,
newIndefUnitId,
newSimpleUnitId,
hashUnitId,
fsToUnitId,
stringToUnitId,
stableUnitIdCmp,
-- * HOLE renaming
renameHoleUnitId,
renameHoleModule,
renameHoleUnitId',
renameHoleModule',
-- * Generalization
splitModuleInsts,
splitUnitIdInsts,
generalizeIndefUnitId,
generalizeIndefModule,
-- * Parsers
parseModuleName,
parseUnitId,
parseComponentId,
parseModuleId,
parseModSubst,
-- * Wired-in UnitIds
-- $wired_in_packages
primUnitId,
integerUnitId,
baseUnitId,
rtsUnitId,
thUnitId,
etaMetaId,
dphSeqUnitId,
dphParUnitId,
mainUnitId,
thisGhcUnitId,
javaUnitId, javaUnitFs,
isHoleModule,
interactiveUnitId, isInteractiveModule,
wiredInUnitIds,
-- * The Module type
Module(Module),
moduleUnitId, moduleName,
pprModule,
mkModule,
mkHoleModule,
stableModuleCmp,
HasModule(..),
ContainsModule(..),
-- * Virgin modules
-- VirginModule,
-- VirginUnitId,
-- VirginModuleEnv,
--
-- -- * Hole module
-- HoleModule,
-- * Installed unit ids and modules
InstalledModule(..),
InstalledModuleEnv,
installedModuleEq,
installedUnitIdEq,
installedUnitIdString,
fsToInstalledUnitId,
componentIdToInstalledUnitId,
stringToInstalledUnitId,
emptyInstalledModuleEnv,
lookupInstalledModuleEnv,
extendInstalledModuleEnv,
filterInstalledModuleEnv,
delInstalledModuleEnv,
DefUnitId(..),
-- * The ModuleLocation type
ModLocation(..),
addBootSuffix, addBootSuffix_maybe, addBootSuffixLocn,
-- * Module mappings
ModuleEnv,
elemModuleEnv, extendModuleEnv, extendModuleEnvList,
extendModuleEnvList_C, plusModuleEnv_C,
delModuleEnvList, delModuleEnv, plusModuleEnv, lookupModuleEnv,
lookupWithDefaultModuleEnv, mapModuleEnv, mkModuleEnv, emptyModuleEnv,
moduleEnvKeys, moduleEnvElts, moduleEnvToList,
unitModuleEnv, isEmptyModuleEnv,
extendModuleEnvWith, filterModuleEnv,
-- * ModuleName mappings
ModuleNameEnv, DModuleNameEnv,
-- * Sets of Modules
ModuleSet,
emptyModuleSet, mkModuleSet, moduleSetElts, extendModuleSet, elemModuleSet,
delModuleSet
) where
import Eta.PackageDb (BinaryStringRep(..), DbUnitIdModuleRep(..), DbModule(..), DbUnitId(..))
import Eta.Utils.Outputable
import Eta.BasicTypes.Unique
import Eta.Utils.UniqFM
import Eta.Utils.UniqDFM
import Eta.Utils.UniqDSet
import Eta.Utils.FastString
import Eta.Utils.Binary
import Eta.Utils.Util
import {-# SOURCE #-} Eta.Main.Packages
import qualified Eta.Utils.FiniteMap as Map
import Data.Data
import Data.Map (Map)
import qualified Data.Map as Map
import System.FilePath
import Data.List
import Data.Ord
import qualified Data.ByteString as BS
import qualified Data.ByteString.Unsafe as BS
import qualified Data.ByteString.Char8 as BS.Char8
import System.IO.Unsafe
import Foreign.Ptr (castPtr)
import GHC.Fingerprint
import Eta.Utils.Encoding
import qualified Text.ParserCombinators.ReadP as Parse
import Text.ParserCombinators.ReadP (ReadP, (<++))
import Data.Char (isAlphaNum)
import Control.DeepSeq
import Data.Coerce
import Data.Function
import Data.Set (Set)
import qualified Data.Set as Set
import {-# SOURCE #-} Eta.Main.DynFlags (DynFlags)
-- Note [The identifier lexicon]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Unit IDs, installed package IDs, ABI hashes, package names,
-- versions, there are a *lot* of different identifiers for closely
-- related things. What do they all mean? Here's what. (See also
-- https://ghc.haskell.org/trac/ghc/wiki/Commentary/Packages/Concepts )
--
-- THE IMPORTANT ONES
--
-- ComponentId: An opaque identifier provided by Cabal, which should
-- uniquely identify such things as the package name, the package
-- version, the name of the component, the hash of the source code
-- tarball, the selected Cabal flags, GHC flags, direct dependencies of
-- the component. These are very similar to InstalledPackageId, but
-- an 'InstalledPackageId' implies that it identifies a package, while
-- a package may install multiple components with different
-- 'ComponentId's.
-- - Same as Distribution.Package.ComponentId
--
-- UnitId/InstalledUnitId: A ComponentId + a mapping from hole names
-- (ModuleName) to Modules. This is how the compiler identifies instantiated
-- components, and also is the main identifier by which GHC identifies things.
-- - When Backpack is not being used, UnitId = ComponentId.
-- this means a useful fiction for end-users is that there are
-- only ever ComponentIds, and some ComponentIds happen to have
-- more information (UnitIds).
-- - Same as Language.Eta.Meta.Syntax:PkgName, see
-- https://ghc.haskell.org/trac/ghc/ticket/10279
-- - The same as PackageKey in GHC 7.10 (we renamed it because
-- they don't necessarily identify packages anymore.)
-- - Same as -this-package-key/-package-name flags
-- - An InstalledUnitId corresponds to an actual package which
-- we have installed on disk. It could be definite or indefinite,
-- but if it's indefinite, it has nothing instantiated (we
-- never install partially instantiated units.)
--
-- Module/InstalledModule: A UnitId/InstalledUnitId + ModuleName. This is how
-- the compiler identifies modules (e.g. a Name is a Module + OccName)
-- - Same as Language.Eta.Meta.Syntax:Module
--
-- THE LESS IMPORTANT ONES
--
-- PackageName: The "name" field in a Cabal file, something like "lens".
-- - Same as Distribution.Package.PackageName
-- - DIFFERENT FROM Language.Eta.Meta.Syntax:PkgName, see
-- https://ghc.haskell.org/trac/ghc/ticket/10279
-- - DIFFERENT FROM -package-name flag
-- - DIFFERENT FROM the 'name' field in an installed package
-- information. This field could more accurately be described
-- as a munged package name: when it's for the main library
-- it is the same as the package name, but if it's an internal
-- library it's a munged combination of the package name and
-- the component name.
--
-- LEGACY ONES
--
-- InstalledPackageId: This is what we used to call ComponentId.
-- It's a still pretty useful concept for packages that have only
-- one library; in that case the logical InstalledPackageId =
-- ComponentId. Also, the Cabal nix-local-build continues to
-- compute an InstalledPackageId which is then forcibly used
-- for all components in a package. This means that if a dependency
-- from one component in a package changes, the InstalledPackageId
-- changes: you don't get as fine-grained dependency tracking,
-- but it means your builds are hermetic. Eventually, Cabal will
-- deal completely in components and we can get rid of this.
--
-- PackageKey: This is what we used to call UnitId. We ditched
-- "Package" from the name when we realized that you might want to
-- assign different "PackageKeys" to components from the same package.
-- (For a brief, non-released period of time, we also called these
-- UnitKeys).
{-
************************************************************************
* *
\subsection{Module locations}
* *
************************************************************************
-}
-- | Where a module lives on the file system: the actual locations
-- of the .hs, .hi and .o files, if we have them
data ModLocation
= ModLocation {
ml_hs_file :: Maybe FilePath,
-- The source file, if we have one. Package modules
-- probably don't have source files.
ml_hi_file :: FilePath,
-- Where the .hi file is, whether or not it exists
-- yet. Always of form foo.hi, even if there is an
-- hi-boot file (we add the -boot suffix later)
ml_obj_file :: FilePath
-- Where the .o file is, whether or not it exists yet.
-- (might not exist either because the module hasn't
-- been compiled yet, or because it is part of a
-- package with a .a file)
} deriving Show
instance Outputable ModLocation where
ppr = text . show
{-
For a module in another package, the hs_file and obj_file
components of ModLocation are undefined.
The locations specified by a ModLocation may or may not
correspond to actual files yet: for example, even if the object
file doesn't exist, the ModLocation still contains the path to
where the object file will reside if/when it is created.
-}
addBootSuffix :: FilePath -> FilePath
-- ^ Add the @-boot@ suffix to .hs, .hi and .o files
addBootSuffix path = path ++ "-boot"
addBootSuffix_maybe :: Bool -> FilePath -> FilePath
-- ^ Add the @-boot@ suffix if the @Bool@ argument is @True@
addBootSuffix_maybe is_boot path
| is_boot = addBootSuffix path
| otherwise = path
addBootSuffixLocn :: ModLocation -> ModLocation
-- ^ Add the @-boot@ suffix to all file paths associated with the module
addBootSuffixLocn locn
= locn { ml_hs_file = fmap addBootSuffix (ml_hs_file locn)
, ml_hi_file = addBootSuffix (ml_hi_file locn)
, ml_obj_file = addBootSuffix (ml_obj_file locn) }
{-
************************************************************************
* *
\subsection{The name of a module}
* *
************************************************************************
-}
-- | A ModuleName is essentially a simple string, e.g. @Data.List@.
newtype ModuleName = ModuleName FastString
instance Uniquable ModuleName where
getUnique (ModuleName nm) = getUnique nm
instance Eq ModuleName where
nm1 == nm2 = getUnique nm1 == getUnique nm2
instance Ord ModuleName where
nm1 `compare` nm2 = stableModuleNameCmp nm1 nm2
instance Outputable ModuleName where
ppr = pprModuleName
instance Binary ModuleName where
put_ bh (ModuleName fs) = put_ bh fs
get bh = do fs <- get bh; return (ModuleName fs)
instance BinaryStringRep ModuleName where
fromStringRep = mkModuleNameFS . mkFastStringByteString
toStringRep = fastStringToByteString . moduleNameFS
instance Data ModuleName where
-- don't traverse?
toConstr _ = abstractConstr "ModuleName"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "ModuleName"
instance NFData ModuleName where
rnf x = x `seq` ()
stableModuleNameCmp :: ModuleName -> ModuleName -> Ordering
-- ^ Compares module names lexically, rather than by their 'Unique's
stableModuleNameCmp n1 n2 = moduleNameFS n1 `compare` moduleNameFS n2
pprModuleName :: ModuleName -> SDoc
pprModuleName (ModuleName nm) =
getPprStyle $ \ sty ->
if codeStyle sty
then ztext (zEncodeFS nm)
else ftext nm
moduleNameFS :: ModuleName -> FastString
moduleNameFS (ModuleName mod) = mod
moduleNameString :: ModuleName -> String
moduleNameString (ModuleName mod) = unpackFS mod
-- | Get a string representation of a 'Module' that's unique and stable
-- across recompilations.
-- eg. "$aeson_70dylHtv1FFGeai1IoxcQr$Data.Aeson.Types.Internal"
moduleStableString :: Module -> String
moduleStableString Module{..} =
"$" ++ unitIdString moduleUnitId ++ "$" ++ moduleNameString moduleName
mkModuleName :: String -> ModuleName
mkModuleName s = ModuleName (mkFastString s)
mkModuleNameFS :: FastString -> ModuleName
mkModuleNameFS s = ModuleName s
-- |Returns the string version of the module name, with dots replaced by slashes.
--
moduleNameSlashes :: ModuleName -> String
moduleNameSlashes = dots_to_slashes . moduleNameString
where dots_to_slashes = map (\c -> if c == '.' then pathSeparator else c)
-- |Returns the string version of the module name, with dots replaced by underscores.
--
moduleNameColons :: ModuleName -> String
moduleNameColons = dots_to_colons . moduleNameString
where dots_to_colons = map (\c -> if c == '.' then ':' else c)
{-
************************************************************************
* *
\subsection{A fully qualified module}
* *
************************************************************************
-}
-- | A Module is a pair of a 'PackageKey' and a 'ModuleName'.
--
-- Module variables (i.e. @<H>@) which can be instantiated to a
-- specific module at some later point in time are represented
-- with 'moduleUnitId' set to 'holeUnitId' (this allows us to
-- avoid having to make 'moduleUnitId' a partial operation.)
--
data Module = Module {
moduleUnitId :: !UnitId, -- pkg-1.0
moduleName :: !ModuleName -- A.B.C
}
deriving (Eq, Ord)
-- | Calculate the free holes of a 'Module'. If this set is non-empty,
-- this module was defined in an indefinite library that had required
-- signatures.
--
-- If a module has free holes, that means that substitutions can operate on it;
-- if it has no free holes, substituting over a module has no effect.
moduleFreeHoles :: Module -> UniqDSet ModuleName
moduleFreeHoles m
| isHoleModule m = unitUniqDSet (moduleName m)
| otherwise = unitIdFreeHoles (moduleUnitId m)
-- | A 'Module' is definite if it has no free holes.
moduleIsDefinite :: Module -> Bool
moduleIsDefinite = isEmptyUniqDSet . moduleFreeHoles
-- | Create a module variable at some 'ModuleName'.
-- See Note [Representation of module/name variables]
mkHoleModule :: ModuleName -> Module
mkHoleModule = mkModule holeUnitId
instance Uniquable Module where
getUnique (Module p n) = getUnique (unitIdFS p `appendFS` moduleNameFS n)
instance Outputable Module where
ppr = pprModule
instance Binary Module where
put_ bh (Module p n) = put_ bh p >> put_ bh n
get bh = do p <- get bh; n <- get bh; return (Module p n)
instance Data Module where
-- don't traverse?
toConstr _ = abstractConstr "Module"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "Module"
-- | This gives a stable ordering, as opposed to the Ord instance which
-- gives an ordering based on the 'Unique's of the components, which may
-- not be stable from run to run of the compiler.
stableModuleCmp :: Module -> Module -> Ordering
stableModuleCmp (Module p1 n1) (Module p2 n2)
= (p1 `stableUnitIdCmp` p2) `thenCmp`
(n1 `stableModuleNameCmp` n2)
mkModule :: UnitId -> ModuleName -> Module
mkModule = Module
pprModule :: Module -> SDoc
pprModule mod@(Module p n) = getPprStyle doc
where
doc sty
| codeStyle sty =
(if p == mainUnitId
then empty -- never qualify the main package in code
else ztext (zEncodeFS (unitIdFS p)) <> char '_')
<> pprModuleName n
| qualModule sty mod =
if isHoleModule mod
then angleBrackets (pprModuleName n)
else ppr (moduleUnitId mod) <> char ':' <> pprModuleName n
| otherwise = pprModuleName n
class ContainsModule t where
extractModule :: t -> Module
class HasModule m where
getModule :: m Module
instance DbUnitIdModuleRep InstalledUnitId ComponentId UnitId ModuleName Module where
fromDbModule (DbModule uid mod_name) = mkModule uid mod_name
fromDbModule (DbModuleVar mod_name) = mkHoleModule mod_name
fromDbUnitId (DbUnitId cid insts) = newUnitId cid insts
fromDbUnitId (DbInstalledUnitId iuid) = DefiniteUnitId (DefUnitId iuid)
-- Eta never writes to the database, so it's not needed
toDbModule = error "toDbModule: not implemented"
toDbUnitId = error "toDbUnitId: not implemented"
{-
************************************************************************
* *
\subsection{ComponentId}
* *
************************************************************************
-}
-- | A 'ComponentId' consists of the package name, package version, component
-- ID, the transitive dependencies of the component, and other information to
-- uniquely identify the source code and build configuration of a component.
--
-- This used to be known as an 'InstalledPackageId', but a package can contain
-- multiple components and a 'ComponentId' uniquely identifies a component
-- within a package. When a package only has one component, the 'ComponentId'
-- coincides with the 'InstalledPackageId'
newtype ComponentId = ComponentId FastString deriving (Eq, Ord)
instance BinaryStringRep ComponentId where
fromStringRep = ComponentId . mkFastStringByteString
toStringRep (ComponentId s) = fastStringToByteString s
instance Uniquable ComponentId where
getUnique (ComponentId n) = getUnique n
instance Outputable ComponentId where
ppr cid@(ComponentId fs) =
getPprStyle $ \sty ->
sdocWithDynFlags $ \dflags ->
case componentIdString dflags cid of
Just str | not (debugStyle sty) -> text str
_ -> ftext fs
instance Binary ComponentId where
put_ bh (ComponentId fs) = put_ bh fs
get bh = do { fs <- get bh; return (ComponentId fs) }
-- | Generate a uniquely identifying 'FastString' for a unit
-- identifier. This is a one-way function. You can rely on one special
-- property: if a unit identifier is in most general form, its 'FastString'
-- coincides with its 'ComponentId'. This hash is completely internal
-- to GHC and is not used for symbol names or file paths.
hashUnitId :: ComponentId -> [(ModuleName, Module)] -> FastString
hashUnitId cid sorted_holes =
mkFastStringByteString
. fingerprintUnitId (toStringRep cid)
$ rawHashUnitId sorted_holes
-- | Generate a hash for a sorted module substitution.
rawHashUnitId :: [(ModuleName, Module)] -> Fingerprint
rawHashUnitId sorted_holes =
fingerprintByteString
. BS.concat $ do
(m, b) <- sorted_holes
[ toStringRep m, BS.Char8.singleton ' ',
fastStringToByteString (unitIdFS (moduleUnitId b)), BS.Char8.singleton ':',
toStringRep (moduleName b), BS.Char8.singleton '\n']
fingerprintByteString :: BS.ByteString -> Fingerprint
fingerprintByteString bs = unsafePerformIO
. BS.unsafeUseAsCStringLen bs
$ \(p,l) -> fingerprintData (castPtr p) l
fingerprintUnitId :: BS.ByteString -> Fingerprint -> BS.ByteString
fingerprintUnitId prefix (Fingerprint a b)
= BS.concat
$ [ prefix
, BS.Char8.singleton '-'
, BS.Char8.pack (toBase62Padded a)
, BS.Char8.pack (toBase62Padded b) ]
{-
************************************************************************
* *
\subsection{UnitId}
* *
************************************************************************
-}
-- | A unit identifier identifies a (possibly partially) instantiated
-- library. It is primarily used as part of 'Module', which in turn
-- is used in 'Name', which is used to give names to entities when
-- typechecking.
--
-- There are two possible forms for a 'UnitId'. It can be a
-- 'DefiniteUnitId', in which case we just have a string that uniquely
-- identifies some fully compiled, installed library we have on disk.
-- However, when we are typechecking a library with missing holes,
-- we may need to instantiate a library on the fly (in which case
-- we don't have any on-disk representation.) In that case, you
-- have an 'IndefiniteUnitId', which explicitly records the
-- instantiation, so that we can substitute over it.
data UnitId
= IndefiniteUnitId {-# UNPACK #-} !IndefUnitId
| DefiniteUnitId {-# UNPACK #-} !DefUnitId
deriving (Typeable)
instance Eq UnitId where
uid1 == uid2 = unitIdKey uid1 == unitIdKey uid2
instance Uniquable UnitId where
getUnique = unitIdKey
instance Show UnitId where
show = unitIdString
instance Ord UnitId where
nm1 `compare` nm2 = stableUnitIdCmp nm1 nm2
instance Data UnitId where
-- don't traverse?
toConstr _ = abstractConstr "UnitId"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "UnitId"
instance NFData UnitId where
rnf x = x `seq` ()
instance Outputable UnitId where
ppr pk = pprUnitId pk
-- Performance: would prefer to have a NameCache like thing
instance Binary UnitId where
put_ bh (DefiniteUnitId def_uid) = do
putByte bh 0
put_ bh def_uid
put_ bh (IndefiniteUnitId indef_uid) = do
putByte bh 1
put_ bh indef_uid
get bh = do b <- getByte bh
case b of
0 -> fmap DefiniteUnitId (get bh)
_ -> fmap IndefiniteUnitId (get bh)
unitIdFS :: UnitId -> FastString
unitIdFS (IndefiniteUnitId x) = indefUnitIdFS x
unitIdFS (DefiniteUnitId (DefUnitId x)) = installedUnitIdFS x
unitIdKey :: UnitId -> Unique
unitIdKey (IndefiniteUnitId x) = indefUnitIdKey x
unitIdKey (DefiniteUnitId (DefUnitId x)) = installedUnitIdKey x
-- | Create a new simple unit identifier from a 'FastString'. Internally,
-- this is primarily used to specify wired-in unit identifiers.
fsToUnitId :: FastString -> UnitId
fsToUnitId = DefiniteUnitId . DefUnitId . InstalledUnitId
stringToUnitId :: String -> UnitId
stringToUnitId = fsToUnitId . mkFastString
unitIdString :: UnitId -> String
unitIdString = unpackFS . unitIdFS
stableUnitIdCmp :: UnitId -> UnitId -> Ordering
-- ^ Compares package ids lexically, rather than by their 'Unique's
stableUnitIdCmp p1 p2 = unitIdFS p1 `compare` unitIdFS p2
pprUnitId :: UnitId -> SDoc
pprUnitId (DefiniteUnitId uid) = ppr uid
pprUnitId (IndefiniteUnitId uid) = ppr uid
-- | Create a new, un-hashed unit identifier.
newUnitId :: ComponentId -> [(ModuleName, Module)] -> UnitId
newUnitId cid [] = newSimpleUnitId cid -- TODO: this indicates some latent bug...
newUnitId cid insts = IndefiniteUnitId $ newIndefUnitId cid insts
-- | Create a new simple unit identifier (no holes) from a 'ComponentId'.
newSimpleUnitId :: ComponentId -> UnitId
newSimpleUnitId (ComponentId fs) = fsToUnitId fs
-- | Retrieve the set of free holes of a 'UnitId'.
unitIdFreeHoles :: UnitId -> UniqDSet ModuleName
unitIdFreeHoles (IndefiniteUnitId x) = indefUnitIdFreeHoles x
-- Hashed unit ids are always fully instantiated
unitIdFreeHoles (DefiniteUnitId _) = emptyUniqDSet
-- | A 'UnitId' is definite if it has no free holes.
unitIdIsDefinite :: UnitId -> Bool
unitIdIsDefinite = isEmptyUniqDSet . unitIdFreeHoles
-- | A unit identifier which identifies an indefinite
-- library (with holes) that has been *on-the-fly* instantiated
-- with a substitution 'indefUnitIdInsts'. In fact, an indefinite
-- unit identifier could have no holes, but we haven't gotten
-- around to compiling the actual library yet.
--
-- An indefinite unit identifier pretty-prints to something like
-- @p[H=<H>,A=aimpl:A>]@ (@p@ is the 'ComponentId', and the
-- brackets enclose the module substitution).
data IndefUnitId
= IndefUnitId {
-- | A private, uniquely identifying representation of
-- a UnitId. This string is completely private to GHC
-- and is just used to get a unique; in particular, we don't use it for
-- symbols (indefinite libraries are not compiled).
indefUnitIdFS :: FastString,
-- | Cached unique of 'unitIdFS'.
indefUnitIdKey :: Unique,
-- | The component identity of the indefinite library that
-- is being instantiated.
indefUnitIdComponentId :: !ComponentId,
-- | The sorted (by 'ModuleName') instantiations of this library.
indefUnitIdInsts :: ![(ModuleName, Module)],
-- | A cache of the free module variables of 'unitIdInsts'.
-- This lets us efficiently tell if a 'UnitId' has been
-- fully instantiated (free module variables are empty)
-- and whether or not a substitution can have any effect.
indefUnitIdFreeHoles :: UniqDSet ModuleName
} deriving (Typeable)
instance Eq IndefUnitId where
u1 == u2 = indefUnitIdKey u1 == indefUnitIdKey u2
instance Ord IndefUnitId where
u1 `compare` u2 = indefUnitIdFS u1 `compare` indefUnitIdFS u2
instance Binary IndefUnitId where
put_ bh indef = do
put_ bh (indefUnitIdComponentId indef)
put_ bh (indefUnitIdInsts indef)
get bh = do
cid <- get bh
insts <- get bh
let fs = hashUnitId cid insts
return IndefUnitId {
indefUnitIdComponentId = cid,
indefUnitIdInsts = insts,
indefUnitIdFreeHoles = unionManyUniqDSets (map (moduleFreeHoles.snd) insts),
indefUnitIdFS = fs,
indefUnitIdKey = getUnique fs
}
instance Outputable IndefUnitId where
ppr uid =
-- getPprStyle $ \sty ->
ppr cid <>
(if not (null insts) -- pprIf
then
brackets (hcat
(punctuate comma $
[ ppr modname <> text "=" <> ppr m
| (modname, m) <- insts]))
else empty)
where
cid = indefUnitIdComponentId uid
insts = indefUnitIdInsts uid
-- | Create a new 'IndefUnitId' given an explicit module substitution.
newIndefUnitId :: ComponentId -> [(ModuleName, Module)] -> IndefUnitId
newIndefUnitId cid insts =
IndefUnitId {
indefUnitIdComponentId = cid,
indefUnitIdInsts = sorted_insts,
indefUnitIdFreeHoles = unionManyUniqDSets (map (moduleFreeHoles.snd) insts),
indefUnitIdFS = fs,
indefUnitIdKey = getUnique fs
}
where
fs = hashUnitId cid sorted_insts
sorted_insts = sortBy (stableModuleNameCmp `on` fst) insts
-- | Injects an 'IndefUnitId' (indefinite library which
-- was on-the-fly instantiated) to a 'UnitId' (either
-- an indefinite or definite library).
indefUnitIdToUnitId :: DynFlags -> IndefUnitId -> UnitId
indefUnitIdToUnitId dflags iuid =
-- NB: suppose that we want to compare the indefinite
-- unit id p[H=impl:H] against p+abcd (where p+abcd
-- happens to be the existing, installed version of
-- p[H=impl:H]. If we *only* wrap in p[H=impl:H]
-- IndefiniteUnitId, they won't compare equal; only
-- after improvement will the equality hold.
improveUnitId (getPackageConfigMap dflags) $
IndefiniteUnitId iuid
data IndefModule = IndefModule {
indefModuleUnitId :: IndefUnitId,
indefModuleName :: ModuleName
} deriving (Typeable, Eq, Ord)
instance Outputable IndefModule where
ppr (IndefModule uid m) =
ppr uid <> char ':' <> ppr m
-- | Injects an 'IndefModule' to 'Module' (see also
-- 'indefUnitIdToUnitId'.
indefModuleToModule :: DynFlags -> IndefModule -> Module
indefModuleToModule dflags (IndefModule iuid mod_name) =
mkModule (indefUnitIdToUnitId dflags iuid) mod_name
-- | An installed unit identifier identifies a library which has
-- been installed to the package database. These strings are
-- provided to us via the @-this-unit-id@ flag. The library
-- in question may be definite or indefinite; if it is indefinite,
-- none of the holes have been filled (we never install partially
-- instantiated libraries.) Put another way, an installed unit id
-- is either fully instantiated, or not instantiated at all.
--
-- Installed unit identifiers look something like @p+af23SAj2dZ219@,
-- or maybe just @p@ if they don't use Backpack.
newtype InstalledUnitId =
InstalledUnitId {
-- | The full hashed unit identifier, including the component id
-- and the hash.
installedUnitIdFS :: FastString
}
deriving (Typeable)
instance Binary InstalledUnitId where
put_ bh (InstalledUnitId fs) = put_ bh fs
get bh = do fs <- get bh; return (InstalledUnitId fs)
instance BinaryStringRep InstalledUnitId where
fromStringRep bs = InstalledUnitId (mkFastStringByteString bs)
-- Eta doesn't write to database
toStringRep = error "BinaryStringRep InstalledUnitId: not implemented"
instance Eq InstalledUnitId where
uid1 == uid2 = installedUnitIdKey uid1 == installedUnitIdKey uid2
instance Ord InstalledUnitId where
u1 `compare` u2 = installedUnitIdFS u1 `compare` installedUnitIdFS u2
instance Uniquable InstalledUnitId where
getUnique = installedUnitIdKey
instance Outputable InstalledUnitId where
ppr uid@(InstalledUnitId fs) =
getPprStyle $ \sty ->
sdocWithDynFlags $ \dflags ->
case displayInstalledUnitId dflags uid of
Just str | not (debugStyle sty) -> text str
_ -> ftext fs
fsToInstalledUnitId :: FastString -> InstalledUnitId
fsToInstalledUnitId fs = InstalledUnitId fs
componentIdToInstalledUnitId :: ComponentId -> InstalledUnitId
componentIdToInstalledUnitId (ComponentId fs) = fsToInstalledUnitId fs
stringToInstalledUnitId :: String -> InstalledUnitId
stringToInstalledUnitId = fsToInstalledUnitId . mkFastString
installedUnitIdKey :: InstalledUnitId -> Unique
installedUnitIdKey = getUnique . installedUnitIdFS
-- | Lossy conversion to the on-disk 'InstalledUnitId' for a component.
toInstalledUnitId :: UnitId -> InstalledUnitId
toInstalledUnitId (DefiniteUnitId (DefUnitId iuid)) = iuid
toInstalledUnitId (IndefiniteUnitId indef) =
componentIdToInstalledUnitId (indefUnitIdComponentId indef)
installedUnitIdString :: InstalledUnitId -> String
installedUnitIdString = unpackFS . installedUnitIdFS
-- Note [UnitId to InstalledUnitId improvement]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Just because a UnitId is definite (has no holes) doesn't
-- mean it's necessarily a InstalledUnitId; it could just be
-- that over the course of renaming UnitIds on the fly
-- while typechecking an indefinite library, we
-- ended up with a fully instantiated unit id with no hash,
-- since we haven't built it yet. This is fine.
--
-- However, if there is a hashed unit id for this instantiation
-- in the package database, we *better use it*, because
-- that hashed unit id may be lurking in another interface,
-- and chaos will ensue if we attempt to compare the two
-- (the unitIdFS for a UnitId never corresponds to a Cabal-provided
-- hash of a compiled instantiated library).
--
-- There is one last niggle: improvement based on the package database means
-- that we might end up developing on a package that is not transitively
-- depended upon by the packages the user specified directly via command line
-- flags. This could lead to strange and difficult to understand bugs if those
-- instantiations are out of date. The solution is to only improve a
-- unit id if the new unit id is part of the 'preloadClosure'; i.e., the
-- closure of all the packages which were explicitly specified.
-- | A 'InstalledModule' is a 'Module' which contains a 'InstalledUnitId'.
data InstalledModule = InstalledModule {
installedModuleUnitId :: !InstalledUnitId,
installedModuleName :: !ModuleName
}
deriving (Eq, Ord)
instance Outputable InstalledModule where
ppr (InstalledModule p n) =
ppr p <> char ':' <> pprModuleName n
-- | Test if a 'Module' corresponds to a given 'InstalledModule',
-- modulo instantiation.
installedModuleEq :: InstalledModule -> Module -> Bool
installedModuleEq imod mod =
fst (splitModuleInsts mod) == imod
-- | Test if a 'UnitId' corresponds to a given 'InstalledUnitId',
-- modulo instantiation.
installedUnitIdEq :: InstalledUnitId -> UnitId -> Bool
installedUnitIdEq iuid uid =
fst (splitUnitIdInsts uid) == iuid
-- | A 'DefUnitId' is an 'InstalledUnitId' with the invariant that
-- it only refers to a definite library; i.e., one we have generated
-- code for.
newtype DefUnitId = DefUnitId { unDefUnitId :: InstalledUnitId }
deriving (Eq, Ord, Typeable)
instance Outputable DefUnitId where
ppr (DefUnitId uid) = ppr uid
instance Binary DefUnitId where
put_ bh (DefUnitId uid) = put_ bh uid
get bh = do uid <- get bh; return (DefUnitId uid)
-- | A map keyed off of 'InstalledModule'
newtype InstalledModuleEnv elt = InstalledModuleEnv (Map InstalledModule elt)
emptyInstalledModuleEnv :: InstalledModuleEnv a
emptyInstalledModuleEnv = InstalledModuleEnv Map.empty
lookupInstalledModuleEnv :: InstalledModuleEnv a -> InstalledModule -> Maybe a
lookupInstalledModuleEnv (InstalledModuleEnv e) m = Map.lookup m e
extendInstalledModuleEnv
:: InstalledModuleEnv a -> InstalledModule -> a -> InstalledModuleEnv a
extendInstalledModuleEnv (InstalledModuleEnv e) m x =
InstalledModuleEnv (Map.insert m x e)
filterInstalledModuleEnv
:: (InstalledModule -> a -> Bool) -> InstalledModuleEnv a -> InstalledModuleEnv a
filterInstalledModuleEnv f (InstalledModuleEnv e) =
InstalledModuleEnv (Map.filterWithKey f e)
delInstalledModuleEnv :: InstalledModuleEnv a -> InstalledModule -> InstalledModuleEnv a
delInstalledModuleEnv (InstalledModuleEnv e) m = InstalledModuleEnv (Map.delete m e)
{-
************************************************************************
* *
Hole substitutions
* *
************************************************************************
-}
-- | Substitution on module variables, mapping module names to module
-- identifiers.
type ShHoleSubst = ModuleNameEnv Module
-- | Substitutes holes in a 'Module'. NOT suitable for being called
-- directly on a 'nameModule', see Note [Representation of module/name variable].
-- @p[A=<A>]:B@ maps to @p[A=q():A]:B@ with @A=q():A@;
-- similarly, @<A>@ maps to @q():A@.
renameHoleModule :: DynFlags -> ShHoleSubst -> Module -> Module
renameHoleModule dflags = renameHoleModule' (getPackageConfigMap dflags)
-- | Substitutes holes in a 'UnitId', suitable for renaming when
-- an include occurs; see Note [Representation of module/name variable].
--
-- @p[A=<A>]@ maps to @p[A=<B>]@ with @A=<B>@.
renameHoleUnitId :: DynFlags -> ShHoleSubst -> UnitId -> UnitId
renameHoleUnitId dflags = renameHoleUnitId' (getPackageConfigMap dflags)
-- | Like 'renameHoleModule', but requires only 'PackageConfigMap'
-- so it can be used by "Packages".
renameHoleModule' :: PackageConfigMap -> ShHoleSubst -> Module -> Module
renameHoleModule' pkg_map env m
| not (isHoleModule m) =
let uid = renameHoleUnitId' pkg_map env (moduleUnitId m)
in mkModule uid (moduleName m)
| Just m' <- lookupUFM env (moduleName m) = m'
-- NB m = <Blah>, that's what's in scope.
| otherwise = m
-- | Like 'renameHoleUnitId, but requires only 'PackageConfigMap'
-- so it can be used by "Packages".
renameHoleUnitId' :: PackageConfigMap -> ShHoleSubst -> UnitId -> UnitId
renameHoleUnitId' pkg_map env uid =
case uid of
(IndefiniteUnitId
IndefUnitId{ indefUnitIdComponentId = cid
, indefUnitIdInsts = insts
, indefUnitIdFreeHoles = fh })
-> if isNullUFM (intersectUFM_C const (udfmToUfm fh) env)
then uid
-- Functorially apply the substitution to the instantiation,
-- then check the 'PackageConfigMap' to see if there is
-- a compiled version of this 'UnitId' we can improve to.
-- See Note [UnitId to InstalledUnitId] improvement
else improveUnitId pkg_map $
newUnitId cid
(map (\(k,v) -> (k, renameHoleModule' pkg_map env v)) insts)
_ -> uid
-- | Given a possibly on-the-fly instantiated module, split it into
-- a 'Module' that we definitely can find on-disk, as well as an
-- instantiation if we need to instantiate it on the fly. If the
-- instantiation is @Nothing@ no on-the-fly renaming is needed.
splitModuleInsts :: Module -> (InstalledModule, Maybe IndefModule)
splitModuleInsts m =
let (uid, mb_iuid) = splitUnitIdInsts (moduleUnitId m)
in (InstalledModule uid (moduleName m),
fmap (\iuid -> IndefModule iuid (moduleName m)) mb_iuid)
-- | See 'splitModuleInsts'.
splitUnitIdInsts :: UnitId -> (InstalledUnitId, Maybe IndefUnitId)
splitUnitIdInsts (IndefiniteUnitId iuid) =
(componentIdToInstalledUnitId (indefUnitIdComponentId iuid), Just iuid)
splitUnitIdInsts (DefiniteUnitId (DefUnitId uid)) = (uid, Nothing)
generalizeIndefUnitId :: IndefUnitId -> IndefUnitId
generalizeIndefUnitId IndefUnitId{ indefUnitIdComponentId = cid
, indefUnitIdInsts = insts } =
newIndefUnitId cid (map (\(m,_) -> (m, mkHoleModule m)) insts)
generalizeIndefModule :: IndefModule -> IndefModule
generalizeIndefModule (IndefModule uid n) = IndefModule (generalizeIndefUnitId uid) n
parseModuleName :: ReadP ModuleName
parseModuleName = fmap mkModuleName
$ Parse.munch1 (\c -> isAlphaNum c || c `elem` "_.")
parseUnitId :: ReadP UnitId
parseUnitId = parseFullUnitId <++ parseDefiniteUnitId <++ parseSimpleUnitId
where
parseFullUnitId = do
cid <- parseComponentId
insts <- parseModSubst
return (newUnitId cid insts)
parseDefiniteUnitId = do
s <- Parse.munch1 (\c -> isAlphaNum c || c `elem` "-_.+")
return (stringToUnitId s)
parseSimpleUnitId = do
cid <- parseComponentId
return (newSimpleUnitId cid)
parseComponentId :: ReadP ComponentId
parseComponentId = (ComponentId . mkFastString) `fmap` Parse.munch1 abi_char
where abi_char c = isAlphaNum c || c `elem` "-_."
parseModuleId :: ReadP Module
parseModuleId = parseModuleVar <++ parseModule
where
parseModuleVar = do
_ <- Parse.char '<'
modname <- parseModuleName
_ <- Parse.char '>'
return (mkHoleModule modname)
parseModule = do
uid <- parseUnitId
_ <- Parse.char ':'
modname <- parseModuleName
return (mkModule uid modname)
parseModSubst :: ReadP [(ModuleName, Module)]
parseModSubst = Parse.between (Parse.char '[') (Parse.char ']')
. flip Parse.sepBy (Parse.char ',')
$ do k <- parseModuleName
_ <- Parse.char '='
v <- parseModuleId
return (k, v)
-- -----------------------------------------------------------------------------
-- $wired_in_packages
-- Certain packages are known to the compiler, in that we know about certain
-- entities that reside in these packages, and the compiler needs to
-- declare static Modules and Names that refer to these packages. Hence
-- the wired-in packages can't include version numbers, since we don't want
-- to bake the version numbers of these packages into GHC.
--
-- So here's the plan. Wired-in packages are still versioned as
-- normal in the packages database, and you can still have multiple
-- versions of them installed. However, for each invocation of GHC,
-- only a single instance of each wired-in package will be recognized
-- (the desired one is selected via @-package@\/@-hide-package@), and GHC
-- will use the unversioned 'PackageKey' below when referring to it,
-- including in .hi files and object file symbols. Unselected
-- versions of wired-in packages will be ignored, as will any other
-- package that depends directly or indirectly on it (much as if you
-- had used @-ignore-package@).
-- Make sure you change 'Packages.findWiredInPackages' if you add an entry here
integerUnitId, primUnitId,
baseUnitId, rtsUnitId,
thUnitId, dphSeqUnitId, dphParUnitId,
mainUnitId, thisGhcUnitId, etaMetaId, interactiveUnitId, javaUnitId :: UnitId
primUnitId = fsToUnitId (fsLit "ghc-prim")
integerUnitId = fsToUnitId (fsLit "integer")
baseUnitId = fsToUnitId (fsLit "base")
rtsUnitId = fsToUnitId (fsLit "rts")
thUnitId = fsToUnitId (fsLit "template-haskell")
etaMetaId = fsToUnitId (fsLit "eta-meta")
dphSeqUnitId = fsToUnitId (fsLit "dph-seq")
dphParUnitId = fsToUnitId (fsLit "dph-par")
thisGhcUnitId = fsToUnitId (fsLit "ghc")
interactiveUnitId = fsToUnitId (fsLit "interactive")
-- | This is the package Id for the current program. It is the default
-- package Id if you don't specify a package name. We don't add this prefix
-- to symbol names, since there can be only one main package per program.
mainUnitId = fsToUnitId (fsLit "main")
-- | This is the package string for direct Java imports.
javaUnitFs :: FastString
javaUnitFs = fsLit "@java"
-- | This is the package string for direct Java imports.
javaUnitId = fsToUnitId javaUnitFs
-- | This is a fake package id used to provide identities to any un-implemented
-- signatures. The set of hole identities is global over an entire compilation.
-- Don't use this directly: use 'mkHoleModule' or 'isHoleModule' instead.
-- See Note [Representation of module/name variables]
holeUnitId :: UnitId
holeUnitId = fsToUnitId (fsLit "hole")
isInteractiveModule :: Module -> Bool
isInteractiveModule mod = moduleUnitId mod == interactiveUnitId
-- Note [Representation of module/name variables]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- In our ICFP'16, we use <A> to represent module holes, and {A.T} to represent
-- name holes. This could have been represented by adding some new cases
-- to the core data types, but this would have made the existing 'nameModule'
-- and 'moduleUnitId' partial, which would have required a lot of modifications
-- to existing code.
--
-- Instead, we adopted the following encoding scheme:
--
-- <A> ===> hole:A
-- {A.T} ===> hole:A.T
--
-- This encoding is quite convenient, but it is also a bit dangerous too,
-- because if you have a 'hole:A' you need to know if it's actually a
-- 'Module' or just a module stored in a 'Name'; these two cases must be
-- treated differently when doing substitutions. 'renameHoleModule'
-- and 'renameHoleUnitId' assume they are NOT operating on a
-- 'Name'; 'NameShape' handles name substitutions exclusively.
isHoleModule :: Module -> Bool
isHoleModule mod = moduleUnitId mod == holeUnitId
wiredInUnitIds :: [UnitId]
wiredInUnitIds = [ primUnitId,
integerUnitId,
baseUnitId,
rtsUnitId,
thUnitId,
etaMetaId,
thisGhcUnitId,
dphSeqUnitId,
dphParUnitId ]
{-
************************************************************************
* *
\subsection{@ModuleEnv@s}
* *
************************************************************************
-}
-- | A map keyed off of 'Module's
newtype ModuleEnv elt = ModuleEnv (Map NDModule elt)
{-
Note [ModuleEnv performance and determinism]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To prevent accidental reintroduction of nondeterminism the Ord instance
for Module was changed to not depend on Unique ordering and to use the
lexicographic order. This is potentially expensive, but when measured
there was no difference in performance.
To be on the safe side and not pessimize ModuleEnv uses nondeterministic
ordering on Module and normalizes by doing the lexicographic sort when
turning the env to a list.
See Note [Unique Determinism] for more information about the source of
nondeterminism and and Note [Deterministic UniqFM] for explanation of why
it matters for maps.
-}
newtype NDModule = NDModule { unNDModule :: Module }
deriving Eq
-- A wrapper for Module with faster nondeterministic Ord.
-- Don't export, See [ModuleEnv performance and determinism]
instance Ord NDModule where
compare (NDModule (Module p1 n1)) (NDModule (Module p2 n2)) =
(getUnique p1 `nonDetCmpUnique` getUnique p2) `thenCmp`
(getUnique n1 `nonDetCmpUnique` getUnique n2)
filterModuleEnv :: (Module -> a -> Bool) -> ModuleEnv a -> ModuleEnv a
filterModuleEnv f (ModuleEnv e) = ModuleEnv (Map.filterWithKey (f . unNDModule) e)
elemModuleEnv :: Module -> ModuleEnv a -> Bool
elemModuleEnv m (ModuleEnv e) = Map.member (NDModule m) e
extendModuleEnv :: ModuleEnv a -> Module -> a -> ModuleEnv a
extendModuleEnv (ModuleEnv e) m x = ModuleEnv (Map.insert (NDModule m) x e)
extendModuleEnvWith :: (a -> a -> a) -> ModuleEnv a -> Module -> a -> ModuleEnv a
extendModuleEnvWith f (ModuleEnv e) m x = ModuleEnv (Map.insertWith f (NDModule m) x e)
extendModuleEnvList :: ModuleEnv a -> [(Module, a)] -> ModuleEnv a
extendModuleEnvList (ModuleEnv e) xs =
ModuleEnv (Map.insertList [(NDModule k, v) | (k,v) <- xs] e)
extendModuleEnvList_C :: (a -> a -> a) -> ModuleEnv a -> [(Module, a)]
-> ModuleEnv a
extendModuleEnvList_C f (ModuleEnv e) xs =
ModuleEnv (Map.insertListWith f [(NDModule k, v) | (k,v) <- xs] e)
plusModuleEnv_C :: (a -> a -> a) -> ModuleEnv a -> ModuleEnv a -> ModuleEnv a
plusModuleEnv_C f (ModuleEnv e1) (ModuleEnv e2) = ModuleEnv (Map.unionWith f e1 e2)
delModuleEnvList :: ModuleEnv a -> [Module] -> ModuleEnv a
delModuleEnvList (ModuleEnv e) ms = ModuleEnv (Map.deleteList (map NDModule ms) e)
delModuleEnv :: ModuleEnv a -> Module -> ModuleEnv a
delModuleEnv (ModuleEnv e) m = ModuleEnv (Map.delete (NDModule m) e)
plusModuleEnv :: ModuleEnv a -> ModuleEnv a -> ModuleEnv a
plusModuleEnv (ModuleEnv e1) (ModuleEnv e2) = ModuleEnv (Map.union e1 e2)
lookupModuleEnv :: ModuleEnv a -> Module -> Maybe a
lookupModuleEnv (ModuleEnv e) m = Map.lookup (NDModule m) e
lookupWithDefaultModuleEnv :: ModuleEnv a -> a -> Module -> a
lookupWithDefaultModuleEnv (ModuleEnv e) x m = Map.findWithDefault x (NDModule m) e
mapModuleEnv :: (a -> b) -> ModuleEnv a -> ModuleEnv b
mapModuleEnv f (ModuleEnv e) = ModuleEnv (Map.mapWithKey (\_ v -> f v) e)
mkModuleEnv :: [(Module, a)] -> ModuleEnv a
mkModuleEnv xs = ModuleEnv (Map.fromList [(NDModule k, v) | (k,v) <- xs])
emptyModuleEnv :: ModuleEnv a
emptyModuleEnv = ModuleEnv Map.empty
moduleEnvKeys :: ModuleEnv a -> [Module]
moduleEnvKeys (ModuleEnv e) = sort $ map unNDModule $ Map.keys e
-- See Note [ModuleEnv performance and determinism]
moduleEnvElts :: ModuleEnv a -> [a]
moduleEnvElts e = map snd $ moduleEnvToList e
-- See Note [ModuleEnv performance and determinism]
moduleEnvToList :: ModuleEnv a -> [(Module, a)]
moduleEnvToList (ModuleEnv e) =
sortBy (comparing fst) [(m, v) | (NDModule m, v) <- Map.toList e]
-- See Note [ModuleEnv performance and determinism]
unitModuleEnv :: Module -> a -> ModuleEnv a
unitModuleEnv m x = ModuleEnv (Map.singleton (NDModule m) x)
isEmptyModuleEnv :: ModuleEnv a -> Bool
isEmptyModuleEnv (ModuleEnv e) = Map.null e
-- | A set of 'Module's
type ModuleSet = Set NDModule
mkModuleSet :: [Module] -> ModuleSet
extendModuleSet :: ModuleSet -> Module -> ModuleSet
emptyModuleSet :: ModuleSet
moduleSetElts :: ModuleSet -> [Module]
elemModuleSet :: Module -> ModuleSet -> Bool
emptyModuleSet = Set.empty
mkModuleSet = Set.fromList . coerce
extendModuleSet s m = Set.insert (NDModule m) s
moduleSetElts = sort . coerce . Set.toList
elemModuleSet = Set.member . coerce
delModuleSet :: ModuleSet -> Module -> ModuleSet
delModuleSet = coerce (flip Set.delete)
{-
A ModuleName has a Unique, so we can build mappings of these using
UniqFM.
-}
-- | A map keyed off of 'ModuleName's (actually, their 'Unique's)
type ModuleNameEnv elt = UniqFM elt
-- | A map keyed off of 'ModuleName's (actually, their 'Unique's)
-- Has deterministic folds and can be deterministically converted to a list
type DModuleNameEnv elt = UniqDFM elt
|
rahulmutt/ghcvm
|
compiler/Eta/BasicTypes/Module.hs
|
bsd-3-clause
| 49,019 | 0 | 18 | 10,875 | 8,138 | 4,423 | 3,715 | 674 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Build.Macros
-- Copyright : Simon Marlow 2008
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- Generate cabal_macros.h - CPP macros for package version testing
--
-- When using CPP you get
--
-- > VERSION_<package>
-- > MIN_VERSION_<package>(A,B,C)
--
-- for each /package/ in @build-depends@, which is true if the version of
-- /package/ in use is @>= A.B.C@, using the normal ordering on version
-- numbers.
--
module Distribution.Simple.Build.Macros (
generate,
generatePackageVersionMacros,
) where
import Data.Maybe
( isJust )
import Distribution.Package
( PackageIdentifier(PackageIdentifier) )
import Distribution.Version
( Version(versionBranch) )
import Distribution.PackageDescription
( PackageDescription ( package ) )
import Distribution.Simple.LocalBuildInfo
( LocalBuildInfo(withPrograms), externalPackageDeps
, localComponentId, localCompatPackageKey )
import Distribution.Simple.Program.Db
( configuredPrograms )
import Distribution.Simple.Program.Types
( ConfiguredProgram(programId, programVersion) )
import Distribution.Text
( display )
-- ------------------------------------------------------------
-- * Generate cabal_macros.h
-- ------------------------------------------------------------
-- | The contents of the @cabal_macros.h@ for the given configured package.
--
generate :: PackageDescription -> LocalBuildInfo -> String
generate pkg_descr lbi =
"/* DO NOT EDIT: This file is automatically generated by Cabal */\n\n" ++
generatePackageVersionMacros
(package pkg_descr : map snd (externalPackageDeps lbi)) ++
generateToolVersionMacros (configuredPrograms . withPrograms $ lbi) ++
generateComponentIdMacro lbi
-- | Helper function that generates just the @VERSION_pkg@ and @MIN_VERSION_pkg@
-- macros for a list of package ids (usually used with the specific deps of
-- a configured package).
--
generatePackageVersionMacros :: [PackageIdentifier] -> String
generatePackageVersionMacros pkgids = concat
[ "/* package " ++ display pkgid ++ " */\n"
++ generateMacros "" pkgname version
| pkgid@(PackageIdentifier name version) <- pkgids
, let pkgname = map fixchar (display name)
]
-- | Helper function that generates just the @TOOL_VERSION_pkg@ and
-- @MIN_TOOL_VERSION_pkg@ macros for a list of configured programs.
--
generateToolVersionMacros :: [ConfiguredProgram] -> String
generateToolVersionMacros progs = concat
[ "/* tool " ++ progid ++ " */\n"
++ generateMacros "TOOL_" progname version
| prog <- progs
, isJust . programVersion $ prog
, let progid = programId prog ++ "-" ++ display version
progname = map fixchar (programId prog)
Just version = programVersion prog
]
-- | Common implementation of 'generatePackageVersionMacros' and
-- 'generateToolVersionMacros'.
--
generateMacros :: String -> String -> Version -> String
generateMacros prefix name version =
concat
["#define ", prefix, "VERSION_",name," ",show (display version),"\n"
,"#define MIN_", prefix, "VERSION_",name,"(major1,major2,minor) (\\\n"
," (major1) < ",major1," || \\\n"
," (major1) == ",major1," && (major2) < ",major2," || \\\n"
," (major1) == ",major1," && (major2) == ",major2," && (minor) <= ",minor,")"
,"\n\n"
]
where
(major1:major2:minor:_) = map show (versionBranch version ++ repeat 0)
-- | Generate the @CURRENT_COMPONENT_ID@ definition for the component ID
-- of the current package.
generateComponentIdMacro :: LocalBuildInfo -> String
generateComponentIdMacro lbi =
concat
[ "#define CURRENT_COMPONENT_ID \"" ++ display (localComponentId lbi) ++ "\"\n\n"
, "#define CURRENT_PACKAGE_KEY \"" ++ localCompatPackageKey lbi ++ "\"\n\n"
]
fixchar :: Char -> Char
fixchar '-' = '_'
fixchar c = c
|
tolysz/prepare-ghcjs
|
spec-lts8/cabal/Cabal/Distribution/Simple/Build/Macros.hs
|
bsd-3-clause
| 3,971 | 0 | 13 | 693 | 695 | 398 | 297 | 60 | 1 |
-- | Template Haskell functions for deriving "Mutable" instances.
module SubHask.TemplateHaskell.Mutable
( mkMutable
, mkMutablePrimRef
, mkMutableNewtype
)
where
import SubHask.TemplateHaskell.Common
import Prelude
import Control.Monad
import Language.Haskell.TH
showtype :: Type -> String
showtype t = map go (show t)
where
go ' ' = '_'
go '.' = '_'
go '[' = '_'
go ']' = '_'
go '(' = '_'
go ')' = '_'
go '/' = '_'
go '+' = '_'
go '>' = '_'
go '<' = '_'
go x = x
type2name :: Type -> Name
type2name t = mkName $ "Mutable_"++showtype t
-- | Inspects the given type and creates the most efficient "Mutable" instance possible.
--
-- FIXME: implement properly
mkMutable :: Q Type -> Q [Dec]
mkMutable = mkMutablePrimRef
-- | Create a "Mutable" instance for newtype wrappers.
-- The instance has the form:
--
-- > newtype instance Mutable m (TyCon t) = Mutable_TyCon (Mutable m t)
--
-- Also create the appropriate "IsMutable" instance.
--
-- FIXME:
-- Currently uses default implementations which are slow.
mkMutableNewtype :: Name -> Q [Dec]
mkMutableNewtype typename = do
typeinfo <- reify typename
(conname,typekind,typeapp) <- case typeinfo of
TyConI (NewtypeD [] _ typekind (NormalC conname [( _,typeapp)]) _)
-> return (conname,typekind,typeapp)
TyConI (NewtypeD [] _ typekind (RecC conname [(_,_,typeapp)]) _)
-> return (conname,typekind,typeapp)
_ -> error $ "\nderiveSingleInstance; typeinfo="++show typeinfo
let mutname = mkName $ "Mutable_" ++ nameBase conname
nameexists <- lookupValueName (show mutname)
return $ case nameexists of
Just x -> []
Nothing ->
[ NewtypeInstD
[ ]
( mkName $ "Mutable" )
[ VarT (mkName "m"), apply2varlist (ConT typename) typekind ]
( NormalC
mutname
[( NotStrict
, AppT
( AppT
( ConT $ mkName "Mutable" )
( VarT $ mkName "m" )
)
typeapp
)]
)
[ ]
, InstanceD
( map (\x -> AppT (ConT $ mkName "IsMutable") (bndr2type x)) $ filter isStar $ typekind )
( AppT
( ConT $ mkName "IsMutable" )
( apply2varlist (ConT typename) typekind )
)
[ FunD (mkName "freeze")
[ Clause
[ ConP mutname [ VarP $ mkName "x" ] ]
( NormalB $ AppE
( AppE (VarE $ mkName "helper_liftM") (ConE conname) )
( AppE (VarE $ mkName "freeze") (VarE $ mkName "x") )
)
[]
]
, FunD (mkName "thaw")
[ Clause
[ ConP conname [ VarP $ mkName "x" ] ]
( NormalB $ AppE
( AppE (VarE $ mkName "helper_liftM") (ConE mutname) )
( AppE (VarE $ mkName "thaw") (VarE $ mkName "x") )
)
[]
]
, FunD (mkName "write")
[ Clause
[ ConP mutname [ VarP $ mkName "x" ]
, ConP conname [ VarP $ mkName "x'" ]
]
( NormalB $
AppE ( AppE (VarE $ mkName "write") (VarE $ mkName "x") ) (VarE $ mkName "x'" )
)
[]
]
]
]
-- | Create a "Mutable" instance that uses "PrimRef"s for the underlying implementation.
-- This method will succeed for all types.
-- But certain types can be implemented for efficiently.
mkMutablePrimRef :: Q Type -> Q [Dec]
mkMutablePrimRef qt = do
_t <- qt
let (cxt,t) = case _t of
(ForallT _ cxt t) -> (cxt,t)
_ -> ([],_t)
return $
[ NewtypeInstD
cxt
( mkName $ "Mutable" )
[ VarT (mkName "m"), t ]
( NormalC
( type2name t )
[( NotStrict
, AppT (AppT (ConT $ mkName "PrimRef") (VarT $ mkName "m")) t
)]
)
[ ]
, InstanceD
cxt
( AppT ( ConT $ mkName "IsMutable" ) t )
[ FunD (mkName "freeze")
[ Clause
[ ConP (type2name t) [ VarP $ mkName "x"] ]
( NormalB $ AppE (VarE $ mkName "readPrimRef") (VarE $ mkName "x"))
[]
]
, FunD (mkName "thaw")
[ Clause
[ VarP $ mkName "x" ]
( NormalB $ AppE
( AppE (VarE $ mkName "helper_liftM") (ConE $ type2name t) )
( AppE (VarE $ mkName "newPrimRef") (VarE $ mkName "x") )
)
[]
]
, FunD (mkName "write")
[ Clause
[ ConP (type2name t) [VarP $ mkName "x"], VarP $ mkName "x'" ]
( NormalB $ AppE
( AppE (VarE $ mkName "writePrimRef") (VarE $ mkName "x") )
( VarE $ mkName "x'" )
)
[]
]
]
]
|
abailly/subhask
|
src/SubHask/TemplateHaskell/Mutable.hs
|
bsd-3-clause
| 5,718 | 0 | 24 | 2,695 | 1,499 | 770 | 729 | 116 | 11 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS -fno-warn-unused-do-bind -fno-warn-type-defaults #-}
-- | A word cloud of all the nicknames participating in the time frame.
module Ircbrowse.View.NickCloud where
import Ircbrowse.View
import Ircbrowse.View.Template
import Ircbrowse.View.Cloud
nickCloud :: [(String,Integer)] -> Html
nickCloud stats = do
template "nick-cloud" "Nick Cloud" cloudScripts $ do
containerFluid $ do
row $ do
span12 $ do
mainHeading $ do
"Nick Word Cloud"
p $ do "Below is a nick cloud in logarithmic scale, "
"because IRC channels tend to have top contributors, "
"rather than an evenly distributed user contribution. "
cloud "cloud-container" (900,700) 450 5 stats
|
plow-technologies/ircbrowse
|
src/Ircbrowse/View/NickCloud.hs
|
bsd-3-clause
| 827 | 0 | 23 | 202 | 136 | 70 | 66 | 19 | 1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sk-SK">
<title>SVN Digger Files</title>
<maps>
<homeID>svndigger</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/svndigger/src/main/javahelp/help_sk_SK/helpset_sk_SK.hs
|
apache-2.0
| 967 | 77 | 66 | 157 | 409 | 207 | 202 | -1 | -1 |
{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleInstances,
MultiParamTypeClasses #-}
module Haste.Monad (
JSGen, genJS, dependOn, getModName, addLocal, getCfg, continue, isolate,
pushBind, popBind, getCurrentBinding, whenCfg, rename, getActualName
) where
import Control.Monad.State.Strict
import Data.JSTarget as J hiding (modName)
import qualified Data.Set as S
import Control.Applicative
import qualified Data.Map as M
data GenState cfg = GenState {
-- | Dependencies in current context.
deps :: ![Name],
-- | Local variables in current context.
locals :: ![Name],
-- | The current continuation. Code is generated by appending to this
-- continuation.
continuation :: !(Stm -> Stm),
-- | The stack of nested lambdas we've traversed.
bindStack :: ![Var],
-- | Name of the module being compiled.
modName :: !String,
-- | Current compiler configuration.
config :: !cfg,
-- | Mapping of variable renamings.
renames :: !(M.Map Var Var)
}
initialState :: cfg -> GenState cfg
initialState cfg = GenState {
deps = [],
locals = [],
continuation = id,
bindStack = [],
modName = "",
config = cfg,
renames = M.empty
}
newtype JSGen cfg a =
JSGen (State (GenState cfg) a)
deriving (Monad, Functor, Applicative)
class Dependency a where
-- | Add a dependency to the function currently being generated.
dependOn :: a -> JSGen cfg ()
-- | Mark a symbol as local, excluding it from the dependency graph.
addLocal :: a -> JSGen cfg ()
instance Dependency J.Name where
{-# INLINE dependOn #-}
dependOn v = JSGen $ do
st <- get
put st {deps = v : deps st}
{-# INLINE addLocal #-}
addLocal v = JSGen $ do
st <- get
put st {locals = v : locals st}
instance Dependency J.Var where
{-# INLINE dependOn #-}
dependOn (Foreign _) = return ()
dependOn (Internal n _ _) = dependOn n
{-# INLINE addLocal #-}
addLocal (Foreign _) = return ()
addLocal (Internal n _ _) = addLocal n
instance Dependency a => Dependency [a] where
dependOn = mapM_ dependOn
addLocal = mapM_ addLocal
instance Dependency a => Dependency (S.Set a) where
dependOn = dependOn . S.toList
addLocal = addLocal . S.toList
genJS :: cfg -- ^ Config to use for code generation.
-> String -- ^ Name of the module being compiled.
-> JSGen cfg a -- ^ The code generation computation.
-> (a, S.Set J.Name, S.Set J.Name, Stm -> Stm)
genJS cfg myModName (JSGen gen) =
case runState gen (initialState cfg) {modName = myModName} of
(a, GenState dependencies loc cont _ _ _ _) ->
(a, S.fromList dependencies, S.fromList loc, cont)
getModName :: JSGen cfg String
getModName = JSGen $ modName <$> get
pushBind :: Var -> JSGen cfg ()
pushBind v = JSGen $ do
st <- get
put st {bindStack = v : bindStack st}
popBind :: JSGen cfg ()
popBind = JSGen $ do
st <- get
put st {bindStack = tail $ bindStack st}
getCurrentBinding :: JSGen cfg Var
getCurrentBinding = JSGen $ fmap (head . bindStack) get
-- | Add a new continuation onto the current one.
continue :: (Stm -> Stm) -> JSGen cfg ()
continue cont = JSGen $ do
st <- get
put st {continuation = continuation st . cont}
-- | Run a GenJS computation in isolation, returning its results rather than
-- writing them to the output stream. Dependencies and locals are still
-- updated, however, and any enclosing renames are still visible within
-- the isolated computation.
isolate :: JSGen cfg a -> JSGen cfg (a, Stm -> Stm)
isolate gen = do
myMod <- getModName
cfg <- getCfg
b <- getCurrentBinding
rns <- renames <$> JSGen get
let (x, dep, loc, cont) = genJS cfg myMod $ do
pushBind b
JSGen $ do
st <- get
put st {renames = rns}
gen
dependOn dep
addLocal loc
return (x, cont)
getCfg :: JSGen cfg cfg
getCfg = JSGen $ fmap config get
whenCfg :: (cfg -> Bool) -> JSGen cfg () -> JSGen cfg ()
whenCfg p act = do
cfg <- getCfg
when (p cfg) act
-- | Run a computation with the given renaming added to its context.
rename :: Var -> Var -> JSGen cfg a -> JSGen cfg a
rename from to m = do
st <- JSGen get
JSGen $ put st {renames = M.insert from to $ renames st}
x <- m
st' <- JSGen get
JSGen $ put st' {renames = renames st}
return x
-- | Get the actual name of a variable, recursing through multiple renamings
-- if necessary.
getActualName :: Var -> JSGen cfg Var
getActualName v = do
rns <- renames <$> JSGen get
maybe (return v) getActualName $ M.lookup v rns
|
beni55/haste-compiler
|
src/Haste/Monad.hs
|
bsd-3-clause
| 4,645 | 0 | 18 | 1,177 | 1,416 | 736 | 680 | 126 | 1 |
{-# Language PatternGuards #-}
module Blub
( blub
, foo
, bar
) where
import Ugah.Foo
import Control.Applicative
import qualified Control.Monad as CM
import Ugah.Blub
f :: Int -> Int
f = (+ 3)
g :: Int -> Int
g =
where
|
jystic/hsimport
|
tests/inputFiles/ModuleTest24.hs
|
bsd-3-clause
| 235 | 0 | 5 | 58 | 71 | 45 | 26 | -1 | -1 |
{-# LANGUAGE CPP #-}
#ifndef MIN_VERSION_profunctors
#define MIN_VERSION_profunctors(x,y,z) 0
#endif
#if (MIN_VERSION_profunctors(4,4,0)) && __GLASGOW_HASKELL__ >= 708
#define USE_COERCE
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
#else
{-# LANGUAGE Unsafe #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2015 Edward Kmett and Eric Mertens
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- This module provides a shim around 'coerce' that defaults to 'unsafeCoerce'
-- on GHC < 7.8
-----------------------------------------------------------------------------
module Control.Lens.Internal.Coerce
( coerce
, coerce'
) where
#ifdef USE_COERCE
import Data.Coerce
coerce' :: forall a b. Coercible a b => b -> a
coerce' = coerce (id :: a -> a)
{-# INLINE coerce' #-}
#else
import Unsafe.Coerce
coerce, coerce' :: a -> b
coerce = unsafeCoerce
coerce' = unsafeCoerce
{-# INLINE coerce #-}
{-# INLINE coerce' #-}
#endif
|
danidiaz/lens
|
src/Control/Lens/Internal/Coerce.hs
|
bsd-3-clause
| 1,164 | 0 | 7 | 179 | 89 | 63 | 26 | 11 | 1 |
--
-- Sudoku solver using constraint propagation. The algorithm is by
-- Peter Norvig http://norvig.com/sudoku.html; the Haskell
-- implementation is by Manu and Daniel Fischer, and can be found on
-- the Haskell Wiki http://www.haskell.org/haskellwiki/Sudoku
--
-- The Haskell wiki license applies to this code:
--
-- Permission is hereby granted, free of charge, to any person obtaining
-- this work (the "Work"), to deal in the Work without restriction,
-- including without limitation the rights to use, copy, modify, merge,
-- publish, distribute, sublicense, and/or sell copies of the Work, and
-- to permit persons to whom the Work is furnished to do so.
--
-- THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-- WITH THE WORK OR THE USE OR OTHER DEALINGS IN THE WORK.
module Sudoku (solve, printGrid) where
import Data.List hiding (lookup)
import Data.Array
import Control.Monad
import Data.Maybe
-- Types
type Digit = Char
type Square = (Char,Char)
type Unit = [Square]
-- We represent our grid as an array
type Grid = Array Square [Digit]
-- Setting Up the Problem
rows = "ABCDEFGHI"
cols = "123456789"
digits = "123456789"
box = (('A','1'),('I','9'))
cross :: String -> String -> [Square]
cross rows cols = [ (r,c) | r <- rows, c <- cols ]
squares :: [Square]
squares = cross rows cols -- [('A','1'),('A','2'),('A','3'),...]
peers :: Array Square [Square]
peers = array box [(s, set (units!s)) | s <- squares ]
where
set = nub . concat
unitlist :: [Unit]
unitlist = [ cross rows [c] | c <- cols ] ++
[ cross [r] cols | r <- rows ] ++
[ cross rs cs | rs <- ["ABC","DEF","GHI"],
cs <- ["123","456","789"]]
-- this could still be done more efficiently, but what the heck...
units :: Array Square [Unit]
units = array box [(s, [filter (/= s) u | u <- unitlist, s `elem` u ]) |
s <- squares]
allPossibilities :: Grid
allPossibilities = array box [ (s,digits) | s <- squares ]
-- Parsing a grid into an Array
parsegrid :: String -> Maybe Grid
parsegrid g = do regularGrid g
foldM assign allPossibilities (zip squares g)
where regularGrid :: String -> Maybe String
regularGrid g = if all (`elem` "0.-123456789") g
then Just g
else Nothing
-- Propagating Constraints
assign :: Grid -> (Square, Digit) -> Maybe Grid
assign g (s,d) = if d `elem` digits
-- check that we are assigning a digit and not a '.'
then do
let ds = g ! s
toDump = delete d ds
foldM eliminate g (zip (repeat s) toDump)
else return g
eliminate :: Grid -> (Square, Digit) -> Maybe Grid
eliminate g (s,d) =
let cell = g ! s in
if d `notElem` cell then return g -- already eliminated
-- else d is deleted from s' values
else do let newCell = delete d cell
newV = g // [(s,newCell)]
newV2 <- case newCell of
-- contradiction : Nothing terminates the computation
[] -> Nothing
-- if there is only one value left in s, remove it from peers
[d'] -> do let peersOfS = peers ! s
foldM eliminate newV (zip peersOfS (repeat d'))
-- else : return the new grid
_ -> return newV
-- Now check the places where d appears in the peers of s
foldM (locate d) newV2 (units ! s)
locate :: Digit -> Grid -> Unit -> Maybe Grid
locate d g u = case filter ((d `elem`) . (g !)) u of
[] -> Nothing
[s] -> assign g (s,d)
_ -> return g
-- Search
search :: Grid -> Maybe Grid
search g =
case [(l,(s,xs)) | (s,xs) <- assocs g, let l = length xs, l /= 1] of
[] -> return g
ls -> do let (_,(s,ds)) = minimum ls
msum [assign g (s,d) >>= search | d <- ds]
solve :: String -> Maybe Grid
solve str = do
grd <- parsegrid str
search grd
-- Display solved grid
printGrid :: Grid -> IO ()
printGrid = putStrLn . gridToString
gridToString :: Grid -> String
gridToString g =
let l0 = elems g
-- [("1537"),("4"),...]
l1 = (map (\s -> " " ++ s ++ " ")) l0
-- ["1 "," 2 ",...]
l2 = (map concat . sublist 3) l1
-- ["1 2 3 "," 4 5 6 ", ...]
l3 = (sublist 3) l2
-- [["1 2 3 "," 4 5 6 "," 7 8 9 "],...]
l4 = (map (concat . intersperse "|")) l3
-- ["1 2 3 | 4 5 6 | 7 8 9 ",...]
l5 = (concat . intersperse [line] . sublist 3) l4
in unlines l5
where sublist n [] = []
sublist n xs = ys : sublist n zs
where (ys,zs) = splitAt n xs
line = hyphens ++ "+" ++ hyphens ++ "+" ++ hyphens
hyphens = replicate 9 '-'
|
y-kamiya/parallel-concurrent-haskell
|
src/Sudoku-sample/Sudoku.hs
|
gpl-2.0
| 5,282 | 0 | 20 | 1,669 | 1,422 | 773 | 649 | 87 | 4 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-2015
-}
-- | Functions to computing the statistics reflective of the "size"
-- of a Core expression
module CoreStats (
-- * Expression and bindings size
coreBindsSize, exprSize,
CoreStats(..), coreBindsStats, exprStats,
) where
import CoreSyn
import Outputable
import Coercion
import Var
import Type (Type, typeSize, seqType)
import Id (idType)
import CoreSeq (megaSeqIdInfo)
data CoreStats = CS { cs_tm :: Int -- Terms
, cs_ty :: Int -- Types
, cs_co :: Int } -- Coercions
instance Outputable CoreStats where
ppr (CS { cs_tm = i1, cs_ty = i2, cs_co = i3 })
= braces (sep [text "terms:" <+> intWithCommas i1 <> comma,
text "types:" <+> intWithCommas i2 <> comma,
text "coercions:" <+> intWithCommas i3])
plusCS :: CoreStats -> CoreStats -> CoreStats
plusCS (CS { cs_tm = p1, cs_ty = q1, cs_co = r1 })
(CS { cs_tm = p2, cs_ty = q2, cs_co = r2 })
= CS { cs_tm = p1+p2, cs_ty = q1+q2, cs_co = r1+r2 }
zeroCS, oneTM :: CoreStats
zeroCS = CS { cs_tm = 0, cs_ty = 0, cs_co = 0 }
oneTM = zeroCS { cs_tm = 1 }
sumCS :: (a -> CoreStats) -> [a] -> CoreStats
sumCS f = foldr (plusCS . f) zeroCS
coreBindsStats :: [CoreBind] -> CoreStats
coreBindsStats = sumCS bindStats
bindStats :: CoreBind -> CoreStats
bindStats (NonRec v r) = bindingStats v r
bindStats (Rec prs) = sumCS (\(v,r) -> bindingStats v r) prs
bindingStats :: Var -> CoreExpr -> CoreStats
bindingStats v r = bndrStats v `plusCS` exprStats r
bndrStats :: Var -> CoreStats
bndrStats v = oneTM `plusCS` tyStats (varType v)
exprStats :: CoreExpr -> CoreStats
exprStats (Var {}) = oneTM
exprStats (Lit {}) = oneTM
exprStats (Type t) = tyStats t
exprStats (Coercion c) = coStats c
exprStats (App f a) = exprStats f `plusCS` exprStats a
exprStats (Lam b e) = bndrStats b `plusCS` exprStats e
exprStats (Let b e) = bindStats b `plusCS` exprStats e
exprStats (Case e b _ as) = exprStats e `plusCS` bndrStats b
`plusCS` sumCS altStats as
exprStats (Cast e co) = coStats co `plusCS` exprStats e
exprStats (Tick _ e) = exprStats e
altStats :: CoreAlt -> CoreStats
altStats (_, bs, r) = altBndrStats bs `plusCS` exprStats r
altBndrStats :: [Var] -> CoreStats
-- Charge one for the alternative, not for each binder
altBndrStats vs = oneTM `plusCS` sumCS (tyStats . varType) vs
tyStats :: Type -> CoreStats
tyStats ty = zeroCS { cs_ty = typeSize ty }
coStats :: Coercion -> CoreStats
coStats co = zeroCS { cs_co = coercionSize co }
coreBindsSize :: [CoreBind] -> Int
-- We use coreBindStats for user printout
-- but this one is a quick and dirty basis for
-- the simplifier's tick limit
coreBindsSize bs = foldr ((+) . bindSize) 0 bs
exprSize :: CoreExpr -> Int
-- ^ A measure of the size of the expressions, strictly greater than 0
-- It also forces the expression pretty drastically as a side effect
-- Counts *leaves*, not internal nodes. Types and coercions are not counted.
exprSize (Var v) = v `seq` 1
exprSize (Lit lit) = lit `seq` 1
exprSize (App f a) = exprSize f + exprSize a
exprSize (Lam b e) = bndrSize b + exprSize e
exprSize (Let b e) = bindSize b + exprSize e
exprSize (Case e b t as) = seqType t `seq`
exprSize e + bndrSize b + 1 + foldr ((+) . altSize) 0 as
exprSize (Cast e co) = (seqCo co `seq` 1) + exprSize e
exprSize (Tick n e) = tickSize n + exprSize e
exprSize (Type t) = seqType t `seq` 1
exprSize (Coercion co) = seqCo co `seq` 1
tickSize :: Tickish Id -> Int
tickSize (ProfNote cc _ _) = cc `seq` 1
tickSize _ = 1 -- the rest are strict
bndrSize :: Var -> Int
bndrSize b | isTyVar b = seqType (tyVarKind b) `seq` 1
| otherwise = seqType (idType b) `seq`
megaSeqIdInfo (idInfo b) `seq`
1
bndrsSize :: [Var] -> Int
bndrsSize = sum . map bndrSize
bindSize :: CoreBind -> Int
bindSize (NonRec b e) = bndrSize b + exprSize e
bindSize (Rec prs) = foldr ((+) . pairSize) 0 prs
pairSize :: (Var, CoreExpr) -> Int
pairSize (b,e) = bndrSize b + exprSize e
altSize :: CoreAlt -> Int
altSize (c,bs,e) = c `seq` bndrsSize bs + exprSize e
|
olsner/ghc
|
compiler/coreSyn/CoreStats.hs
|
bsd-3-clause
| 4,393 | 0 | 12 | 1,152 | 1,558 | 838 | 720 | 87 | 1 |
module ShouldCompile where
-- This file contains several non-breaking space characters,
-- aka '\xa0'. The compiler should recognise these as whitespace.
f = ( + )
|
urbanslug/ghc
|
testsuite/tests/parser/should_compile/read037.hs
|
bsd-3-clause
| 244 | 3 | 7 | 56 | 19 | 10 | 9 | 2 | 1 |
module Network.Mail.ImapSpec (main, spec) where
import Test.Hspec
import Data.List (intercalate)
import Network.Mail
import Network.Mail.Imap
import Network.Mail.Imap.Types
import Network.Mail.ImapStub
prettyPrintCurrentDirectory :: Imap (Maybe [String])
prettyPrintCurrentDirectory =
getAllMails fetchHeader >>= prettyPrintHeaders
prettyPrintFirstMailOfCurrentDirectory :: Imap (Maybe [String])
prettyPrintFirstMailOfCurrentDirectory =
getAllMails (fetchHeader . take 1) >>= prettyPrintHeaders
getAllMails :: ([UID] -> Imap (Maybe a)) -> Imap (Maybe a)
getAllMails f = searchAll >>= maybe (return Nothing) f
prettyPrintHeaders :: Maybe [Header] -> Imap (Maybe [String])
prettyPrintHeaders = return . fmap (fmap showHeader)
where showHeader h = intercalate " " $ fmap ($ h)
[show . extractUID . getUID, getDate, getSender, getSubject]
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "DSL usecases" $ do
describe "select" $ do
describe "'INBOX' directory" $ do
it "DirectoryDescription with two mails" $ do
runStubTest (select ".")
`shouldBe` Just (DirectoryDescription 0 2 0)
it "Print all mails" $ do
runStubTest prettyPrintCurrentDirectory
`shouldBe` Just ["1 2015-01-01 10:10 S1 T1", "2 2015-02-03 21:12 S2 T2"]
it "Print the first mail" $ do
runStubTest prettyPrintFirstMailOfCurrentDirectory
`shouldBe` Just ["1 2015-01-01 10:10 S1 T1"]
it "Print all mails after going into a folder and going up" $ do
runStubTest (select "Personal" >> select ".." >> prettyPrintCurrentDirectory)
`shouldBe` Just ["1 2015-01-01 10:10 S1 T1", "2 2015-02-03 21:12 S2 T2"]
it "Print all mails after going to itself" $ do
runStubTest (select "." >> prettyPrintCurrentDirectory)
`shouldBe` Just ["1 2015-01-01 10:10 S1 T1", "2 2015-02-03 21:12 S2 T2"]
it "Print all mails after going into a folder, to this one and going up" $ do
runStubTest (select "Personal" >> select "." >> select ".." >> prettyPrintCurrentDirectory)
`shouldBe` Just ["1 2015-01-01 10:10 S1 T1", "2 2015-02-03 21:12 S2 T2"]
it "Print all mails after going to itself, then into a folder, to this one and going up" $ do
runStubTest (select "Personal" >> select "." >> select ".." >> prettyPrintCurrentDirectory)
`shouldBe` Just ["1 2015-01-01 10:10 S1 T1", "2 2015-02-03 21:12 S2 T2"]
describe "'Personal' directory" $ do
it "DirectoryDescription with only one mail" $ do
runStubTest (select "Personal")
`shouldBe` Just (DirectoryDescription 0 1 0)
it "Print all mails" $ do
runStubTest (select "Personal" >> prettyPrintCurrentDirectory)
`shouldBe` Just ["3 2015-04-05 12:34 S2 T1"]
it "Print all mails after going to 'Personal' then to itself" $ do
runStubTest (select "Personal" >> select "." >> prettyPrintCurrentDirectory)
`shouldBe` Just ["3 2015-04-05 12:34 S2 T1"]
it "Print all mails after going to itself then to 'Personal'" $ do
runStubTest (select "." >> select "Personal" >> prettyPrintCurrentDirectory)
`shouldBe` Just ["3 2015-04-05 12:34 S2 T1"]
describe "Unknown directory" $ do
it "Print the cotent of the previous valid Directory, here 'INBOX'" $ do
runStubTest (select "Unknown" >> prettyPrintCurrentDirectory)
`shouldBe` Just ["1 2015-01-01 10:10 S1 T1", "2 2015-02-03 21:12 S2 T2"]
describe "create" $ do
it "Create a non-existing directory should be true" $ do
runStubTest (create "New")
`shouldBe` True
it "Create an existing directory should be false" $ do
runStubTest (create "Personal")
`shouldBe` False
describe "rename" $ do
it "Rename an existing directory with a non-existing directory name should be true" $ do
runStubTest (select "Personal" >> rename "Personal_new")
`shouldBe` True
it "Rename an existing directory with an existing directory name should be false" $ do
runStubTest (select "Personal" >> rename "Work")
`shouldBe` False
describe "delete" $ do
it "Delete an existing directory should be true" $ do
runStubTest (delete "Personal")
`shouldBe` True
it "Delete a non-existing directory should be false" $ do
runStubTest (delete "Unknown")
`shouldBe` False
describe "subscribe" $ do
it "Subscribe to an existing directory should be true" $ do
runStubTest (subscribe "Personal")
`shouldBe` True
it "Subscribe to a non-existing directory should be false" $ do
runStubTest (subscribe "Unknown")
`shouldBe` False
describe "unsubscribe" $ do
it "Unsubscribe to an existing directory should be true" $ do
runStubTest (unsubscribe "Personal")
`shouldBe` True
it "Unsubscribe to a non-existing directory should be false" $ do
runStubTest (unsubscribe "Unknown")
`shouldBe` False
describe "list" $ do
it "list 'INBOX' directory should return 'Personal' and 'Work'" $ do
runStubTest (list (Left "."))
`shouldBe` Just ["Personal", "Work"]
it "list 'Personal' directory should return en empty list" $ do
runStubTest (list (Left "Personal"))
`shouldBe` Just []
describe "lsub" $ do
it "lsub 'INBOX' directory should return 'Personal' and 'Work'" $ do
runStubTest (lsub (Left "."))
`shouldBe` Just ["Personal", "Work"]
it "lsub 'Personal' directory should return en empty list" $ do
runStubTest (lsub (Left "Personal"))
`shouldBe` Just []
describe "expunge" $ do
it "Expunge 'INBOX' directory should be true" $ do
runStubTest expunge
`shouldBe` True
it "go to 'Personal' folder and run expunge should be false" $ do
runStubTest (select "Personal" >> expunge)
`shouldBe` False
describe "check" $ do
it "Check and print all mails of 'INBOX'" $ do
runStubTest (check >> prettyPrintCurrentDirectory)
`shouldBe` Just ["1 2015-01-01 10:10 S1 T1", "2 2015-02-03 21:12 S2 T2"]
it "Check and list 'INBOX' directory should return 'Personal' and 'Work'" $ do
runStubTest (check >> list (Left "."))
`shouldBe` Just ["Personal", "Work"]
it "Check, go to 'Personal' folder and print all mails" $ do
runStubTest (check >> select "Personal" >> prettyPrintCurrentDirectory)
`shouldBe` Just ["3 2015-04-05 12:34 S2 T1"]
it "Check and rename an existing directory with a non-existing directory name should be true" $ do
runStubTest (check >> select "Personal" >> rename "Personal_new")
`shouldBe` True
it "Check and subscribe to an existing directory should be true" $ do
runStubTest (check >> subscribe "Personal")
`shouldBe` True
it "Check and unsubscribe to an existing directory should be true" $ do
runStubTest (check >> unsubscribe "Personal")
`shouldBe` True
it "Check and list 'INBOX' directory should return 'Personal' and 'Work'" $ do
runStubTest (check >> list (Left "."))
`shouldBe` Just ["Personal", "Work"]
it "Check and lsub 'INBOX' directory should return 'Personal' and 'Work'" $ do
runStubTest (check >> lsub (Left "."))
`shouldBe` Just ["Personal", "Work"]
it "Check and expunge should be true" $ do
runStubTest (check >> expunge)
`shouldBe` True
describe "examine" $ do
it "Examine a directory and print all mails should print those of 'INBOX'" $ do
runStubTest (examine "Personal" >> prettyPrintCurrentDirectory)
`shouldBe` Just ["1 2015-01-01 10:10 S1 T1", "2 2015-02-03 21:12 S2 T2"]
it "Examine a directory should return a DirectoryDescription with only one mail" $ do
runStubTest (examine "Personal")
`shouldBe` Just (DirectoryDescription 0 1 0)
it "Examine itself should return a DirectoryDescription with two mails" $ do
runStubTest (examine ".")
`shouldBe` Just (DirectoryDescription 0 2 0)
it "Examine an unknown directory should return Nothing" $ do
runStubTest (examine "Unknown")
`shouldBe` Nothing
describe "noop" $ do
it "Noop on 'INBOX' should return a DirectoryDescription with two mails" $ do
runStubTest noop
`shouldBe` DirectoryDescription 0 2 0
it "Noop on 'Personal' should return a DirectoryDescription with one mail" $ do
runStubTest (select "Personal" >> noop)
`shouldBe` DirectoryDescription 0 1 0
it "Noop on an unknown directory should return the DirectoryDescription of 'INBOX', ie. two mails" $ do
runStubTest (select "Unknown" >> noop)
`shouldBe` DirectoryDescription 0 2 0
it "Noop on an unknown directory after going in a know one should return the DirectoryDescription of the known directory, ie. one mail" $ do
runStubTest (select "Personal" >> select "Unknown" >> noop)
`shouldBe` DirectoryDescription 0 1 0
it "Noop on an unknown directory on the parent directory after going in a know one should return the DirectoryDescription of the known directory, ie. one mail" $ do
runStubTest (select "Personal" >> select "../Unknown" >> noop)
`shouldBe` DirectoryDescription 0 1 0
describe "status" $ do
describe "unseen item" $ do
it "status on 'INBOX' should return with two mails" $ do
runStubTest (status "." SQUnseen)
`shouldBe` Just 2
it "status on 'Personal' should return with one mail" $ do
runStubTest (status "Personal" SQUnseen)
`shouldBe` Just 1
describe "messages item" $ do
it "status on 'INBOX' should return with two mails" $ do
runStubTest (status "." SQMessages)
`shouldBe` Just 2
it "status on 'Personal' should return with one mail" $ do
runStubTest (status "Personal" SQMessages)
`shouldBe` Just 1
describe "recent item" $ do
it "status on 'INBOX' should return with two mails" $ do
runStubTest (status "." SQRecent)
`shouldBe` Just 2
it "status on 'Personal' should return with one mail" $ do
runStubTest (status "Personal" SQRecent)
`shouldBe` Just 1
describe "uidnext item" $ do
it "status on 'INBOX' should return with the maximum UID + 1 (ie. 4)" $ do
runStubTest (status "." SQUidnext)
`shouldBe` Just (UID 4)
it "status on 'Personal' should return with two mails" $ do
runStubTest (status "Personal" SQUidnext)
`shouldBe` Just (UID 4)
describe "uidvalidity item" $ do
it "status on 'INBOX' should return with two mails" $ do
runStubTest (status "." SQUidvalidity)
`shouldBe` Just (UID 2)
it "status on 'Personal' should return with two mails" $ do
runStubTest (status "Personal" SQUidvalidity)
`shouldBe` Just (UID 3)
describe "unseen and messages item" $ do
it "status on 'INBOX' should return with two mails" $ do
runStubTest (status "." (SQProduct SQUnseen SQMessages))
`shouldBe` Just (2, 2)
it "status on 'Personal' should return with two mails" $ do
runStubTest (status "Personal" (SQProduct SQUnseen SQMessages))
`shouldBe` Just (1, 1)
describe "all items" $ do
it "status on 'INBOX' should return with two mails" $ do
runStubTest (status "." (SQProduct (SQProduct SQUnseen SQMessages) (SQProduct SQRecent (SQProduct SQUidnext SQUidvalidity))))
`shouldBe` Just ((2, 2), (2, (UID 4, UID 2)))
it "status on 'Personal' should return with one mail" $ do
runStubTest (status "Personal" (SQProduct (SQProduct SQUnseen SQMessages) (SQProduct SQRecent (SQProduct SQUidnext SQUidvalidity))))
`shouldBe` Just ((1, 1), (1, (UID 4, UID 3)))
|
blackheaven/smoothmail
|
test/Network/Mail/ImapSpec.hs
|
isc
| 12,326 | 0 | 28 | 3,389 | 2,903 | 1,377 | 1,526 | 227 | 1 |
{-# OPTIONS_HADDOCK hide #-}
module Graphics.Gloss.Internals.Interface.Backend.GLUT
(GLUTState)
where
import Data.IORef
import Control.Monad
import Control.Concurrent
import Graphics.UI.GLUT (get,($=))
import qualified Graphics.Rendering.OpenGL as GL
import qualified Graphics.UI.GLUT as GLUT
import qualified System.Exit as System
import Graphics.Gloss.Internals.Interface.Backend.Types
-- | We don't maintain any state information for the GLUT backend,
-- so this data type is empty.
data GLUTState
= GLUTState
glutStateInit :: GLUTState
glutStateInit = GLUTState
instance Backend GLUTState where
initBackendState = glutStateInit
initializeBackend = initializeGLUT
-- non-freeglut doesn't like this: (\_ -> GLUT.leaveMainLoop)
exitBackend = (\_ -> System.exitWith System.ExitSuccess)
openWindow = openWindowGLUT
dumpBackendState = dumpStateGLUT
installDisplayCallback = installDisplayCallbackGLUT
-- We can ask for this in freeglut, but it doesn't seem to work :(.
-- (\_ -> GLUT.actionOnWindowClose $= GLUT.MainLoopReturns)
installWindowCloseCallback = (\_ -> return ())
installReshapeCallback = installReshapeCallbackGLUT
installKeyMouseCallback = installKeyMouseCallbackGLUT
installMotionCallback = installMotionCallbackGLUT
installIdleCallback = installIdleCallbackGLUT
-- Call the GLUT mainloop.
-- This function will return when something calls GLUT.leaveMainLoop
runMainLoop _
= GLUT.mainLoop
postRedisplay _
= GLUT.postRedisplay Nothing
getWindowDimensions _
= do GL.Size sizeX sizeY <- get GLUT.windowSize
return (fromEnum sizeX,fromEnum sizeY)
elapsedTime _
= do t <- get GLUT.elapsedTime
return $ (fromIntegral t) / 1000
sleep _ sec
= do threadDelay (round $ sec * 1000000)
-- Initialise -----------------------------------------------------------------
initializeGLUT
:: IORef GLUTState
-> Bool
-> IO ()
initializeGLUT _ debug
= do (_progName, _args) <- GLUT.getArgsAndInitialize
glutVersion <- get GLUT.glutVersion
when debug
$ putStr $ " glutVersion = " ++ show glutVersion ++ "\n"
GLUT.initialDisplayMode
$= [ GLUT.RGBMode
, GLUT.DoubleBuffered]
-- See if our requested display mode is possible
displayMode <- get GLUT.initialDisplayMode
displayModePossible <- get GLUT.displayModePossible
when debug
$ do putStr $ " displayMode = " ++ show displayMode ++ "\n"
++ " possible = " ++ show displayModePossible ++ "\n"
++ "\n"
-- Open Window ----------------------------------------------------------------
openWindowGLUT
:: IORef GLUTState
-> Display
-> IO ()
openWindowGLUT _ display
= do
-- Setup and create a new window.
-- Be sure to set initialWindow{Position,Size} before calling
-- createWindow. If we don't do this we get wierd half-created
-- windows some of the time.
case display of
InWindow windowName (sizeX, sizeY) (posX, posY) ->
do GLUT.initialWindowSize
$= GL.Size
(fromIntegral sizeX)
(fromIntegral sizeY)
GLUT.initialWindowPosition
$= GL.Position
(fromIntegral posX)
(fromIntegral posY)
_ <- GLUT.createWindow windowName
GLUT.windowSize
$= GL.Size
(fromIntegral sizeX)
(fromIntegral sizeY)
FullScreen (sizeX, sizeY) ->
do GLUT.gameModeCapabilities $=
[ GLUT.Where' GLUT.GameModeWidth GLUT.IsEqualTo sizeX
, GLUT.Where' GLUT.GameModeHeight GLUT.IsEqualTo sizeY ]
void $ GLUT.enterGameMode
-- Switch some things.
-- auto repeat interferes with key up / key down checks.
-- BUGS: this doesn't seem to work?
GLUT.perWindowKeyRepeat $= GLUT.PerWindowKeyRepeatOff
-- Dump State -----------------------------------------------------------------
dumpStateGLUT
:: IORef GLUTState
-> IO ()
dumpStateGLUT _
= do
wbw <- get GLUT.windowBorderWidth
whh <- get GLUT.windowHeaderHeight
rgba <- get GLUT.rgba
rgbaBD <- get GLUT.rgbaBufferDepths
colorBD <- get GLUT.colorBufferDepth
depthBD <- get GLUT.depthBufferDepth
accumBD <- get GLUT.accumBufferDepths
stencilBD <- get GLUT.stencilBufferDepth
doubleBuffered <- get GLUT.doubleBuffered
colorMask <- get GLUT.colorMask
depthMask <- get GLUT.depthMask
putStr $ "* dumpGlutState\n"
++ " windowBorderWidth = " ++ show wbw ++ "\n"
++ " windowHeaderHeight = " ++ show whh ++ "\n"
++ " rgba = " ++ show rgba ++ "\n"
++ " depth rgba = " ++ show rgbaBD ++ "\n"
++ " color = " ++ show colorBD ++ "\n"
++ " depth = " ++ show depthBD ++ "\n"
++ " accum = " ++ show accumBD ++ "\n"
++ " stencil = " ++ show stencilBD ++ "\n"
++ " doubleBuffered = " ++ show doubleBuffered ++ "\n"
++ " mask color = " ++ show colorMask ++ "\n"
++ " depth = " ++ show depthMask ++ "\n"
++ "\n"
-- Display Callback -----------------------------------------------------------
installDisplayCallbackGLUT
:: IORef GLUTState -> [Callback]
-> IO ()
installDisplayCallbackGLUT ref callbacks
= GLUT.displayCallback $= callbackDisplay ref callbacks
callbackDisplay
:: IORef GLUTState -> [Callback]
-> IO ()
callbackDisplay ref callbacks
= do -- clear the display
GL.clear [GL.ColorBuffer, GL.DepthBuffer]
GL.color $ GL.Color4 0 0 0 (1 :: GL.GLfloat)
-- get the display callbacks from the chain
let funs = [f ref | (Display f) <- callbacks]
sequence_ funs
-- swap front and back buffers
GLUT.swapBuffers
-- Don't report errors by default.
-- The windows OpenGL implementation seems to complain for no reason.
-- GLUT.reportErrors
return ()
-- Reshape Callback -----------------------------------------------------------
installReshapeCallbackGLUT
:: IORef GLUTState -> [Callback]
-> IO ()
installReshapeCallbackGLUT ref callbacks
= GLUT.reshapeCallback $= Just (callbackReshape ref callbacks)
callbackReshape
:: IORef GLUTState -> [Callback]
-> GLUT.Size
-> IO ()
callbackReshape ref callbacks (GLUT.Size sizeX sizeY)
= sequence_
$ map (\f -> f (fromEnum sizeX, fromEnum sizeY))
[f ref | Reshape f <- callbacks]
-- KeyMouse Callback ----------------------------------------------------------
installKeyMouseCallbackGLUT
:: IORef GLUTState -> [Callback]
-> IO ()
installKeyMouseCallbackGLUT ref callbacks
= GLUT.keyboardMouseCallback $= Just (callbackKeyMouse ref callbacks)
callbackKeyMouse
:: IORef GLUTState -> [Callback]
-> GLUT.Key
-> GLUT.KeyState
-> GLUT.Modifiers
-> GLUT.Position
-> IO ()
callbackKeyMouse ref callbacks key keystate modifiers (GLUT.Position posX posY)
= sequence_
$ map (\f -> f key' keyState' modifiers' pos)
[f ref | KeyMouse f <- callbacks]
where
key' = glutKeyToKey key
keyState' = glutKeyStateToKeyState keystate
modifiers' = glutModifiersToModifiers modifiers
pos = (fromEnum posX, fromEnum posY)
-- Motion Callback ------------------------------------------------------------
installMotionCallbackGLUT
:: IORef GLUTState -> [Callback]
-> IO ()
installMotionCallbackGLUT ref callbacks
= do GLUT.motionCallback $= Just (callbackMotion ref callbacks)
GLUT.passiveMotionCallback $= Just (callbackMotion ref callbacks)
callbackMotion
:: IORef GLUTState -> [Callback]
-> GLUT.Position
-> IO ()
callbackMotion ref callbacks (GLUT.Position posX posY)
= do let pos = (fromEnum posX, fromEnum posY)
sequence_
$ map (\f -> f pos)
[f ref | Motion f <- callbacks]
-- Idle Callback --------------------------------------------------------------
installIdleCallbackGLUT
:: IORef GLUTState -> [Callback]
-> IO ()
installIdleCallbackGLUT ref callbacks
= GLUT.idleCallback $= Just (callbackIdle ref callbacks)
callbackIdle
:: IORef GLUTState -> [Callback]
-> IO ()
callbackIdle ref callbacks
= sequence_
$ [f ref | Idle f <- callbacks]
-------------------------------------------------------------------------------
-- | Convert GLUTs key codes to our internal ones.
glutKeyToKey :: GLUT.Key -> Key
glutKeyToKey key
= case key of
GLUT.Char '\32' -> SpecialKey KeySpace
GLUT.Char '\13' -> SpecialKey KeyEnter
GLUT.Char '\9' -> SpecialKey KeyTab
GLUT.Char '\ESC' -> SpecialKey KeyEsc
GLUT.Char '\DEL' -> SpecialKey KeyDelete
GLUT.Char c -> Char c
GLUT.SpecialKey GLUT.KeyF1 -> SpecialKey KeyF1
GLUT.SpecialKey GLUT.KeyF2 -> SpecialKey KeyF2
GLUT.SpecialKey GLUT.KeyF3 -> SpecialKey KeyF3
GLUT.SpecialKey GLUT.KeyF4 -> SpecialKey KeyF4
GLUT.SpecialKey GLUT.KeyF5 -> SpecialKey KeyF5
GLUT.SpecialKey GLUT.KeyF6 -> SpecialKey KeyF6
GLUT.SpecialKey GLUT.KeyF7 -> SpecialKey KeyF7
GLUT.SpecialKey GLUT.KeyF8 -> SpecialKey KeyF8
GLUT.SpecialKey GLUT.KeyF9 -> SpecialKey KeyF9
GLUT.SpecialKey GLUT.KeyF10 -> SpecialKey KeyF10
GLUT.SpecialKey GLUT.KeyF11 -> SpecialKey KeyF11
GLUT.SpecialKey GLUT.KeyF12 -> SpecialKey KeyF12
GLUT.SpecialKey GLUT.KeyLeft -> SpecialKey KeyLeft
GLUT.SpecialKey GLUT.KeyUp -> SpecialKey KeyUp
GLUT.SpecialKey GLUT.KeyRight -> SpecialKey KeyRight
GLUT.SpecialKey GLUT.KeyDown -> SpecialKey KeyDown
GLUT.SpecialKey GLUT.KeyPageUp -> SpecialKey KeyPageUp
GLUT.SpecialKey GLUT.KeyPageDown -> SpecialKey KeyPageDown
GLUT.SpecialKey GLUT.KeyHome -> SpecialKey KeyHome
GLUT.SpecialKey GLUT.KeyEnd -> SpecialKey KeyEnd
GLUT.SpecialKey GLUT.KeyInsert -> SpecialKey KeyInsert
GLUT.SpecialKey GLUT.KeyNumLock -> SpecialKey KeyNumLock
GLUT.SpecialKey GLUT.KeyBegin -> SpecialKey KeyBegin
GLUT.SpecialKey GLUT.KeyDelete -> SpecialKey KeyDelete
GLUT.SpecialKey (GLUT.KeyUnknown _) -> SpecialKey KeyUnknown
GLUT.MouseButton GLUT.LeftButton -> MouseButton LeftButton
GLUT.MouseButton GLUT.MiddleButton -> MouseButton MiddleButton
GLUT.MouseButton GLUT.RightButton -> MouseButton RightButton
GLUT.MouseButton GLUT.WheelUp -> MouseButton WheelUp
GLUT.MouseButton GLUT.WheelDown -> MouseButton WheelDown
GLUT.MouseButton (GLUT.AdditionalButton i) -> MouseButton (AdditionalButton i)
-- | Convert GLUTs key states to our internal ones.
glutKeyStateToKeyState :: GLUT.KeyState -> KeyState
glutKeyStateToKeyState state
= case state of
GLUT.Down -> Down
GLUT.Up -> Up
-- | Convert GLUTs key states to our internal ones.
glutModifiersToModifiers
:: GLUT.Modifiers
-> Modifiers
glutModifiersToModifiers (GLUT.Modifiers a b c)
= Modifiers (glutKeyStateToKeyState a)
(glutKeyStateToKeyState b)
(glutKeyStateToKeyState c)
|
gscalzo/HaskellTheHardWay
|
gloss-try/gloss-master/gloss/Graphics/Gloss/Internals/Interface/Backend/GLUT.hs
|
mit
| 12,968 | 0 | 41 | 4,431 | 2,643 | 1,285 | 1,358 | 240 | 37 |
{-# htermination isDigit :: Char -> Bool #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_isDigit_1.hs
|
mit
| 45 | 0 | 2 | 8 | 3 | 2 | 1 | 1 | 0 |
-- 4. Write a program that transposes the text in a file. For instance, it
-- should convert "hello\nworld\n" to "hw\neo\nlr\nll\nod\n".
import Test.HUnit
transposeFile :: String -> String
transposeFile [] = []
transposeFile xs = transposeLines $ lines xs
transposeLines :: [String] -> ??? FFffuu
transposeLines (x:xs) = undefined
-- | Join the first letter of two words
joinWords :: [String] -> String
joinWords [] = ""
joinWords (x:xs) = head x : joinWords xs
-- Tests
basicCase = TestCase (assertEqual "" "hw\nlr\nll\nod\n" (transposeFile "hello\nworld\n"))
tests = TestList [
TestLabel "Basic case" basicCase
]
main = do
runTestTT tests
|
supermitch/learn-haskell
|
real-world-haskell/ch04/Transpose.hs
|
mit
| 661 | 2 | 9 | 119 | 173 | 90 | 83 | -1 | -1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
-- |
-- Helpers to string together parser and renderer by puzzle type.
module Data.Compose
( compose,
)
where
import Data.Lib
import Data.PuzzleTypes
import Data.Yaml
( Parser,
Value,
)
import Draw.Draw
import Draw.Lib
import qualified Draw.PuzzleTypes as D
import Parse.Puzzle
import qualified Parse.PuzzleTypes as R
compose ::
Backend' b =>
PuzzleType ->
((Value, Maybe Value) -> Parser (Drawing b, Maybe (Drawing b)))
compose = handle drawPuzzleMaybeSol
-- | A function to compose an arbitrary matching pair of parser and renderer.
-- In @PuzzleHandler b a@, @b@ is the rendering backend type, while @a@ is
-- the result type of the composition.
type PuzzleHandler b a =
forall p q.
ParsePuzzle p q ->
Drawers b p q ->
a
-- | @handle h t@ composes the parser and renderer for the puzzle
-- type @t@ with the handler @h@.
handle :: Backend' b => PuzzleHandler b a -> PuzzleType -> a
handle f LITS = f R.lits D.lits
handle f Geradeweg = f R.geradeweg D.geradeweg
handle f Fillomino = f R.fillomino D.fillomino
handle f Masyu = f R.masyu D.masyu
handle f Nurikabe = f R.nurikabe D.nurikabe
handle f LatinTapa = f R.latintapa D.latintapa
handle f Sudoku = f R.sudoku D.sudoku
handle f ThermoSudoku = f R.thermosudoku D.thermosudoku
handle f Pyramid = f R.pyramid D.pyramid
handle f RowKropkiPyramid = f R.kpyramid D.kpyramid
handle f SlitherLink = f R.slither D.slither
handle f SlitherLinkLiar = f R.liarslither D.liarslither
handle f WordLoop = f R.wordloop D.wordloop
handle f WordSearch = f R.wordsearch D.wordsearch
handle f CurveData = f R.curvedata D.curvedata
handle f DoubleBack = f R.doubleback D.doubleback
handle f Slalom = f R.slalom D.slalom
handle f Compass = f R.compass D.compass
handle f MeanderingNumbers = f R.meanderingnumbers D.meanderingnumbers
handle f Tapa = f R.tapa D.tapa
handle f JapaneseSums = f R.japanesesums D.japanesesums
handle f Coral = f R.coral D.coral
handle f MaximalLengths = f R.maximallengths D.maximallengths
handle f Labyrinth = f R.labyrinth D.labyrinth
handle f Bahnhof = f R.bahnhof D.bahnhof
handle f BlackoutDominos = f R.blackoutDominos D.blackoutDominos
handle f TwilightTapa = f R.tapa D.tapa
handle f TapaCave = f R.tapa D.tapa
handle f DominoPillen = f R.dominoPills D.dominoPills
handle f AngleLoop = f R.angleLoop D.angleLoop
handle f Shikaku = f R.shikaku D.shikaku
handle f SlovakSums = f R.slovaksums D.slovaksums
handle f Anglers = f R.anglers D.anglers
handle f Dominos = f R.dominos D.dominos
handle f FillominoCheckered = f R.fillomino D.fillominoCheckered
handle f FillominoLoop = f R.fillominoLoop D.fillominoLoop
handle f Cave = f R.cave D.cave
handle f Numberlink = f R.numberlink D.numberlink
handle f Skyscrapers = f R.skyscrapers D.skyscrapers
handle f SkyscrapersFrac = f R.tightfitskyscrapers D.tightfitskyscrapers
handle f SkyscrapersTightfit = f R.tightfitskyscrapers D.tightfitskyscrapers
handle f TurningFences = f R.slither D.slither
handle f Summon = f R.summon D.summon
handle f Baca = f R.baca D.baca
handle f Buchstabensalat = f R.buchstabensalat D.buchstabensalat
handle f Doppelblock = f R.doppelblock D.doppelblock
handle f SudokuDoppelblock = f R.sudokuDoppelblock D.sudokuDoppelblock
handle f Loopki = f R.loopki D.loopki
handle f Scrabble = f R.scrabble D.scrabble
handle f Neighbors = f R.neighbors D.neighbors
handle f Starbattle = f R.starbattle D.starbattle
handle f Heyawake = f R.heyawake D.heyawake
handle f Pentominous = f R.pentominous D.pentominous
handle f ColorAkari = f R.colorakari D.colorakari
handle f PersistenceOfMemory = f R.persistenceOfMemory D.persistenceOfMemory
handle f ABCtje = f R.abctje D.abctje
handle f Kropki = f R.kropki D.kropki
handle f StatuePark = f R.statuepark D.statuepark
handle f PentominousBorders = f R.pentominousBorders D.pentominousBorders
handle f NanroSignpost = f R.nanroSignpost D.nanroSignpost
handle f TomTom = f R.tomTom D.tomTom
handle f Illumination = f R.illumination D.illumination
handle f Pentopia = f R.pentopia D.pentopia
handle f GreaterWall = f R.greaterWall D.greaterWall
handle f Galaxies = f R.galaxies D.galaxies
handle f Mines = f R.mines D.mines
handle f Tents = f R.tents D.tents
handle f PentominoSums = f R.pentominoSums D.pentominoSums
handle f CoralLITS = f R.coralLits D.coralLits
handle f CoralLITSO = f R.coralLitso D.coralLitso
handle f Snake = f R.snake D.snake
handle f CountryRoad = f R.countryRoad D.countryRoad
handle f KillerSudoku = f R.killersudoku D.killersudoku
handle f JapaneseSumsMasyu = f R.japsummasyu D.japsummasyu
handle f ArrowSudoku = f R.arrowsudoku D.arrowsudoku
handle f DualLoop = f R.dualloop D.dualloop
handle _ t =
if isGeneric t
then impossible
else error $ "puzzle type unhandled: " ++ show t
-- | Handler that parses puzzle and an optional solution from a pair of
-- corresponding YAML values, and renders both individually, optionally
-- for the solution.
drawPuzzleMaybeSol ::
PuzzleHandler
b
((Value, Maybe Value) -> Parser (Drawing b, Maybe (Drawing b)))
drawPuzzleMaybeSol (pp, ps) (Drawers dp ds) (p, s) = do
p' <- pp p
s' <- traverse ps s
let mps = case s' of
Nothing -> Nothing
Just s'' -> Just (p', s'')
return (dp p', ds <$> mps)
|
robx/puzzle-draw
|
src/Data/Compose.hs
|
mit
| 5,384 | 0 | 14 | 889 | 1,835 | 899 | 936 | 119 | 2 |
module LtsHs.Version where
import System.Directory (
getHomeDirectory,
getDirectoryContents,
doesDirectoryExist,
makeAbsolute
)
import System.FilePath (
pathSeparator
)
import Data.List.Split (splitOn)
import Data.List (find)
import Text.Read (readMaybe)
-- LTS Haskell version (major, minor)
data Version = Version Int Int deriving (Show, Eq, Ord)
versionString :: Version -> String
versionString (Version major minor) = show major ++ "." ++ show minor
-- Are two versions exepected to be compatible?
isCompatible :: Version -> Version -> Bool
isCompatible (Version major1 _) (Version major2 _) = major1 == major2
-- Extract version at a given file path.
extractVersion :: FilePath -> IO (Maybe Version)
extractVersion path = do
absolute <- makeAbsolute path
let dirs = splitOn [pathSeparator] absolute
version = do
lastDirName <- find (not . null) $ reverse dirs
let majorMinor = splitOn "." lastDirName
case fmap (readMaybe :: String -> Maybe Int) majorMinor of
[Just major, Just minor] -> Just (Version major minor)
_ -> Nothing
return version
|
tkawachi/ltshs
|
src/LtsHs/Version.hs
|
mit
| 1,121 | 0 | 17 | 228 | 339 | 175 | 164 | 27 | 2 |
module Main where
import Test.Hspec
import Test.Hspec.Runner (defaultConfig, hspecWith)
import App
main :: IO ()
main = hspecWith defaultConfig specs >> return ()
specs :: Spec
specs = describe "App" $ do
it "foo is always a string with foo" $ do
foo `shouldBe` "foo"
it "inc should always increment" $ do
-- TODO: Fix this error
--
-- execute ./startTestLoop on the root of the testloop-example
-- project and then fix this code
inc 1 `shouldBe` 2
|
roman/testloop
|
examples/testloop-example/test/TestSuite.hs
|
mit
| 481 | 0 | 12 | 110 | 117 | 63 | 54 | 12 | 1 |
import Data.Word
import Data.List(elemIndex)
import Data.Maybe
import Data.Complex
import qualified Data.Array.Repa as R
import Data.Array.Repa.IO.BMP
import System.Environment
type Number = Double
type ComplexNumber = Complex Number
type IterationCount = Integer
type PointData = (ComplexNumber, IterationCount)
type RootData = (Int, IterationCount)
type Bounds = (Number, Number, Number, Number)
type Step = Number
type Color = (Word8, Word8, Word8)
e :: ComplexNumber
e = (exp 1) :+ 0
data Function = Constant ComplexNumber
| Z
| Sum Function Function
| Product Function Function
| Quotient Function Function
| Power ComplexNumber Function
| Sin Function
| Cos Function
| Exponential ComplexNumber Function
| Log ComplexNumber Function
| Undefined
| Indeterminate
deriving (Show)
realConstant :: Number -> Function
realConstant n = Constant (n :+ 0)
derivative :: Function -> Function
derivative (Constant _) = realConstant 0
derivative Z = realConstant 1
derivative (Sum u v) = Sum (derivative u) (derivative v)
derivative (Product u v) = Sum (Product (derivative u) v) (Product u (derivative v))
derivative (Quotient u v) = (Quotient (Sum (Product v (derivative u)) (Product (Product (realConstant (-1)) u) (derivative v))) (Power 2 v))
derivative (Power p f) = Product (Product (Constant p) (Power (p - 1) f)) (derivative f)
derivative (Sin f) = Product (Cos f) (derivative f)
derivative (Cos f) = Product (Product (realConstant (-1)) (Sin f)) (derivative f)
derivative (Exponential b f) = Product (Product (Exponential b f) (Log e (Constant b))) (derivative f)
derivative (Log b f) = Quotient (derivative f) (Product f (Log e (Constant b)))
derivative Undefined = Undefined
derivative Indeterminate = Indeterminate
evaluate :: Function -> ComplexNumber -> ComplexNumber
evaluate (Constant a) z = a
evaluate Z z = z
evaluate (Sum u v) z = (evaluate u z) + (evaluate v z)
evaluate (Product u v) z = (evaluate u z) * (evaluate v z)
evaluate (Quotient u v) z = (evaluate u z) / (evaluate v z)
evaluate (Power p f) z = (evaluate f z) ** p
evaluate (Sin f) z = sin (evaluate f z)
evaluate (Cos f) z = cos (evaluate f z)
evaluate (Exponential b f) z = b ** (evaluate f z)
evaluate (Log b f) z = logBase b (evaluate f z)
evaluate Undefined z = undefined
evaluate Indeterminate z = undefined
maxIterations :: IterationCount
maxIterations = 100
epsilon :: Number
epsilon = 1e-12
newton :: Function -> Function -> ComplexNumber -> PointData
newton f f' z0 = newton' z1 z0 0
where approximate z = z - (evaluate f z) / (evaluate f' z)
z1 = approximate z0
newton' current previous n
| n > maxIterations = (current, n)
| magnitude (current - previous) < epsilon = (current, n)
| otherwise = newton' (approximate current) current (n + 1)
windowApply :: (ComplexNumber -> PointData) -> Bounds -> Step -> [PointData]
windowApply f (top, left, bottom, right) step = [f (x :+ y ) | y <- ys, x <- xs]
where xs = [left, left + step .. right]
ys = [top, top + step .. bottom]
approximateIndex :: ComplexNumber -> [ComplexNumber] -> Maybe Int
approximateIndex z zs = elemIndex True [magnitude (z - zi) < epsilon * 2 | zi <- zs]
closestIndex :: ComplexNumber -> [ComplexNumber] -> Int
closestIndex z zs = snd . minimum $ zip [magnitude (z - zi) | zi <- zs] [0..]
closeEnough :: ComplexNumber -> [ComplexNumber] -> Bool
closeEnough z zs = case approximateIndex z zs of
Just _ -> True
Nothing -> False
roots :: [PointData] -> [ComplexNumber]
roots ps = foldr checkRoot [] zs
where checkRoot z roots
| z `closeEnough` roots = roots
| otherwise = z:roots
zs = fst . unzip $ ps
assignRoot :: [ComplexNumber] -> PointData -> RootData
assignRoot rs p@(z, i) = (closestIndex z rs, i)
colorRoot :: RootData -> Color
colorRoot (n, i) = (ra, ga, ba)
where colors = [ (0, 0, 0)
, (255, 0, 0)
, (0, 255, 0)
, (0, 0, 255)
, (255, 255, 0)
, (255, 0, 255)
, (0, 255, 255)
, (255, 255, 255)
]
(r, g, b) = colors !! n
ii = max i 1
ra = fromIntegral . min 255 $ 4 * r `div` ii
ga = fromIntegral . min 255 $ 4 * g `div` ii
ba = fromIntegral . min 255 $ 4 * b `div` ii
colorRoots :: Function -> Bounds -> Step -> [Color]
colorRoots f bounds step = map colorRoot rds
where ps = windowApply (newton f (derivative f)) bounds step
rs = roots ps
rds = map (assignRoot rs) ps
arrayify :: Int -> Int -> [Color] -> R.Array R.U R.DIM2 Color
arrayify width height =
R.fromListUnboxed (R.Z R.:. height R.:. width :: R.DIM2)
f = Sum (Power 3 Z) (realConstant (-1))
main = do
args <- getArgs
let [fileName, stringTop, stringLeft, stringBottom, stringRight, stringStep] = args
top = read stringTop
left = read stringLeft
bottom = read stringBottom
right = read stringRight
step = read stringStep
width = floor ((right - left) / step) + 1
height = floor ((bottom - top) / step) + 1
colorList = colorRoots f (top, left, bottom, right) step
colorArray = arrayify width height colorList
writeImageToBMP fileName colorArray
|
jlubi333/newton-hs
|
Main.hs
|
mit
| 5,507 | 0 | 16 | 1,503 | 2,251 | 1,197 | 1,054 | 127 | 2 |
{-# LANGUAGE DeriveGeneric, OverloadedStrings, TemplateHaskell #-}
{-|
Michelson's speed of light dataset - five repeated measurements of the speed of light.
Data from <https://github.com/datasets-io/michelson-speed-of-light>
The embedded dataset is Copyright (c) 2015 The Compute.io Authors.
-}
module Numeric.Datasets.Michelson where
import Numeric.Datasets
import Data.FileEmbed
import Data.ByteString.Lazy (fromStrict)
michelson :: [[Double]]
michelson = readDataset JSON (fromStrict $(embedFile "datafiles/michelson.json"))
|
glutamate/datasets
|
datasets/src/Numeric/Datasets/Michelson.hs
|
mit
| 538 | 0 | 10 | 64 | 64 | 38 | 26 | 7 | 1 |
multThree :: (Num a) => a -> a -> a -> a
multThree x y z = x * y * z
compareWithHundred :: (Ord a, Num a) => a -> Ordering
compareWithHundred x = compare 100 x
compareWithHundredBetter :: (Ord a, Num a) => a -> Ordering
compareWithHundredBetter = compare 100
divideByTen :: (Floating a) => a -> a
divideByTen = (/10)
isUpperAlphaNum :: Char -> Bool
isUpperAlphaNum = (`elem` ['A'..'Z'])
|
pegurnee/2015-01-341
|
haskell/higherOrderFunctions.hs
|
mit
| 387 | 0 | 8 | 72 | 168 | 92 | 76 | 10 | 1 |
-- |
-- Module: Math.NumberTheory.MoebiusInversion.IntTests
-- Copyright: (c) 2016 Andrew Lelechenko
-- Licence: MIT
-- Maintainer: Andrew Lelechenko <[email protected]>
-- Stability: Provisional
--
-- Tests for Math.NumberTheory.MoebiusInversion.Int
--
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module Math.NumberTheory.MoebiusInversion.IntTests
( testSuite
) where
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck as QC hiding (Positive)
import Math.NumberTheory.MoebiusInversion.Int
import Math.NumberTheory.ArithmeticFunctions
import Math.NumberTheory.TestUtils
totientSumProperty :: Positive Int -> Bool
totientSumProperty (Positive n) = toInteger (totientSum n) == sum (map totient [1 .. toInteger n])
totientSumSpecialCase1 :: Assertion
totientSumSpecialCase1 = assertEqual "totientSum" 4496 (totientSum 121)
totientSumSpecialCase2 :: Assertion
totientSumSpecialCase2 = assertEqual "totientSum" 0 (totientSum (-9001))
totientSumZero :: Assertion
totientSumZero = assertEqual "totientSum" 0 (totientSum 0)
generalInversionProperty :: (Int -> Int) -> Positive Int -> Bool
generalInversionProperty g (Positive n)
= g n == sum [f (n `quot` k) | k <- [1 .. n]]
&& f n == sum [fromInteger (moebius (toInteger k)) * g (n `quot` k) | k <- [1 .. n]]
where
f = generalInversion g
testSuite :: TestTree
testSuite = testGroup "Int"
[ testGroup "totientSum"
[ testSmallAndQuick "matches definitions" totientSumProperty
, testCase "special case 1" totientSumSpecialCase1
, testCase "special case 2" totientSumSpecialCase2
, testCase "zero" totientSumZero
]
, QC.testProperty "generalInversion" generalInversionProperty
]
|
cfredric/arithmoi
|
test-suite/Math/NumberTheory/MoebiusInversion/IntTests.hs
|
mit
| 1,765 | 0 | 13 | 313 | 415 | 228 | 187 | 30 | 1 |
-- Copyright (c) Microsoft. All rights reserved.
-- Licensed under the MIT license. See LICENSE file in the project root for full license information.
{-# LANGUAGE QuasiQuotes, OverloadedStrings #-}
module Language.Bond.Codegen.Cpp.Apply_cpp (apply_cpp) where
import Data.Text.Lazy (Text)
import Text.Shakespeare.Text
import Language.Bond.Syntax.Types
import Language.Bond.Codegen.TypeMapping
import Language.Bond.Codegen.Util
import Language.Bond.Codegen.Cpp.ApplyOverloads
import qualified Language.Bond.Codegen.Cpp.Util as CPP
-- | Codegen template for generating /base_name/_apply.cpp containing
-- definitions of the @Apply@ function overloads for the specified protocols.
apply_cpp :: [Protocol] -- ^ List of protocols for which @Apply@ overloads should be generated
-> MappingContext -> String -> [Import] -> [Declaration] -> (String, Text)
apply_cpp protocols cpp file _imports declarations = ("_apply.cpp", [lt|
#include "#{file}_apply.h"
#include "#{file}_reflection.h"
#{CPP.openNamespace cpp}
#{newlineSepEnd 1 (applyOverloads protocols cpp attr body) declarations}
#{CPP.closeNamespace cpp}
|])
where
body = [lt|
{
return bond::Apply<>(transform, value);
}|]
attr = [lt||]
|
ant0nsc/bond
|
compiler/src/Language/Bond/Codegen/Cpp/Apply_cpp.hs
|
mit
| 1,235 | 0 | 10 | 183 | 163 | 111 | 52 | 14 | 1 |
module PreludData where
import DataP
-- data types from prelude, so we can derive things for these
-- as needed without parsing the whole prelude
-- users may want to add commonly-used datatypes to this list, to save
-- repeatedly searching for a type. The list data is generated using the
-- 'test' rule on the required datatypes.
preludeData :: [Data]
preludeData = [
D{name="Bool",constraints=[],vars=[],body=[
Body{constructor="False",labels=[],types=[]},
Body{constructor="True",labels=[],types=[]}]
,derives=["Eq", "Ord", "Ix", "Enum", "Read", "Show", "Bounded"]
,statement=DataStmt},
D{name="Maybe",constraints=[],vars=["a"],body=[
Body{constructor="Just",labels=[],types=[Var "a"]},
Body{constructor="Nothing",labels=[],types=[]}] ,
derives=["Eq", "Ord", "Read", "Show"],statement=DataStmt},
D{name="Either",constraints=[],vars=["a", "b"],body=[
Body{constructor="Left",labels=[],types=[Var "a"]},
Body{constructor="Right",labels=[],types=[Var "b"]}],
derives=["Eq", "Ord", "Read", "Show"],statement=DataStmt},
D{name="Ordering",constraints=[],vars=[],body=[
Body{constructor="LT",labels=[],types=[]},
Body{constructor="EQ",labels=[],types=[]},
Body{constructor="GT",labels=[],types=[]}],
derives=["Eq", "Ord", "Ix", "Enum", "Read", "Show", "Bounded"],
statement=DataStmt}]
|
ajhc/drift
|
src/PreludData.hs
|
mit
| 1,321 | 32 | 12 | 145 | 563 | 357 | 206 | 23 | 1 |
module Light.Geometry (module X)
where
import Light.Geometry.AABB as X
import Light.Geometry.Matrix as X
import Light.Geometry.Normal as X
import Light.Geometry.Point as X
import Light.Geometry.Quaternion as X
import Light.Geometry.Ray as X
import Light.Geometry.Transform as X
import Light.Geometry.Vector as X
|
jtdubs/Light
|
src/Light/Geometry.hs
|
mit
| 314 | 0 | 4 | 39 | 76 | 56 | 20 | 9 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Y2020.M11.D11.Exercise where
-- Okay, now, finally, we have alliances of the world in one structure:
import Y2020.M11.D10.Exercise (go)
-- so, convert that to graph-data and upload to our graph.
-- ... you do remember our graph of countries / continents / airbases, yes?
import Y2020.M10.D12.Exercise -- for Country
import Y2020.M10.D28.Exercise hiding (Alliance, name, countries) -- for Name
import Y2020.M10.D30.Exercise -- for AllianceMap
import Data.Relation
import Graph.Query
-- that means converting our AllianceMap into a set of Relation-values
data Member = MEMBER_OF
deriving Show
data AllianceNode = Ally Name | Nation Country
deriving Eq
allianceGraph :: AllianceMap -> [Relation AllianceNode Member AllianceNode]
allianceGraph = undefined
-- which means these things have to be instanced for this:
instance Node AllianceNode where
asNode = undefined
instance Edge Member where
asEdge = undefined
-- with these relations we should be able to upload these Alliances to the Graph
{--
>>> graphEndpoint
...
>>> let url = it
>>> go
...
>>> let am = it
>>> cyphIt url (allianceGraph am)
... and now we can start to ask some alliance-y questions of our airbases.
--}
|
geophf/1HaskellADay
|
exercises/HAD/Y2020/M11/D11/Exercise.hs
|
mit
| 1,272 | 0 | 7 | 243 | 151 | 97 | 54 | 18 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Holumbus.Index.Inverted.CompressedPrefixMem
( Inverted(..)
, Parts
, Part
, Inverted0
, InvertedCompressed
, InvertedSerialized
, InvertedCSerialized
, InvertedOSerialized
, ComprOccurrences(..)
, emptyInverted
, emptyInverted0
, emptyInvertedCompressed
, emptyInvertedSerialized
, emptyInvertedCSerialized
, emptyInvertedOSerialized
, mapOcc
, zipOcc
, emptyOcc
, theOcc
, nullOcc
, unionOcc
, diffOcc
, insertPosOcc
, deletePosOcc
, updateDocIdOcc
, deleteDocIds
, removeDocIdsInverted
)
where
import Control.Arrow (second)
import Control.DeepSeq
import qualified Data.Binary as B
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Short as SS
import Data.Function (on)
import Data.List (foldl', sortBy)
import qualified Data.Map.Strict as M
import Data.Maybe
import qualified Data.StringMap.Strict as PT
import Data.Typeable
import qualified Holumbus.ByteStringCompression as BZ
import Holumbus.Index.Common
import Holumbus.Index.Compression
import Text.XML.HXT.Core (PU, XmlPickler, xpAttr, xpElem,
xpList, xpPair, xpText, xpWrap,
xpickle)
#if sizeable == 1
import Data.Size
#endif
-- ----------------------------------------------------------------------------
compress :: BL.ByteString -> BL.ByteString
compress = BZ.compressBZipSmart
decompress :: BL.ByteString -> BL.ByteString
decompress = BZ.decompressBZipSmart
traceFrom :: Occurrences -> Occurrences
traceFrom = id
-- traceFrom = traceOccPos
-- ----------------------------------------------------------------------------
class ComprOccurrences s where
toOccurrences :: s -> Occurrences
fromOccurrences :: Occurrences -> s
mapOcc :: (ComprOccurrences s) => (Occurrences -> Occurrences) -> s -> s
mapOcc f = fromOccurrences . f . toOccurrences
zipOcc :: (ComprOccurrences s) => (Occurrences -> Occurrences -> Occurrences) -> s -> s -> s
zipOcc op x y = fromOccurrences $ op (toOccurrences x)(toOccurrences y)
emptyOcc :: (ComprOccurrences s) => s
emptyOcc = fromOccurrences $ emptyOccurrences
theOcc :: (ComprOccurrences s) => s -> Occurrences
theOcc = toOccurrences
nullOcc :: (ComprOccurrences s) => s -> Bool
nullOcc = (== emptyOccurrences) . toOccurrences -- better nullOccurrences, but not yet there
unionOcc :: (ComprOccurrences s) => Occurrences -> s -> s
unionOcc os = mapOcc $ mergeOccurrences os
diffOcc :: (ComprOccurrences s) => Occurrences -> s -> s
diffOcc os = mapOcc $ substractOccurrences os
insertPosOcc :: (ComprOccurrences s) => DocId -> Position -> s -> s
insertPosOcc d p = mapOcc $ insertOccurrence d p
deletePosOcc :: (ComprOccurrences s) => DocId -> Position -> s -> s
deletePosOcc d p = mapOcc $ deleteOccurrence d p
updateDocIdOcc :: (ComprOccurrences s) => (DocId -> DocId) -> s -> s
updateDocIdOcc f = mapOcc $ updateOccurrences f
deleteDocIds :: (ComprOccurrences s) => Occurrences -> s -> s
deleteDocIds ids = mapOcc $ flip diffOccurrences ids
-- ----------------------------------------------------------------------------
--
-- auxiliary type for strict Bytestrings
-- the use of the smart constructor assures that the Bytestring is
-- fully evaluated before constructing the value
--
-- This type is used in the variants working with compressed and/or serialised data
-- to represent occurences 'OccCompressed', 'OccSerialized', 'OccCserialized', OccOSerialized'
--
-- The constructor must not be called directly, only via mkBs
--
-- The SByteString is a candidate for a BS.ShortByteString available with bytestring 0.10.4,
-- then 5 machine words can be saved per value
newtype SByteString = Bs { unSs :: SS.ShortByteString }
deriving (Eq, Show, Typeable)
mkBs :: BS.ByteString -> SByteString
mkBs s = Bs $!! SS.toShort s
unBs :: SByteString -> BS.ByteString
unBs = SS.fromShort . unSs
-- in mkBs the ByteString is physically copied into a ShortByteString
-- to avoid sharing data with other possibly very large strings
-- this can occur e.g in the Binary instance with get
-- Working with ShortByteString prevents fragmentation of the heap store,
-- ByteStrings can't be move in the heap (are PINNED), ShortByteString can.
instance NFData SByteString where
-- use default implementation: eval to WHNF, and that's sufficient
instance B.Binary SByteString where
put = B.put . unBs
get = B.get >>= return . mkBs
-- to avoid sharing the data with with the input the ByteString is physically copied
-- before return. This should be the single place where sharing is introduced,
-- else the copy must be moved to mSBs
-- ----------------------------------------------------------------------------
--
-- the pure occurrence type, just wrapped in a newtype for instance declarations
-- and for forcing evaluation
newtype Occ0 = Occ0 { unOcc0 :: Occurrences }
deriving (Show, Typeable)
mkOcc0 :: Occurrences -> Occ0
mkOcc0 os = Occ0 $!! os
instance ComprOccurrences Occ0 where
fromOccurrences = mkOcc0 . traceFrom
toOccurrences = unOcc0
instance NFData Occ0 where
-- use default implementation: eval to WHNF, and that's sufficient
instance B.Binary Occ0 where
put = B.put . unOcc0
get = B.get >>= return . mkOcc0
-- ----------------------------------------------------------------------------
--
-- the simple-9 compressed occurrence type, just wrapped in a newtype for instance declarations
newtype OccCompressed = OccCp { unOccCp :: CompressedOccurrences }
deriving (Eq, Show, Typeable)
mkOccCp :: Occurrences -> OccCompressed
mkOccCp os = OccCp $!! deflateOcc os
instance ComprOccurrences OccCompressed where
fromOccurrences = mkOccCp . traceFrom
toOccurrences = inflateOcc . unOccCp
instance NFData OccCompressed where
-- use default implementation: eval to WHNF, and that's sufficient
instance B.Binary OccCompressed where
put = B.put . unOccCp
get = B.get >>= ((return . OccCp) $!!)
-- ----------------------------------------------------------------------------
--
-- the simpe-9 compresses occurrences serialized into a byte strings
newtype OccSerialized = OccBs { unOccBs :: SByteString }
deriving (Eq, Show, NFData, Typeable)
instance ComprOccurrences OccSerialized where
fromOccurrences = OccBs . mkBs . BL.toStrict . B.encode . deflateOcc . traceFrom
toOccurrences = inflateOcc . B.decode . BL.fromStrict . unBs . unOccBs
instance B.Binary OccSerialized where
put = B.put . unOccBs
get = B.get >>= return . OccBs
-- ----------------------------------------------------------------------------
--
-- the simple-9 compressed occurrences serialized and bzipped into a byte string
newtype OccCSerialized = OccCBs { unOccCBs :: SByteString }
deriving (Eq, Show, NFData, Typeable)
instance ComprOccurrences OccCSerialized where
fromOccurrences = OccCBs . mkBs . BL.toStrict . compress . B.encode . deflateOcc . traceFrom
toOccurrences = inflateOcc . B.decode . decompress . BL.fromStrict . unBs . unOccCBs
instance B.Binary OccCSerialized where
put = B.put . unOccCBs
get = B.get >>= return . OccCBs
-- ----------------------------------------------------------------------------
--
-- the pure occurrences serialized and bzipped into a byte string
-- this seems to be the best choice: compression is about 4% better then simple-9 & bzip
-- and lookup is about 8% better
newtype OccOSerialized = OccOBs { unOccOBs :: SByteString }
deriving (Eq, Show, NFData, Typeable)
instance ComprOccurrences OccOSerialized where
fromOccurrences = OccOBs . mkBs . BL.toStrict . compress . B.encode .traceFrom
toOccurrences = B.decode . decompress . BL.fromStrict . unBs . unOccOBs
instance B.Binary OccOSerialized where
put = B.put . unOccOBs
get = B.get >>= return . OccOBs
-- ----------------------------------------------------------------------------
-- | The index consists of a table which maps documents to ids and a number of index parts.
newtype Inverted occ = Inverted
{ unInverted :: Parts occ -- ^ The parts of the index, each representing one context.
}
deriving (Show, Eq, NFData, Typeable)
-- | The index parts are identified by a name, which should denote the context of the words.
type Parts occ = M.Map Context (Part occ)
-- | The index part is the real inverted index. Words are mapped to their occurrences.
-- The part is implemented as a prefix tree
type Part occ = PT.StringMap occ
-- ----------------------------------------------------------------------------
instance (ComprOccurrences occ) => XmlPickler (Inverted occ) where
xpickle = xpElem "indexes" $
xpWrap (Inverted, unInverted) xpParts
xpParts :: (ComprOccurrences occ) => PU (Parts occ)
xpParts = xpWrap (M.fromList, M.toList) (xpList xpContext)
where
xpContext = xpElem "part" (xpPair (xpAttr "id" xpText) xpPart)
xpPart :: (ComprOccurrences occ) => PU (Part occ)
xpPart = xpElem "index" (xpWrap (PT.fromList, PT.toList) (xpList xpWord))
where
xpWord = xpElem "word" $
xpPair (xpAttr "w" xpText)
(xpWrap (fromOccurrences, toOccurrences) xpOccurrences)
-- ----------------------------------------------------------------------------
instance (B.Binary occ) => B.Binary (Inverted occ) where
put = B.put . unInverted
get = B.get >>= return . Inverted
-- ----------------------------------------------------------------------------
instance (B.Binary occ, ComprOccurrences occ) => HolIndex (Inverted occ) where
sizeWords = M.foldl' (\ x y -> x + PT.size y) 0 . unInverted
contexts = fmap fst . M.toList . unInverted
allWords i c = fmap (second toOccurrences) .
PT.toList .
getPart c $ i
prefixCase i c q = fmap (second toOccurrences) .
PT.toListShortestFirst .
PT.prefixFilter q .
getPart c $ i
prefixNoCase i c q = fmap (second toOccurrences) .
PT.toListShortestFirst .
PT.prefixFilterNoCase q .
getPart c $ i
lookupCase i c q = fmap ((,) q . toOccurrences) .
maybeToList .
PT.lookup q .
getPart c $ i
lookupNoCase i c q = fmap (second toOccurrences) .
PT.toList .
PT.lookupNoCase q .
getPart c $ i
mergeIndexes = zipInverted $ M.unionWith $ PT.unionWith (zipOcc mergeOccurrences)
substractIndexes = zipInverted $ M.differenceWith $ substractPart
insertOccurrences c w o i = mergeIndexes i (singletonInverted c w o) -- see "http://holumbus.fh-wedel.de/hayoo/hayoo.html#0:unionWith%20module%3AData.Map"
deleteOccurrences c w o i = substractIndexes i (singletonInverted c w o)
toList = concatMap (uncurry convertPart) . toListInverted
where
convertPart c = map (\(w, o) -> (c, w, toOccurrences o)) . PT.toList
splitByContexts = splitInverted
. map ( (\ i -> (sizeWords i, i))
. Inverted
. uncurry M.singleton
)
. toListInverted
splitByDocuments i = splitInverted ( map (uncurry convert) $
toListDocIdMap $
unionsWithDocIdMap (M.unionWith (M.unionWith unionPos)) docResults
)
where
docResults = map (\c -> resultByDocument c (allWords i c)) (contexts i)
convert d cs = foldl' makeIndex (0, emptyInverted) (M.toList cs)
where
makeIndex r (c, ws) = foldl' makeOcc r (M.toList ws)
where
makeOcc (rs, ri) (w, p) = (sizePos p + rs, insertOccurrences c w (singletonDocIdMap d p) ri)
splitByWords i = splitInverted ( map (uncurry convert) .
M.toList .
M.unionsWith (M.unionWith mergeOccurrences) $ wordResults
)
where
wordResults = map (\c -> resultByWord c (allWords i c)) (contexts i)
convert w cs = foldl' makeIndex (0, emptyInverted) (M.toList cs)
where
makeIndex (rs, ri) (c, o) = (rs + sizeOccurrences o, insertOccurrences c w o ri)
updateDocIds f = mapInverted (M.mapWithKey updatePart)
where
updatePart c = PT.mapWithKey (updateOcc (f c))
updateOcc f' w = mapOcc $ updateOccurrences (f' w)
-- ----------------------------------------------------------------------------
-- | Return a part of the index for a given context.
getPart :: Context -> Inverted i -> Part i
getPart c = fromMaybe PT.empty . M.lookup c . unInverted
-- | Substract one index part from another.
substractPart :: (ComprOccurrences i) => Part i -> Part i -> Maybe (Part i)
substractPart p1 p2
| PT.null res = Nothing
| otherwise = Just res
where
res = diffPart p1 p2
diffPart :: (ComprOccurrences i) => Part i -> Part i -> Part i
diffPart = PT.differenceWith subtractDiffLists
where
subtractDiffLists o1 o2
| nullOcc res = Nothing
| otherwise = Just res
where
res = zipOcc substractOccurrences o1 o2
removeDocIdsPart :: (ComprOccurrences i) => Occurrences -> Part i -> Part i
removeDocIdsPart ids = PT.foldrWithKey removeDocIds PT.empty
where
removeDocIds k occ acc
| nullOcc occ' = acc
| otherwise = PT.insert k occ' acc
where
occ' = deleteDocIds ids occ
-- ----------------------------------------------------------------------------
mapInverted :: (Parts i -> Parts i) -> Inverted i -> Inverted i
mapInverted f = Inverted . f . unInverted
zipInverted :: (Parts i -> Parts i -> Parts i) -> Inverted i -> Inverted i -> Inverted i
zipInverted op i1 i2 = Inverted $ op (unInverted i1) (unInverted i2)
emptyInverted :: Inverted i
emptyInverted = Inverted M.empty
toListInverted :: Inverted i -> [(Context, Part i)]
toListInverted = M.toList . unInverted
-- | Create an index with just one word in one context.
singletonInverted :: (ComprOccurrences i) => Context -> String -> Occurrences -> Inverted i
singletonInverted c w o = Inverted . M.singleton c . PT.singleton w . fromOccurrences $ o
-- | Remove DocIds from index
removeDocIdsInverted :: (ComprOccurrences i) => Occurrences -> Inverted i -> Inverted i
removeDocIdsInverted ids = mapInverted $ M.map (removeDocIdsPart ids)
-- ----------------------------------------------------------------------------
--
-- copied from Holumbus.Index.Inverted.Memory
splitInverted :: (B.Binary i, ComprOccurrences i) => [(Int, Inverted i)] -> Int -> [Inverted i]
splitInverted inp n = allocate mergeIndexes stack buckets
where
buckets = zipWith const (createBuckets n) stack
stack = reverse (sortBy (compare `on` fst) inp)
-- | Allocates values from the first list to the buckets in the second list.
allocate :: (a -> a -> a) -> [(Int, a)] -> [(Int, a)] -> [a]
allocate _ _ [] = []
allocate _ [] ys = map snd ys
allocate f (x:xs) (y:ys) = allocate f xs (sortBy (compare `on` fst) ((combine x y):ys))
where
combine (s1, v1) (s2, v2) = (s1 + s2, f v1 v2)
-- | Create empty buckets for allocating indexes.
createBuckets :: Int -> [(Int, Inverted i)]
createBuckets n = (replicate n (0, emptyInverted))
-- ----------------------------------------------------------------------------
--
-- the 5 variants for the inverted index as prefix tree,
-- | The pure inverted index implemented as a prefix tree without any space optimizations.
-- This may be taken as a reference for space and time measurements for the other index structures
type Inverted0 = Inverted Occ0
-- | The inverted index with simple-9 encoding of the occurence sets
type InvertedCompressed = Inverted OccCompressed
-- | The inverted index with serialized occurence maps with simple-9 encoded sets
type InvertedSerialized = Inverted OccSerialized
-- | The inverted index with serialized occurence maps with simple-9 encoded sets
-- and with the serialized bytestrings compressed with bzip2
type InvertedCSerialized = Inverted OccCSerialized
-- | The pure inverted index with serialized occurence maps
-- and with the serialized bytestrings compressed with bzip2, no simple-9 encoding.
-- This is the most space efficient index of the 5 variants, even a few percent smaller
-- then InvertedCSerialized, and a few percent faster in lookup
type InvertedOSerialized = Inverted OccOSerialized
-- ----------------------------------------------------------------------------
emptyInverted0 :: Inverted0
emptyInverted0 = emptyInverted
emptyInvertedCompressed :: InvertedCompressed
emptyInvertedCompressed = emptyInverted
emptyInvertedSerialized :: InvertedSerialized
emptyInvertedSerialized = emptyInverted
emptyInvertedCSerialized :: InvertedCSerialized
emptyInvertedCSerialized = emptyInverted
emptyInvertedOSerialized :: InvertedOSerialized
emptyInvertedOSerialized = emptyInverted
-- ----------------------------------------------------------------------------
#if sizeable == 1
instance Sizeable SByteString where
dataOf = dataOf . unSs
bytesOf = bytesOf . unSs
statsOf = statsOf . unSs
instance Sizeable OccSerialized where
dataOf = dataOf . unOccBs
bytesOf = bytesOf . unOccBs
statsOf = statsOf . unOccBs
instance Sizeable OccCSerialized where
dataOf = dataOf . unOccCBs
bytesOf = bytesOf . unOccCBs
statsOf = statsOf . unOccCBs
instance Sizeable Occ0 where
dataOf = dataOf . unOcc0
bytesOf = bytesOf . unOcc0
statsOf = statsOf . unOcc0
instance Sizeable OccCompressed where
dataOf = dataOf . unOccCp
bytesOf = bytesOf . unOccCp
statsOf = statsOf . unOccCp
instance Sizeable OccOSerialized where
dataOf = dataOf . unOccOBs
bytesOf = bytesOf . unOccOBs
statsOf = statsOf . unOccOBs
instance (Typeable occ, Sizeable occ) => Sizeable (Inverted occ) where
dataOf = dataOf . unInverted
bytesOf = bytesOf . unInverted
statsOf = statsOf . unInverted
#endif
-- ----------------------------------------------------------------------------
|
ichistmeinname/holumbus
|
src/Holumbus/Index/Inverted/CompressedPrefixMem.hs
|
mit
| 21,576 | 1 | 15 | 7,068 | 4,258 | 2,300 | 1,958 | 263 | 1 |
-- List Comprehensions
-- [(x,y) | x <- [1,2,3], y <- [4,5]]
-- [(x,y) | x <- [1..3], y <- [x..3]]
-- concat :: [[a]] <- [a]
fconcat xss = [x | xs <- xss, x <- xs]
-- factors :: Int -> [Int]
ffactors n = [x | x <- [1..n], n `mod` x == 0]
-- prime :: Int -> Bool
prime n = ffactors n == [1, n]
-- primes :: Int -> [Int]
primes n = [x | x <- [2..n], prime x]
-- pairs :: [a] -> [(a, a)]
pairs xs = zip xs (tail xs)
-- sortec :: Ord a => [a] -> Bool
sorted xs =
and [x <= y | (x,y) <- pairs xs]
-- positions :: Eq a => a -> [a] -> [Int]
positions x xs =
[i | (x', i) <- zip xs [0..n], x == x']
where n = length xs - 1
|
jugalps/edX
|
FP101x/week4/week4.hs
|
mit
| 633 | 0 | 9 | 173 | 241 | 130 | 111 | 10 | 1 |
module Import.Utils where
import Prelude
import Data.Text (Text, pack, unpack)
import Data.Time (UTCTime, addUTCTime, secondsToDiffTime)
import qualified Data.Map.Strict as MapS
import Data.IP (IP)
import System.Random (randomRIO)
import Control.Monad (unless, when)
-- | Takes a random element from list
pick :: [a] -> IO (Maybe a)
pick xs
| length xs == 0 = return Nothing
| otherwise = (Just . (xs!!)) <$> randomRIO (0, length xs - 1)
whenM :: Monad m => m Bool -> m () -> m ()
whenM = (. flip when) . (>>=)
unlessM :: Monad m => m Bool -> m () -> m ()
unlessM = (. flip unless) . (>>=)
tshow :: Show a => a -> Text
tshow = pack . show
tread :: Read a => Text -> a
tread = read . unpack
readIP :: String -> IP
readIP = read
pair :: forall t1 t2 t3. (t1 -> t2) -> (t1 -> t3) -> t1 -> (t2, t3)
pair f g x = (f x, g x)
keyValuesToMap :: (Ord k) => [(k, a)] -> MapS.Map k [a]
keyValuesToMap = MapS.fromListWith (++) . map (\(k,v) -> (k,[v]))
-- | Add UTCTime with Integer seconds
addUTCTime' :: Int -> UTCTime -> UTCTime
addUTCTime' sec t = addUTCTime (realToFrac $ secondsToDiffTime $ toInteger sec) t
|
ahushh/Monaba
|
monaba/src/Import/Utils.hs
|
mit
| 1,118 | 0 | 10 | 231 | 525 | 288 | 237 | -1 | -1 |
module PostgREST.ApiRequest where
import qualified Data.Aeson as JSON
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import qualified Data.Csv as CSV
import Data.List (find)
import qualified Data.HashMap.Strict as M
import qualified Data.Set as S
import Data.Maybe (fromMaybe, isJust, isNothing,
listToMaybe, fromJust)
import Control.Monad (join)
import Data.Monoid ((<>))
import Data.String.Conversions (cs)
import qualified Data.Text as T
import qualified Data.Vector as V
import Network.Wai (Request (..))
import Network.Wai.Parse (parseHttpAccept)
import PostgREST.RangeQuery (NonnegRange, rangeRequested)
import PostgREST.Types (QualifiedIdentifier (..),
Schema, Payload(..),
UniformObjects(..))
import Data.Ranged.Ranges (singletonRange)
type RequestBody = BL.ByteString
-- | Types of things a user wants to do to tables/views/procs
data Action = ActionCreate | ActionRead
| ActionUpdate | ActionDelete
| ActionInfo | ActionInvoke
| ActionUnknown BS.ByteString deriving Eq
-- | The target db object of a user action
data Target = TargetIdent QualifiedIdentifier
| TargetRoot
| TargetUnknown [T.Text]
-- | Enumeration of currently supported content types for
-- route responses and upload payloads
data ContentType = ApplicationJSON | TextCSV deriving Eq
instance Show ContentType where
show ApplicationJSON = "application/json"
show TextCSV = "text/csv"
{-|
Describes what the user wants to do. This data type is a
translation of the raw elements of an HTTP request into domain
specific language. There is no guarantee that the intent is
sensible, it is up to a later stage of processing to determine
if it is an action we are able to perform.
-}
data ApiRequest = ApiRequest {
-- | Set to Nothing for unknown HTTP verbs
iAction :: Action
-- | Set to Nothing for malformed range
, iRange :: NonnegRange
-- | Set to Nothing for strangely nested urls
, iTarget :: Target
-- | The content type the client most desires (or JSON if undecided)
, iAccepts :: Either BS.ByteString ContentType
-- | Data sent by client and used for mutation actions
, iPayload :: Maybe Payload
-- | If client wants created items echoed back
, iPreferRepresentation :: Bool
-- | If client wants first row as raw object
, iPreferSingular :: Bool
-- | Whether the client wants a result count (slower)
, iPreferCount :: Bool
-- | Filters on the result ("id", "eq.10")
, iFilters :: [(String, String)]
-- | &select parameter used to shape the response
, iSelect :: String
-- | &order parameter
, iOrder :: Maybe String
}
-- | Examines HTTP request and translates it into user intent.
userApiRequest :: Schema -> Request -> RequestBody -> ApiRequest
userApiRequest schema req reqBody =
let action = case method of
"GET" -> ActionRead
"POST" -> if isTargetingProc
then ActionInvoke
else ActionCreate
"PATCH" -> ActionUpdate
"DELETE" -> ActionDelete
"OPTIONS" -> ActionInfo
other -> ActionUnknown other
target = case path of
[] -> TargetRoot
[table] -> TargetIdent
$ QualifiedIdentifier schema table
["rpc", proc] -> TargetIdent
$ QualifiedIdentifier schema proc
other -> TargetUnknown other
payload = case pickContentType (lookupHeader "content-type") of
Right ApplicationJSON ->
either (PayloadParseError . cs)
(\val -> case ensureUniform (pluralize val) of
Nothing -> PayloadParseError "All object keys must match"
Just json -> PayloadJSON json)
(JSON.eitherDecode reqBody)
Right TextCSV ->
either (PayloadParseError . cs)
(\val -> case ensureUniform (csvToJson val) of
Nothing -> PayloadParseError "All lines must have same number of fields"
Just json -> PayloadJSON json)
(CSV.decodeByName reqBody)
Left accept ->
PayloadParseError $
"Content-type not acceptable: " <> accept
relevantPayload = case action of
ActionCreate -> Just payload
ActionUpdate -> Just payload
ActionInvoke -> Just payload
_ -> Nothing in
ApiRequest {
iAction = action
, iRange = if singular then singletonRange 0 else rangeRequested hdrs
, iTarget = target
, iAccepts = pickContentType $ lookupHeader "accept"
, iPayload = relevantPayload
, iPreferRepresentation = hasPrefer "return=representation"
, iPreferSingular = singular
, iPreferCount = not $ hasPrefer "count=none"
, iFilters = [ (k, fromJust v) | (k,v) <- qParams, k `notElem` ["select", "order"], isJust v ]
, iSelect = if method == "DELETE"
then "*"
else fromMaybe "*" $ fromMaybe (Just "*") $ lookup "select" qParams
, iOrder = join $ lookup "order" qParams
}
where
path = pathInfo req
method = requestMethod req
isTargetingProc = fromMaybe False $ (== "rpc") <$> listToMaybe path
hdrs = requestHeaders req
qParams = [(cs k, cs <$> v)|(k,v) <- queryString req]
lookupHeader = flip lookup hdrs
hasPrefer val = any (\(h,v) -> h == "Prefer" && v == val) hdrs
singular = hasPrefer "plurality=singular"
-- PRIVATE ---------------------------------------------------------------
{-|
Picks a preferred content type from an Accept header (or from
Content-Type as a degenerate case).
For example
text/csv -> TextCSV
*/* -> ApplicationJSON
text/csv, application/json -> TextCSV
application/json, text/csv -> ApplicationJSON
-}
pickContentType :: Maybe BS.ByteString -> Either BS.ByteString ContentType
pickContentType accept
| isNothing accept || has ctAll || has ctJson = Right ApplicationJSON
| has ctCsv = Right TextCSV
| otherwise = Left accept'
where
ctAll = "*/*"
ctCsv = "text/csv"
ctJson = "application/json"
Just accept' = accept
findInAccept = flip find $ parseHttpAccept accept'
has = isJust . findInAccept . BS.isPrefixOf
type CsvData = V.Vector (M.HashMap T.Text BL.ByteString)
{-|
Converts CSV like
a,b
1,hi
2,bye
into a JSON array like
[ {"a": "1", "b": "hi"}, {"a": 2, "b": "bye"} ]
The reason for its odd signature is so that it can compose
directly with CSV.decodeByName
-}
csvToJson :: (CSV.Header, CsvData) -> JSON.Array
csvToJson (_, vals) =
V.map rowToJsonObj vals
where
rowToJsonObj = JSON.Object .
M.map (\str ->
if str == "NULL"
then JSON.Null
else JSON.String $ cs str
)
-- | Convert {foo} to [{foo}], leave arrays unchanged
-- and truncate everything else to an empty array.
pluralize :: JSON.Value -> JSON.Array
pluralize obj@(JSON.Object _) = V.singleton obj
pluralize (JSON.Array arr) = arr
pluralize _ = V.empty
-- | Test that Array contains only Objects having the same keys
-- and if so mark it as UniformObjects
ensureUniform :: JSON.Array -> Maybe UniformObjects
ensureUniform arr =
let objs :: V.Vector JSON.Object
objs = foldr -- filter non-objects, map to raw objects
(\val result -> case val of
JSON.Object o -> V.cons o result
_ -> result)
V.empty arr
keysPerObj = V.map (S.fromList . M.keys) objs
canonicalKeys = fromMaybe S.empty $ keysPerObj V.!? 0
areKeysUniform = all (==canonicalKeys) keysPerObj in
if (V.length objs == V.length arr) && areKeysUniform
then Just (UniformObjects objs)
else Nothing
|
NikolayS/postgrest
|
src/PostgREST/ApiRequest.hs
|
mit
| 8,259 | 76 | 14 | 2,502 | 1,569 | 881 | 688 | 145 | 19 |
{-# LANGUAGE DeriveDataTypeable, TypeSynonymInstances, OverloadedStrings #-}
{-
Copyright (C) 2009 John MacFarlane <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- | Types for representing a structured formula.
-}
module Text.TeXMath.Types (Exp(..), TeXSymbolType(..), ArrayLine,
FractionType(..), TextType(..),
Alignment(..), DisplayType(..),
Operator(..), FormType(..), Record(..),
Property, Position(..), Env, defaultEnv,
InEDelimited)
where
import Data.Generics
import qualified Data.Text as T
data TeXSymbolType = Ord | Op | Bin | Rel | Open | Close | Pun | Accent
| Fence | TOver | TUnder | Alpha | BotAccent | Rad
deriving (Show, Read, Eq, Ord, Data, Typeable)
data Alignment = AlignLeft | AlignCenter | AlignRight
deriving (Show, Read, Eq, Ord, Data, Typeable)
data FractionType = NormalFrac -- ^ Displayed or textual, acc to 'DisplayType'
| DisplayFrac -- ^ Force display mode
| InlineFrac -- ^ Force inline mode (textual)
| NoLineFrac -- ^ No line between top and bottom
deriving (Show, Read, Eq, Ord, Data, Typeable)
type ArrayLine = [[Exp]]
data Exp =
ENumber T.Text -- ^ A number (@\<mn\>@ in MathML).
| EGrouped [Exp] -- ^ A group of expressions that function as a unit
-- (e.g. @{...}@) in TeX, @\<mrow\>...\</mrow\>@ in MathML.
| EDelimited T.Text T.Text [InEDelimited] -- ^ A group of expressions inside
-- paired open and close delimiters (which may in some
-- cases be null).
| EIdentifier T.Text -- ^ An identifier, e.g. a variable (@\<mi\>...\</mi\>@
-- in MathML. Note that MathML tends to use @\<mi\>@ tags
-- for "sin" and other mathematical operators; these
-- are represented as 'EMathOperator' in TeXMath.
| EMathOperator T.Text -- ^ A spelled-out operator like @lim@ or @sin@.
| ESymbol TeXSymbolType T.Text -- ^ A symbol.
| ESpace Rational -- ^ A space, with the width specified in em.
| ESub Exp Exp -- ^ An expression with a subscript. First argument is base,
-- second subscript.
| ESuper Exp Exp -- ^ An expresion with a superscript. First argument is base,
-- second subscript.
| ESubsup Exp Exp Exp -- ^ An expression with both a sub and a superscript.
-- First argument is base, second subscript, third
-- superscript.
| EOver Bool Exp Exp -- ^ An expression with something over it.
-- The first argument is True if the formula is
-- "convertible:" that is, if the material over the
-- formula should appear as a regular superscript in
-- inline math. The second argument is the base,
-- the third the expression that goes over it.
| EUnder Bool Exp Exp -- ^ An expression with something under it.
-- The arguments work as in @EOver@.
| EUnderover Bool Exp Exp Exp -- ^ An expression with something over and
-- something under it.
| EPhantom Exp -- ^ A "phantom" operator that takes space but doesn't display.
| EBoxed Exp -- ^ A boxed expression.
| EFraction FractionType Exp Exp -- ^ A fraction. First argument is
-- numerator, second denominator.
| ERoot Exp Exp -- ^ An nth root. First argument is index, second is base.
| ESqrt Exp -- ^ A square root.
| EScaled Rational Exp -- ^ An expression that is scaled to some factor
-- of its normal size.
| EArray [Alignment] [ArrayLine] -- ^ An array or matrix. The first argument
-- specifies the alignments of the columns; the second gives
-- the contents of the lines. All of these lists should be
-- the same length.
| EText TextType T.Text -- ^ Some normal text, possibly styled.
| EStyled TextType [Exp] -- ^ A group of styled expressions.
deriving (Show, Read, Eq, Ord, Data, Typeable)
-- | An @EDelimited@ element contains a string of ordinary expressions
-- (represented here as @Right@ values) or fences (represented here as
-- @Left@, and in LaTeX using @\mid@).
type InEDelimited = Either Middle Exp
type Middle = T.Text
data DisplayType = DisplayBlock -- ^ A displayed formula.
| DisplayInline -- ^ A formula rendered inline in text.
deriving (Show, Eq, Ord)
data TextType = TextNormal
| TextBold
| TextItalic
| TextMonospace
| TextSansSerif
| TextDoubleStruck
| TextScript
| TextFraktur
| TextBoldItalic
| TextSansSerifBold
| TextSansSerifBoldItalic
| TextBoldScript
| TextBoldFraktur
| TextSansSerifItalic
deriving (Show, Read, Eq, Ord, Data, Typeable)
data FormType = FPrefix | FPostfix | FInfix deriving (Show, Ord, Eq)
type Property = T.Text
-- | A record of the MathML dictionary as defined
-- <http://www.w3.org/TR/MathML3/appendixc.html in the specification>
data Operator = Operator
{ oper :: T.Text -- ^ Operator
, description :: T.Text -- ^ Plain English Description
, form :: FormType -- ^ Whether Prefix, Postfix or Infix
, priority :: Int -- ^ Default priority for implicit
-- nesting
, lspace :: Int -- ^ Default Left Spacing
, rspace :: Int -- ^ Default Right Spacing
, properties :: [Property] -- ^ List of MathML properties
}
deriving (Show)
-- | A record of the Unicode to LaTeX lookup table
-- a full descripton can be seen
-- <http://milde.users.sourceforge.net/LUCR/Math/data/unimathsymbols.txt
-- here>
data Record = Record { uchar :: Char -- ^ Unicode Character
, commands :: [(T.Text, T.Text)] -- ^ LaTeX commands (package, command)
, category :: TeXSymbolType -- ^ TeX math category
, comments :: T.Text -- ^ Plain english description
} deriving (Show)
data Position = Under | Over
-- | List of available packages
type Env = [T.Text]
-- | Contains @amsmath@ and @amssymbol@
defaultEnv :: [T.Text]
defaultEnv = ["amsmath", "amssymb"]
|
jgm/texmath
|
src/Text/TeXMath/Types.hs
|
gpl-2.0
| 7,350 | 0 | 11 | 2,345 | 878 | 560 | 318 | 84 | 1 |
#!/usr/bin/env runhaskell
{-# LANGUAGE ScopedTypeVariables #-}
import Control.Applicative
import Control.Monad
import Control.Monad.Trans.List
import Control.Monad.Trans.Maybe
import Control.Monad.IO.Class
import Data.List
import System.FilePath
import System.Directory
import System.Environment
import System.Process
max_depth = 3
getDirectoryContents' d = do
exists <- doesDirectoryExist d
if not exists
then return []
else
map (d</>) . filter (not . flip elem [".", ".."]) <$> getDirectoryContents d
main = do
b <- doesFileExist "ohs.cabal"
when (not b)
$ fail "./ohs.cabal doesn't exist, please run me in the project root."
root <- canonicalizePath "."
fs <- getDirectoryContents' =<< canonicalizePath "submodules"
mapM_ (addSubmodule 0) =<< filterM doesDirectoryExist fs
addSubmodule depth _ | depth > max_depth = return ()
addSubmodule depth s = do
-- putStrLn $ "checking " ++ s
fs <- getDirectoryContents' s
let b = or $ do
f <- fs
return $ takeExtension f == ".cabal"
case b of
True -> do
putStrLn $ "adding " ++ s
system $ "cabal sandbox add-source" ++ s
False -> do
-- putStrLn $ "no cabal file in: " ++ s
addSubmodule (depth+1) `mapM_` fs
|
DanielG/ohs
|
scripts/add-sources.hs
|
gpl-3.0
| 1,257 | 1 | 15 | 279 | 363 | 178 | 185 | 36 | 2 |
module Handler.MovieDetailsSpec (spec) where
import TestImport
spec :: Spec
spec = withApp $ do
describe "getMovieDetailsR" $ do
error "Spec not implemented: getMovieDetailsR"
|
Lionex/s16_mangohacks
|
JEGL/test/Handler/MovieDetailsSpec.hs
|
gpl-3.0
| 192 | 0 | 11 | 39 | 44 | 23 | 21 | 6 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Healthcare.Projects.Locations.DataSets.Hl7V2Stores.Create
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a new HL7v2 store within the parent dataset.
--
-- /See:/ <https://cloud.google.com/healthcare Cloud Healthcare API Reference> for @healthcare.projects.locations.datasets.hl7V2Stores.create@.
module Network.Google.Resource.Healthcare.Projects.Locations.DataSets.Hl7V2Stores.Create
(
-- * REST Resource
ProjectsLocationsDataSetsHl7V2StoresCreateResource
-- * Creating a Request
, projectsLocationsDataSetsHl7V2StoresCreate
, ProjectsLocationsDataSetsHl7V2StoresCreate
-- * Request Lenses
, pldshvscParent
, pldshvscXgafv
, pldshvscUploadProtocol
, pldshvscAccessToken
, pldshvscUploadType
, pldshvscPayload
, pldshvscHl7V2StoreId
, pldshvscCallback
) where
import Network.Google.Healthcare.Types
import Network.Google.Prelude
-- | A resource alias for @healthcare.projects.locations.datasets.hl7V2Stores.create@ method which the
-- 'ProjectsLocationsDataSetsHl7V2StoresCreate' request conforms to.
type ProjectsLocationsDataSetsHl7V2StoresCreateResource
=
"v1" :>
Capture "parent" Text :>
"hl7V2Stores" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "hl7V2StoreId" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Hl7V2Store :> Post '[JSON] Hl7V2Store
-- | Creates a new HL7v2 store within the parent dataset.
--
-- /See:/ 'projectsLocationsDataSetsHl7V2StoresCreate' smart constructor.
data ProjectsLocationsDataSetsHl7V2StoresCreate =
ProjectsLocationsDataSetsHl7V2StoresCreate'
{ _pldshvscParent :: !Text
, _pldshvscXgafv :: !(Maybe Xgafv)
, _pldshvscUploadProtocol :: !(Maybe Text)
, _pldshvscAccessToken :: !(Maybe Text)
, _pldshvscUploadType :: !(Maybe Text)
, _pldshvscPayload :: !Hl7V2Store
, _pldshvscHl7V2StoreId :: !(Maybe Text)
, _pldshvscCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsDataSetsHl7V2StoresCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pldshvscParent'
--
-- * 'pldshvscXgafv'
--
-- * 'pldshvscUploadProtocol'
--
-- * 'pldshvscAccessToken'
--
-- * 'pldshvscUploadType'
--
-- * 'pldshvscPayload'
--
-- * 'pldshvscHl7V2StoreId'
--
-- * 'pldshvscCallback'
projectsLocationsDataSetsHl7V2StoresCreate
:: Text -- ^ 'pldshvscParent'
-> Hl7V2Store -- ^ 'pldshvscPayload'
-> ProjectsLocationsDataSetsHl7V2StoresCreate
projectsLocationsDataSetsHl7V2StoresCreate pPldshvscParent_ pPldshvscPayload_ =
ProjectsLocationsDataSetsHl7V2StoresCreate'
{ _pldshvscParent = pPldshvscParent_
, _pldshvscXgafv = Nothing
, _pldshvscUploadProtocol = Nothing
, _pldshvscAccessToken = Nothing
, _pldshvscUploadType = Nothing
, _pldshvscPayload = pPldshvscPayload_
, _pldshvscHl7V2StoreId = Nothing
, _pldshvscCallback = Nothing
}
-- | The name of the dataset this HL7v2 store belongs to.
pldshvscParent :: Lens' ProjectsLocationsDataSetsHl7V2StoresCreate Text
pldshvscParent
= lens _pldshvscParent
(\ s a -> s{_pldshvscParent = a})
-- | V1 error format.
pldshvscXgafv :: Lens' ProjectsLocationsDataSetsHl7V2StoresCreate (Maybe Xgafv)
pldshvscXgafv
= lens _pldshvscXgafv
(\ s a -> s{_pldshvscXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pldshvscUploadProtocol :: Lens' ProjectsLocationsDataSetsHl7V2StoresCreate (Maybe Text)
pldshvscUploadProtocol
= lens _pldshvscUploadProtocol
(\ s a -> s{_pldshvscUploadProtocol = a})
-- | OAuth access token.
pldshvscAccessToken :: Lens' ProjectsLocationsDataSetsHl7V2StoresCreate (Maybe Text)
pldshvscAccessToken
= lens _pldshvscAccessToken
(\ s a -> s{_pldshvscAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pldshvscUploadType :: Lens' ProjectsLocationsDataSetsHl7V2StoresCreate (Maybe Text)
pldshvscUploadType
= lens _pldshvscUploadType
(\ s a -> s{_pldshvscUploadType = a})
-- | Multipart request metadata.
pldshvscPayload :: Lens' ProjectsLocationsDataSetsHl7V2StoresCreate Hl7V2Store
pldshvscPayload
= lens _pldshvscPayload
(\ s a -> s{_pldshvscPayload = a})
-- | The ID of the HL7v2 store that is being created. The string must match
-- the following regex: \`[\\p{L}\\p{N}_\\-\\.]{1,256}\`.
pldshvscHl7V2StoreId :: Lens' ProjectsLocationsDataSetsHl7V2StoresCreate (Maybe Text)
pldshvscHl7V2StoreId
= lens _pldshvscHl7V2StoreId
(\ s a -> s{_pldshvscHl7V2StoreId = a})
-- | JSONP
pldshvscCallback :: Lens' ProjectsLocationsDataSetsHl7V2StoresCreate (Maybe Text)
pldshvscCallback
= lens _pldshvscCallback
(\ s a -> s{_pldshvscCallback = a})
instance GoogleRequest
ProjectsLocationsDataSetsHl7V2StoresCreate
where
type Rs ProjectsLocationsDataSetsHl7V2StoresCreate =
Hl7V2Store
type Scopes
ProjectsLocationsDataSetsHl7V2StoresCreate
= '["https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsLocationsDataSetsHl7V2StoresCreate'{..}
= go _pldshvscParent _pldshvscXgafv
_pldshvscUploadProtocol
_pldshvscAccessToken
_pldshvscUploadType
_pldshvscHl7V2StoreId
_pldshvscCallback
(Just AltJSON)
_pldshvscPayload
healthcareService
where go
= buildClient
(Proxy ::
Proxy
ProjectsLocationsDataSetsHl7V2StoresCreateResource)
mempty
|
brendanhay/gogol
|
gogol-healthcare/gen/Network/Google/Resource/Healthcare/Projects/Locations/DataSets/Hl7V2Stores/Create.hs
|
mpl-2.0
| 6,706 | 0 | 18 | 1,434 | 862 | 502 | 360 | 136 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.BigtableAdmin.Projects.Instances.Clusters.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a cluster from an instance.
--
-- /See:/ <https://cloud.google.com/bigtable/ Cloud Bigtable Admin API Reference> for @bigtableadmin.projects.instances.clusters.delete@.
module Network.Google.Resource.BigtableAdmin.Projects.Instances.Clusters.Delete
(
-- * REST Resource
ProjectsInstancesClustersDeleteResource
-- * Creating a Request
, projectsInstancesClustersDelete
, ProjectsInstancesClustersDelete
-- * Request Lenses
, picdXgafv
, picdUploadProtocol
, picdAccessToken
, picdUploadType
, picdName
, picdCallback
) where
import Network.Google.BigtableAdmin.Types
import Network.Google.Prelude
-- | A resource alias for @bigtableadmin.projects.instances.clusters.delete@ method which the
-- 'ProjectsInstancesClustersDelete' request conforms to.
type ProjectsInstancesClustersDeleteResource =
"v2" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Empty
-- | Deletes a cluster from an instance.
--
-- /See:/ 'projectsInstancesClustersDelete' smart constructor.
data ProjectsInstancesClustersDelete =
ProjectsInstancesClustersDelete'
{ _picdXgafv :: !(Maybe Xgafv)
, _picdUploadProtocol :: !(Maybe Text)
, _picdAccessToken :: !(Maybe Text)
, _picdUploadType :: !(Maybe Text)
, _picdName :: !Text
, _picdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsInstancesClustersDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'picdXgafv'
--
-- * 'picdUploadProtocol'
--
-- * 'picdAccessToken'
--
-- * 'picdUploadType'
--
-- * 'picdName'
--
-- * 'picdCallback'
projectsInstancesClustersDelete
:: Text -- ^ 'picdName'
-> ProjectsInstancesClustersDelete
projectsInstancesClustersDelete pPicdName_ =
ProjectsInstancesClustersDelete'
{ _picdXgafv = Nothing
, _picdUploadProtocol = Nothing
, _picdAccessToken = Nothing
, _picdUploadType = Nothing
, _picdName = pPicdName_
, _picdCallback = Nothing
}
-- | V1 error format.
picdXgafv :: Lens' ProjectsInstancesClustersDelete (Maybe Xgafv)
picdXgafv
= lens _picdXgafv (\ s a -> s{_picdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
picdUploadProtocol :: Lens' ProjectsInstancesClustersDelete (Maybe Text)
picdUploadProtocol
= lens _picdUploadProtocol
(\ s a -> s{_picdUploadProtocol = a})
-- | OAuth access token.
picdAccessToken :: Lens' ProjectsInstancesClustersDelete (Maybe Text)
picdAccessToken
= lens _picdAccessToken
(\ s a -> s{_picdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
picdUploadType :: Lens' ProjectsInstancesClustersDelete (Maybe Text)
picdUploadType
= lens _picdUploadType
(\ s a -> s{_picdUploadType = a})
-- | Required. The unique name of the cluster to be deleted. Values are of
-- the form
-- \`projects\/{project}\/instances\/{instance}\/clusters\/{cluster}\`.
picdName :: Lens' ProjectsInstancesClustersDelete Text
picdName = lens _picdName (\ s a -> s{_picdName = a})
-- | JSONP
picdCallback :: Lens' ProjectsInstancesClustersDelete (Maybe Text)
picdCallback
= lens _picdCallback (\ s a -> s{_picdCallback = a})
instance GoogleRequest
ProjectsInstancesClustersDelete
where
type Rs ProjectsInstancesClustersDelete = Empty
type Scopes ProjectsInstancesClustersDelete =
'["https://www.googleapis.com/auth/bigtable.admin",
"https://www.googleapis.com/auth/bigtable.admin.cluster",
"https://www.googleapis.com/auth/bigtable.admin.instance",
"https://www.googleapis.com/auth/cloud-bigtable.admin",
"https://www.googleapis.com/auth/cloud-bigtable.admin.cluster",
"https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsInstancesClustersDelete'{..}
= go _picdName _picdXgafv _picdUploadProtocol
_picdAccessToken
_picdUploadType
_picdCallback
(Just AltJSON)
bigtableAdminService
where go
= buildClient
(Proxy ::
Proxy ProjectsInstancesClustersDeleteResource)
mempty
|
brendanhay/gogol
|
gogol-bigtableadmin/gen/Network/Google/Resource/BigtableAdmin/Projects/Instances/Clusters/Delete.hs
|
mpl-2.0
| 5,417 | 0 | 15 | 1,164 | 713 | 419 | 294 | 108 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.Glacier.AbortMultipartUpload
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | This operation aborts a multipart upload identified by the upload ID.
--
-- After the Abort Multipart Upload request succeeds, you cannot upload any
-- more parts to the multipart upload or complete the multipart upload. Aborting
-- a completed upload fails. However, aborting an already-aborted upload will
-- succeed, for a short time. For more information about uploading a part and
-- completing a multipart upload, see 'UploadMultipartPart' and 'CompleteMultipartUpload'.
--
-- This operation is idempotent.
--
-- An AWS account has full permission to perform all operations (actions).
-- However, AWS Identity and Access Management (IAM) users don't have any
-- permissions by default. You must grant them explicit permission to perform
-- specific actions. For more information, see <http://docs.aws.amazon.com/amazonglacier/latest/dev/using-iam-with-amazon-glacier.html Access Control Using AWS Identityand Access Management (IAM)>.
--
-- For conceptual information and underlying REST API, go to <http://docs.aws.amazon.com/amazonglacier/latest/dev/working-with-archives.html Working withArchives in Amazon Glacier> and <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-multipart-abort-upload.html Abort Multipart Upload> in the /Amazon GlacierDeveloper Guide/.
--
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-AbortMultipartUpload.html>
module Network.AWS.Glacier.AbortMultipartUpload
(
-- * Request
AbortMultipartUpload
-- ** Request constructor
, abortMultipartUpload
-- ** Request lenses
, amuAccountId
, amuUploadId
, amuVaultName
-- * Response
, AbortMultipartUploadResponse
-- ** Response constructor
, abortMultipartUploadResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.RestJSON
import Network.AWS.Glacier.Types
import qualified GHC.Exts
data AbortMultipartUpload = AbortMultipartUpload
{ _amuAccountId :: Text
, _amuUploadId :: Text
, _amuVaultName :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'AbortMultipartUpload' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'amuAccountId' @::@ 'Text'
--
-- * 'amuUploadId' @::@ 'Text'
--
-- * 'amuVaultName' @::@ 'Text'
--
abortMultipartUpload :: Text -- ^ 'amuAccountId'
-> Text -- ^ 'amuVaultName'
-> Text -- ^ 'amuUploadId'
-> AbortMultipartUpload
abortMultipartUpload p1 p2 p3 = AbortMultipartUpload
{ _amuAccountId = p1
, _amuVaultName = p2
, _amuUploadId = p3
}
-- | The 'AccountId' is the AWS Account ID. You can specify either the AWS Account
-- ID or optionally a '-', in which case Amazon Glacier uses the AWS Account ID
-- associated with the credentials used to sign the request. If you specify your
-- Account ID, do not include hyphens in it.
amuAccountId :: Lens' AbortMultipartUpload Text
amuAccountId = lens _amuAccountId (\s a -> s { _amuAccountId = a })
-- | The upload ID of the multipart upload to delete.
amuUploadId :: Lens' AbortMultipartUpload Text
amuUploadId = lens _amuUploadId (\s a -> s { _amuUploadId = a })
-- | The name of the vault.
amuVaultName :: Lens' AbortMultipartUpload Text
amuVaultName = lens _amuVaultName (\s a -> s { _amuVaultName = a })
data AbortMultipartUploadResponse = AbortMultipartUploadResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'AbortMultipartUploadResponse' constructor.
abortMultipartUploadResponse :: AbortMultipartUploadResponse
abortMultipartUploadResponse = AbortMultipartUploadResponse
instance ToPath AbortMultipartUpload where
toPath AbortMultipartUpload{..} = mconcat
[ "/"
, toText _amuAccountId
, "/vaults/"
, toText _amuVaultName
, "/multipart-uploads/"
, toText _amuUploadId
]
instance ToQuery AbortMultipartUpload where
toQuery = const mempty
instance ToHeaders AbortMultipartUpload
instance ToJSON AbortMultipartUpload where
toJSON = const (toJSON Empty)
instance AWSRequest AbortMultipartUpload where
type Sv AbortMultipartUpload = Glacier
type Rs AbortMultipartUpload = AbortMultipartUploadResponse
request = delete
response = nullResponse AbortMultipartUploadResponse
|
dysinger/amazonka
|
amazonka-glacier/gen/Network/AWS/Glacier/AbortMultipartUpload.hs
|
mpl-2.0
| 5,296 | 0 | 9 | 1,055 | 506 | 313 | 193 | 64 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.DataFusion.Types
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.DataFusion.Types
(
-- * Service Configuration
dataFusionService
-- * OAuth Scopes
, cloudPlatformScope
-- * InstanceLabels
, InstanceLabels
, instanceLabels
, ilAddtional
-- * Status
, Status
, status
, sDetails
, sCode
, sMessage
-- * OperationSchema
, OperationSchema
, operationSchema
, osAddtional
-- * AuditConfig
, AuditConfig
, auditConfig
, acService
, acAuditLogConfigs
-- * Expr
, Expr
, expr
, eLocation
, eExpression
, eTitle
, eDescription
-- * ListLocationsResponse
, ListLocationsResponse
, listLocationsResponse
, llrNextPageToken
, llrLocations
-- * ListOperationsResponse
, ListOperationsResponse
, listOperationsResponse
, lorNextPageToken
, lorOperations
-- * CancelOperationRequest
, CancelOperationRequest
, cancelOperationRequest
-- * Location
, Location
, location
, lName
, lMetadata
, lDisplayName
, lLabels
, lLocationId
-- * Operation
, Operation
, operation
, oDone
, oError
, oResponse
, oName
, oMetadata
-- * Empty
, Empty
, empty
-- * AcceleratorAcceleratorType
, AcceleratorAcceleratorType (..)
-- * AcceleratorState
, AcceleratorState (..)
-- * StatusDetailsItem
, StatusDetailsItem
, statusDetailsItem
, sdiAddtional
-- * CryptoKeyConfig
, CryptoKeyConfig
, cryptoKeyConfig
, ckcKeyReference
-- * SetIAMPolicyRequest
, SetIAMPolicyRequest
, setIAMPolicyRequest
, siprUpdateMask
, siprPolicy
-- * InstanceType
, InstanceType (..)
-- * NetworkConfig
, NetworkConfig
, networkConfig
, ncNetwork
, ncIPAllocation
-- * Accelerator
, Accelerator
, accelerator
, aAcceleratorType
, aState
-- * RestartInstanceRequest
, RestartInstanceRequest
, restartInstanceRequest
-- * AuditLogConfigLogType
, AuditLogConfigLogType (..)
-- * Version
, Version
, version
, vDefaultVersion
, vVersionNumber
, vAvailableFeatures
-- * Xgafv
, Xgafv (..)
-- * TestIAMPermissionsRequest
, TestIAMPermissionsRequest
, testIAMPermissionsRequest
, tiprPermissions
-- * OperationMetadataAdditionalStatus
, OperationMetadataAdditionalStatus
, operationMetadataAdditionalStatus
, omasAddtional
-- * TestIAMPermissionsResponse
, TestIAMPermissionsResponse
, testIAMPermissionsResponse
, tiamprPermissions
-- * Policy
, Policy
, policy
, pAuditConfigs
, pEtag
, pVersion
, pBindings
-- * LocationLabels
, LocationLabels
, locationLabels
, llAddtional
-- * LocationMetadata
, LocationMetadata
, locationMetadata
, lmAddtional
-- * OperationMetadata
, OperationMetadata
, operationMetadata
, omAPIVersion
, omAdditionalStatus
, omRequestedCancellation
, omEndTime
, omStatusDetail
, omVerb
, omTarget
, omCreateTime
-- * AuditLogConfig
, AuditLogConfig
, auditLogConfig
, alcLogType
, alcExemptedMembers
-- * ListInstancesResponse
, ListInstancesResponse
, listInstancesResponse
, lirNextPageToken
, lirUnreachable
, lirInstances
-- * InstanceState
, InstanceState (..)
-- * OperationResponse
, OperationResponse
, operationResponse
, orAddtional
-- * InstanceOptions
, InstanceOptions
, instanceOptions
, ioAddtional
-- * Binding
, Binding
, binding
, bMembers
, bRole
, bCondition
-- * Instance
, Instance
, instance'
, iStateMessage
, iTenantProjectId
, iState
, iEnableStackdriverLogging
, iP4ServiceAccount
, iEnableRbac
, iAPIEndpoint
, iCryptoKeyConfig
, iServiceEndpoint
, iZone
, iGcsBucket
, iServiceAccount
, iNetworkConfig
, iUpdateTime
, iAccelerators
, iPrivateInstance
, iName
, iVersion
, iDataprocServiceAccount
, iDisplayName
, iEnableStackdriverMonitoring
, iLabels
, iOptions
, iType
, iAvailableVersion
, iDescription
, iCreateTime
-- * ListAvailableVersionsResponse
, ListAvailableVersionsResponse
, listAvailableVersionsResponse
, lavrNextPageToken
, lavrAvailableVersions
) where
import Network.Google.DataFusion.Types.Product
import Network.Google.DataFusion.Types.Sum
import Network.Google.Prelude
-- | Default request referring to version 'v1' of the Cloud Data Fusion API. This contains the host and root path used as a starting point for constructing service requests.
dataFusionService :: ServiceConfig
dataFusionService
= defaultService (ServiceId "datafusion:v1")
"datafusion.googleapis.com"
-- | See, edit, configure, and delete your Google Cloud Platform data
cloudPlatformScope :: Proxy '["https://www.googleapis.com/auth/cloud-platform"]
cloudPlatformScope = Proxy
|
brendanhay/gogol
|
gogol-datafusion/gen/Network/Google/DataFusion/Types.hs
|
mpl-2.0
| 5,608 | 0 | 7 | 1,494 | 643 | 446 | 197 | 181 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.ProximityBeacon.Beacons.Decommission
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Decommissions the specified beacon in the service. This beacon will no
-- longer be returned from \`beaconinfo.getforobserved\`. This operation is
-- permanent -- you will not be able to re-register a beacon with this ID
-- again. Authenticate using an [OAuth access
-- token](https:\/\/developers.google.com\/identity\/protocols\/OAuth2)
-- from a signed-in user with **Is owner** or **Can edit** permissions in
-- the Google Developers Console project.
--
-- /See:/ <https://developers.google.com/beacons/proximity/ Proximity Beacon API Reference> for @proximitybeacon.beacons.decommission@.
module Network.Google.Resource.ProximityBeacon.Beacons.Decommission
(
-- * REST Resource
BeaconsDecommissionResource
-- * Creating a Request
, beaconsDecommission
, BeaconsDecommission
-- * Request Lenses
, bddXgafv
, bddUploadProtocol
, bddAccessToken
, bddBeaconName
, bddUploadType
, bddProjectId
, bddCallback
) where
import Network.Google.Prelude
import Network.Google.ProximityBeacon.Types
-- | A resource alias for @proximitybeacon.beacons.decommission@ method which the
-- 'BeaconsDecommission' request conforms to.
type BeaconsDecommissionResource =
"v1beta1" :>
CaptureMode "beaconName" "decommission" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "projectId" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Post '[JSON] Empty
-- | Decommissions the specified beacon in the service. This beacon will no
-- longer be returned from \`beaconinfo.getforobserved\`. This operation is
-- permanent -- you will not be able to re-register a beacon with this ID
-- again. Authenticate using an [OAuth access
-- token](https:\/\/developers.google.com\/identity\/protocols\/OAuth2)
-- from a signed-in user with **Is owner** or **Can edit** permissions in
-- the Google Developers Console project.
--
-- /See:/ 'beaconsDecommission' smart constructor.
data BeaconsDecommission =
BeaconsDecommission'
{ _bddXgafv :: !(Maybe Xgafv)
, _bddUploadProtocol :: !(Maybe Text)
, _bddAccessToken :: !(Maybe Text)
, _bddBeaconName :: !Text
, _bddUploadType :: !(Maybe Text)
, _bddProjectId :: !(Maybe Text)
, _bddCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'BeaconsDecommission' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bddXgafv'
--
-- * 'bddUploadProtocol'
--
-- * 'bddAccessToken'
--
-- * 'bddBeaconName'
--
-- * 'bddUploadType'
--
-- * 'bddProjectId'
--
-- * 'bddCallback'
beaconsDecommission
:: Text -- ^ 'bddBeaconName'
-> BeaconsDecommission
beaconsDecommission pBddBeaconName_ =
BeaconsDecommission'
{ _bddXgafv = Nothing
, _bddUploadProtocol = Nothing
, _bddAccessToken = Nothing
, _bddBeaconName = pBddBeaconName_
, _bddUploadType = Nothing
, _bddProjectId = Nothing
, _bddCallback = Nothing
}
-- | V1 error format.
bddXgafv :: Lens' BeaconsDecommission (Maybe Xgafv)
bddXgafv = lens _bddXgafv (\ s a -> s{_bddXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
bddUploadProtocol :: Lens' BeaconsDecommission (Maybe Text)
bddUploadProtocol
= lens _bddUploadProtocol
(\ s a -> s{_bddUploadProtocol = a})
-- | OAuth access token.
bddAccessToken :: Lens' BeaconsDecommission (Maybe Text)
bddAccessToken
= lens _bddAccessToken
(\ s a -> s{_bddAccessToken = a})
-- | Beacon that should be decommissioned. A beacon name has the format
-- \"beacons\/N!beaconId\" where the beaconId is the base16 ID broadcast by
-- the beacon and N is a code for the beacon\'s type. Possible values are
-- \`3\` for Eddystone-UID, \`4\` for Eddystone-EID, \`1\` for iBeacon, or
-- \`5\` for AltBeacon. For Eddystone-EID beacons, you may use either the
-- current EID of the beacon\'s \"stable\" UID. Required.
bddBeaconName :: Lens' BeaconsDecommission Text
bddBeaconName
= lens _bddBeaconName
(\ s a -> s{_bddBeaconName = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
bddUploadType :: Lens' BeaconsDecommission (Maybe Text)
bddUploadType
= lens _bddUploadType
(\ s a -> s{_bddUploadType = a})
-- | The project id of the beacon to decommission. If the project id is not
-- specified then the project making the request is used. The project id
-- must match the project that owns the beacon. Optional.
bddProjectId :: Lens' BeaconsDecommission (Maybe Text)
bddProjectId
= lens _bddProjectId (\ s a -> s{_bddProjectId = a})
-- | JSONP
bddCallback :: Lens' BeaconsDecommission (Maybe Text)
bddCallback
= lens _bddCallback (\ s a -> s{_bddCallback = a})
instance GoogleRequest BeaconsDecommission where
type Rs BeaconsDecommission = Empty
type Scopes BeaconsDecommission =
'["https://www.googleapis.com/auth/userlocation.beacon.registry"]
requestClient BeaconsDecommission'{..}
= go _bddBeaconName _bddXgafv _bddUploadProtocol
_bddAccessToken
_bddUploadType
_bddProjectId
_bddCallback
(Just AltJSON)
proximityBeaconService
where go
= buildClient
(Proxy :: Proxy BeaconsDecommissionResource)
mempty
|
brendanhay/gogol
|
gogol-proximitybeacon/gen/Network/Google/Resource/ProximityBeacon/Beacons/Decommission.hs
|
mpl-2.0
| 6,379 | 0 | 16 | 1,336 | 795 | 470 | 325 | 112 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.Lambda.Invoke
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Invokes a specified Lambda function.
--
-- This operation requires permission for the 'lambda:InvokeFunction'
-- action.
--
-- /See:/ <http://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html AWS API Reference> for Invoke.
module Network.AWS.Lambda.Invoke
(
-- * Creating a Request
invoke
, Invoke
-- * Request Lenses
, iInvocationType
, iPayload
, iLogType
, iClientContext
, iFunctionName
-- * Destructuring the Response
, invokeResponse
, InvokeResponse
-- * Response Lenses
, irsFunctionError
, irsLogResult
, irsPayload
, irsStatusCode
) where
import Network.AWS.Lambda.Types
import Network.AWS.Lambda.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'invoke' smart constructor.
data Invoke = Invoke'
{ _iInvocationType :: !(Maybe InvocationType)
, _iPayload :: !(Maybe Base64)
, _iLogType :: !(Maybe LogType)
, _iClientContext :: !(Maybe Text)
, _iFunctionName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Invoke' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'iInvocationType'
--
-- * 'iPayload'
--
-- * 'iLogType'
--
-- * 'iClientContext'
--
-- * 'iFunctionName'
invoke
:: Text -- ^ 'iFunctionName'
-> Invoke
invoke pFunctionName_ =
Invoke'
{ _iInvocationType = Nothing
, _iPayload = Nothing
, _iLogType = Nothing
, _iClientContext = Nothing
, _iFunctionName = pFunctionName_
}
-- | By default, the 'Invoke' API assumes \"RequestResponse\" invocation
-- type. You can optionally request asynchronous execution by specifying
-- \"Event\" as the 'InvocationType'. You can also use this parameter to
-- request AWS Lambda to not execute the function but do some verification,
-- such as if the caller is authorized to invoke the function and if the
-- inputs are valid. You request this by specifying \"DryRun\" as the
-- 'InvocationType'. This is useful in a cross-account scenario when you
-- want to verify access to a function without running it.
iInvocationType :: Lens' Invoke (Maybe InvocationType)
iInvocationType = lens _iInvocationType (\ s a -> s{_iInvocationType = a});
-- | JSON that you want to provide to your Lambda function as input.
--
-- /Note:/ This 'Lens' automatically encodes and decodes Base64 data,
-- despite what the AWS documentation might say.
-- The underlying isomorphism will encode to Base64 representation during
-- serialisation, and decode from Base64 representation during deserialisation.
-- This 'Lens' accepts and returns only raw unencoded data.
iPayload :: Lens' Invoke (Maybe ByteString)
iPayload = lens _iPayload (\ s a -> s{_iPayload = a}) . mapping _Base64;
-- | You can set this optional parameter to \"Tail\" in the request only if
-- you specify the 'InvocationType' parameter with value
-- \"RequestResponse\". In this case, AWS Lambda returns the base64-encoded
-- last 4 KB of log data produced by your Lambda function in the
-- 'x-amz-log-results' header.
iLogType :: Lens' Invoke (Maybe LogType)
iLogType = lens _iLogType (\ s a -> s{_iLogType = a});
-- | Using the 'ClientContext' you can pass client-specific information to
-- the Lambda function you are invoking. You can then process the client
-- information in your Lambda function as you choose through the context
-- variable. For an example of a ClientContext JSON, go to
-- <http://docs.aws.amazon.com/mobileanalytics/latest/ug/PutEvents.html PutEvents>
-- in the /Amazon Mobile Analytics API Reference and User Guide/.
--
-- The ClientContext JSON must be base64-encoded.
iClientContext :: Lens' Invoke (Maybe Text)
iClientContext = lens _iClientContext (\ s a -> s{_iClientContext = a});
-- | The Lambda function name.
--
-- You can specify an unqualified function name (for example,
-- \"Thumbnail\") or you can specify Amazon Resource Name (ARN) of the
-- function (for example,
-- \"arn:aws:lambda:us-west-2:account-id:function:ThumbNail\"). AWS Lambda
-- also allows you to specify only the account ID qualifier (for example,
-- \"account-id:Thumbnail\"). Note that the length constraint applies only
-- to the ARN. If you specify only the function name, it is limited to 64
-- character in length.
iFunctionName :: Lens' Invoke Text
iFunctionName = lens _iFunctionName (\ s a -> s{_iFunctionName = a});
instance AWSRequest Invoke where
type Rs Invoke = InvokeResponse
request = postJSON lambda
response
= receiveJSON
(\ s h x ->
InvokeResponse' <$>
(h .#? "X-Amz-Function-Error") <*>
(h .#? "X-Amz-Log-Result")
<*> (x .?> "Payload")
<*> (pure (fromEnum s)))
instance ToHeaders Invoke where
toHeaders Invoke'{..}
= mconcat
["X-Amz-Invocation-Type" =# _iInvocationType,
"X-Amz-Log-Type" =# _iLogType,
"X-Amz-Client-Context" =# _iClientContext]
instance ToJSON Invoke where
toJSON Invoke'{..}
= object (catMaybes [("Payload" .=) <$> _iPayload])
instance ToPath Invoke where
toPath Invoke'{..}
= mconcat
["/2015-03-31/functions/", toBS _iFunctionName,
"/invocations"]
instance ToQuery Invoke where
toQuery = const mempty
-- | Upon success, returns an empty response. Otherwise, throws an exception.
--
-- /See:/ 'invokeResponse' smart constructor.
data InvokeResponse = InvokeResponse'
{ _irsFunctionError :: !(Maybe Text)
, _irsLogResult :: !(Maybe Text)
, _irsPayload :: !(Maybe Base64)
, _irsStatusCode :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'InvokeResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'irsFunctionError'
--
-- * 'irsLogResult'
--
-- * 'irsPayload'
--
-- * 'irsStatusCode'
invokeResponse
:: Int -- ^ 'irsStatusCode'
-> InvokeResponse
invokeResponse pStatusCode_ =
InvokeResponse'
{ _irsFunctionError = Nothing
, _irsLogResult = Nothing
, _irsPayload = Nothing
, _irsStatusCode = pStatusCode_
}
-- | Indicates whether an error occurred while executing the Lambda function.
-- If an error occurred this field will have one of two values; 'Handled'
-- or 'Unhandled'. 'Handled' errors are errors that are reported by the
-- function while the 'Unhandled' errors are those detected and reported by
-- AWS Lambda. Unhandled errors include out of memory errors and function
-- timeouts. For information about how to report an 'Handled' error, see
-- <http://docs.aws.amazon.com/lambda/latest/dg/programming-model.html Programming Model>.
irsFunctionError :: Lens' InvokeResponse (Maybe Text)
irsFunctionError = lens _irsFunctionError (\ s a -> s{_irsFunctionError = a});
-- | It is the base64-encoded logs for the Lambda function invocation. This
-- is present only if the invocation type is \"RequestResponse\" and the
-- logs were requested.
irsLogResult :: Lens' InvokeResponse (Maybe Text)
irsLogResult = lens _irsLogResult (\ s a -> s{_irsLogResult = a});
-- | It is the JSON representation of the object returned by the Lambda
-- function. In This is present only if the invocation type is
-- \"RequestResponse\".
--
-- In the event of a function error this field contains a message
-- describing the error. For the 'Handled' errors the Lambda function will
-- report this message. For 'Unhandled' errors AWS Lambda reports the
-- message.
--
-- /Note:/ This 'Lens' automatically encodes and decodes Base64 data,
-- despite what the AWS documentation might say.
-- The underlying isomorphism will encode to Base64 representation during
-- serialisation, and decode from Base64 representation during deserialisation.
-- This 'Lens' accepts and returns only raw unencoded data.
irsPayload :: Lens' InvokeResponse (Maybe ByteString)
irsPayload = lens _irsPayload (\ s a -> s{_irsPayload = a}) . mapping _Base64;
-- | The HTTP status code will be in the 200 range for successful request.
-- For the \"RequestResonse\" invocation type this status code will be 200.
-- For the \"Event\" invocation type this status code will be 202. For the
-- \"DryRun\" invocation type the status code will be 204.
irsStatusCode :: Lens' InvokeResponse Int
irsStatusCode = lens _irsStatusCode (\ s a -> s{_irsStatusCode = a});
|
fmapfmapfmap/amazonka
|
amazonka-lambda/gen/Network/AWS/Lambda/Invoke.hs
|
mpl-2.0
| 9,303 | 0 | 14 | 1,881 | 1,116 | 678 | 438 | 123 | 1 |
module Freekick.Libsoccer.Region
where
import Freekick.Libsoccer.Stadium
data Region =
Region { name :: String,
stadiums :: [Stadium],
-- hostregion :: Entity,
-- country :: Entity,
-- clubs :: [Entity],
subregions :: [Region]
}
deriving (Show, Eq)
allRegions :: Region -> [Region]
allRegions r = ss ++ concatMap allRegions ss
where ss = subregions r
|
anttisalonen/freekick
|
haskell/libfreekick/Freekick/Libsoccer/Region.hs
|
agpl-3.0
| 469 | 0 | 9 | 171 | 99 | 59 | 40 | 10 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QHeaderView_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:20
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QHeaderView_h where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Enums.Gui.QItemSelectionModel
import Qtc.Enums.Gui.QAbstractItemView
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QAbstractItemDelegate
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QHeaderView ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHeaderView_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QHeaderView_unSetUserMethod" qtc_QHeaderView_unSetUserMethod :: Ptr (TQHeaderView a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QHeaderViewSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHeaderView_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QHeaderView ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHeaderView_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QHeaderViewSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHeaderView_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QHeaderView ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHeaderView_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QHeaderViewSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHeaderView_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QHeaderView ()) (QHeaderView x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QHeaderView setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QHeaderView_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QHeaderView_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHeaderView_setUserMethod" qtc_QHeaderView_setUserMethod :: Ptr (TQHeaderView a) -> CInt -> Ptr (Ptr (TQHeaderView x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QHeaderView :: (Ptr (TQHeaderView x0) -> IO ()) -> IO (FunPtr (Ptr (TQHeaderView x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QHeaderView_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QHeaderViewSc a) (QHeaderView x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QHeaderView setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QHeaderView_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QHeaderView_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QHeaderView ()) (QHeaderView x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QHeaderView setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QHeaderView_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QHeaderView_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHeaderView_setUserMethodVariant" qtc_QHeaderView_setUserMethodVariant :: Ptr (TQHeaderView a) -> CInt -> Ptr (Ptr (TQHeaderView x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QHeaderView :: (Ptr (TQHeaderView x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQHeaderView x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QHeaderView_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QHeaderViewSc a) (QHeaderView x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QHeaderView setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QHeaderView_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QHeaderView_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QHeaderView ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QHeaderView_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QHeaderView_unSetHandler" qtc_QHeaderView_unSetHandler :: Ptr (TQHeaderView a) -> CWString -> IO (CBool)
instance QunSetHandler (QHeaderViewSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QHeaderView_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QHeaderView ()) (QHeaderView x0 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> IO ()
setHandlerWrapper x0
= do x0obj <- qHeaderViewFromPtr x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHeaderView_setHandler1" qtc_QHeaderView_setHandler1 :: Ptr (TQHeaderView a) -> CWString -> Ptr (Ptr (TQHeaderView x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHeaderView1 :: (Ptr (TQHeaderView x0) -> IO ()) -> IO (FunPtr (Ptr (TQHeaderView x0) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QHeaderView1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHeaderViewSc a) (QHeaderView x0 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> IO ()
setHandlerWrapper x0
= do x0obj <- qHeaderViewFromPtr x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdoItemsLayout_h (QHeaderView ()) (()) where
doItemsLayout_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_doItemsLayout cobj_x0
foreign import ccall "qtc_QHeaderView_doItemsLayout" qtc_QHeaderView_doItemsLayout :: Ptr (TQHeaderView a) -> IO ()
instance QdoItemsLayout_h (QHeaderViewSc a) (()) where
doItemsLayout_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_doItemsLayout cobj_x0
instance QsetHandler (QHeaderView ()) (QHeaderView x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qHeaderViewFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHeaderView_setHandler2" qtc_QHeaderView_setHandler2 :: Ptr (TQHeaderView a) -> CWString -> Ptr (Ptr (TQHeaderView x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHeaderView2 :: (Ptr (TQHeaderView x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQHeaderView x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QHeaderView2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHeaderViewSc a) (QHeaderView x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qHeaderViewFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QHeaderView ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_event cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_event" qtc_QHeaderView_event :: Ptr (TQHeaderView a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QHeaderViewSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_event cobj_x0 cobj_x1
instance QsetHandler (QHeaderView ()) (QHeaderView x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qHeaderViewFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHeaderView_setHandler3" qtc_QHeaderView_setHandler3 :: Ptr (TQHeaderView a) -> CWString -> Ptr (Ptr (TQHeaderView x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHeaderView3 :: (Ptr (TQHeaderView x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQHeaderView x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QHeaderView3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHeaderViewSc a) (QHeaderView x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qHeaderViewFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QmouseDoubleClickEvent_h (QHeaderView ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_mouseDoubleClickEvent" qtc_QHeaderView_mouseDoubleClickEvent :: Ptr (TQHeaderView a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QHeaderViewSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QHeaderView ()) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_mouseMoveEvent" qtc_QHeaderView_mouseMoveEvent :: Ptr (TQHeaderView a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QHeaderViewSc a) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QHeaderView ()) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_mousePressEvent" qtc_QHeaderView_mousePressEvent :: Ptr (TQHeaderView a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QHeaderViewSc a) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QHeaderView ()) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_mouseReleaseEvent" qtc_QHeaderView_mouseReleaseEvent :: Ptr (TQHeaderView a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QHeaderViewSc a) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_mouseReleaseEvent cobj_x0 cobj_x1
instance QpaintEvent_h (QHeaderView ()) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_paintEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_paintEvent" qtc_QHeaderView_paintEvent :: Ptr (TQHeaderView a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent_h (QHeaderViewSc a) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_paintEvent cobj_x0 cobj_x1
instance Qreset_h (QHeaderView ()) (()) (IO ()) where
reset_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_reset cobj_x0
foreign import ccall "qtc_QHeaderView_reset" qtc_QHeaderView_reset :: Ptr (TQHeaderView a) -> IO ()
instance Qreset_h (QHeaderViewSc a) (()) (IO ()) where
reset_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_reset cobj_x0
instance QsetHandler (QHeaderView ()) (QHeaderView x0 -> Int -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> CInt -> CInt -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qHeaderViewFromPtr x0
let x1int = fromCInt x1
let x2int = fromCInt x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int x2int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHeaderView_setHandler4" qtc_QHeaderView_setHandler4 :: Ptr (TQHeaderView a) -> CWString -> Ptr (Ptr (TQHeaderView x0) -> CInt -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHeaderView4 :: (Ptr (TQHeaderView x0) -> CInt -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQHeaderView x0) -> CInt -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QHeaderView4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHeaderViewSc a) (QHeaderView x0 -> Int -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> CInt -> CInt -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qHeaderViewFromPtr x0
let x1int = fromCInt x1
let x2int = fromCInt x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int x2int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QscrollContentsBy_h (QHeaderView ()) ((Int, Int)) where
scrollContentsBy_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_scrollContentsBy cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QHeaderView_scrollContentsBy" qtc_QHeaderView_scrollContentsBy :: Ptr (TQHeaderView a) -> CInt -> CInt -> IO ()
instance QscrollContentsBy_h (QHeaderViewSc a) ((Int, Int)) where
scrollContentsBy_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_scrollContentsBy cobj_x0 (toCInt x1) (toCInt x2)
instance QsetHandler (QHeaderView ()) (QHeaderView x0 -> QObject t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> Ptr (TQObject t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qHeaderViewFromPtr x0
x1obj <- qObjectFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHeaderView_setHandler5" qtc_QHeaderView_setHandler5 :: Ptr (TQHeaderView a) -> CWString -> Ptr (Ptr (TQHeaderView x0) -> Ptr (TQObject t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHeaderView5 :: (Ptr (TQHeaderView x0) -> Ptr (TQObject t1) -> IO ()) -> IO (FunPtr (Ptr (TQHeaderView x0) -> Ptr (TQObject t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QHeaderView5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHeaderViewSc a) (QHeaderView x0 -> QObject t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> Ptr (TQObject t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qHeaderViewFromPtr x0
x1obj <- qObjectFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetModel_h (QHeaderView ()) ((QAbstractItemModel t1)) where
setModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setModel cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_setModel" qtc_QHeaderView_setModel :: Ptr (TQHeaderView a) -> Ptr (TQAbstractItemModel t1) -> IO ()
instance QsetModel_h (QHeaderViewSc a) ((QAbstractItemModel t1)) where
setModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setModel cobj_x0 cobj_x1
instance QsetHandler (QHeaderView ()) (QHeaderView x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qHeaderViewFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHeaderView_setHandler6" qtc_QHeaderView_setHandler6 :: Ptr (TQHeaderView a) -> CWString -> Ptr (Ptr (TQHeaderView x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHeaderView6 :: (Ptr (TQHeaderView x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQHeaderView x0) -> IO (Ptr (TQSize t0))))
foreign import ccall "wrapper" wrapSetHandler_QHeaderView6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHeaderViewSc a) (QHeaderView x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qHeaderViewFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqsizeHint_h (QHeaderView ()) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sizeHint cobj_x0
foreign import ccall "qtc_QHeaderView_sizeHint" qtc_QHeaderView_sizeHint :: Ptr (TQHeaderView a) -> IO (Ptr (TQSize ()))
instance QqsizeHint_h (QHeaderViewSc a) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sizeHint cobj_x0
instance QsizeHint_h (QHeaderView ()) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QHeaderView_sizeHint_qth" qtc_QHeaderView_sizeHint_qth :: Ptr (TQHeaderView a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint_h (QHeaderViewSc a) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QviewportEvent_h (QHeaderView ()) ((QEvent t1)) where
viewportEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_viewportEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_viewportEvent" qtc_QHeaderView_viewportEvent :: Ptr (TQHeaderView a) -> Ptr (TQEvent t1) -> IO CBool
instance QviewportEvent_h (QHeaderViewSc a) ((QEvent t1)) where
viewportEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_viewportEvent cobj_x0 cobj_x1
instance QdragEnterEvent_h (QHeaderView ()) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_dragEnterEvent" qtc_QHeaderView_dragEnterEvent :: Ptr (TQHeaderView a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent_h (QHeaderViewSc a) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QHeaderView ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_dragLeaveEvent" qtc_QHeaderView_dragLeaveEvent :: Ptr (TQHeaderView a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent_h (QHeaderViewSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QHeaderView ()) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_dragMoveEvent" qtc_QHeaderView_dragMoveEvent :: Ptr (TQHeaderView a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent_h (QHeaderViewSc a) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QHeaderView ()) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_dropEvent" qtc_QHeaderView_dropEvent :: Ptr (TQHeaderView a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent_h (QHeaderViewSc a) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_dropEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QHeaderView ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_focusInEvent" qtc_QHeaderView_focusInEvent :: Ptr (TQHeaderView a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QHeaderViewSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QHeaderView ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_focusOutEvent" qtc_QHeaderView_focusOutEvent :: Ptr (TQHeaderView a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QHeaderViewSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_focusOutEvent cobj_x0 cobj_x1
instance QsetHandler (QHeaderView ()) (QHeaderView x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qHeaderViewFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHeaderView_setHandler7" qtc_QHeaderView_setHandler7 :: Ptr (TQHeaderView a) -> CWString -> Ptr (Ptr (TQHeaderView x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHeaderView7 :: (Ptr (TQHeaderView x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQHeaderView x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QHeaderView7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHeaderViewSc a) (QHeaderView x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qHeaderViewFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QinputMethodQuery_h (QHeaderView ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QHeaderView_inputMethodQuery" qtc_QHeaderView_inputMethodQuery :: Ptr (TQHeaderView a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QHeaderViewSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyPressEvent_h (QHeaderView ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_keyPressEvent" qtc_QHeaderView_keyPressEvent :: Ptr (TQHeaderView a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QHeaderViewSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_keyPressEvent cobj_x0 cobj_x1
instance QsetHandler (QHeaderView ()) (QHeaderView x0 -> String -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> Ptr (TQString ()) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qHeaderViewFromPtr x0
x1str <- stringFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1str
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHeaderView_setHandler8" qtc_QHeaderView_setHandler8 :: Ptr (TQHeaderView a) -> CWString -> Ptr (Ptr (TQHeaderView x0) -> Ptr (TQString ()) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHeaderView8 :: (Ptr (TQHeaderView x0) -> Ptr (TQString ()) -> IO ()) -> IO (FunPtr (Ptr (TQHeaderView x0) -> Ptr (TQString ()) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QHeaderView8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHeaderViewSc a) (QHeaderView x0 -> String -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> Ptr (TQString ()) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qHeaderViewFromPtr x0
x1str <- stringFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1str
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QkeyboardSearch_h (QHeaderView ()) ((String)) where
keyboardSearch_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QHeaderView_keyboardSearch cobj_x0 cstr_x1
foreign import ccall "qtc_QHeaderView_keyboardSearch" qtc_QHeaderView_keyboardSearch :: Ptr (TQHeaderView a) -> CWString -> IO ()
instance QkeyboardSearch_h (QHeaderViewSc a) ((String)) where
keyboardSearch_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QHeaderView_keyboardSearch cobj_x0 cstr_x1
instance QresizeEvent_h (QHeaderView ()) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_resizeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_resizeEvent" qtc_QHeaderView_resizeEvent :: Ptr (TQHeaderView a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent_h (QHeaderViewSc a) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_resizeEvent cobj_x0 cobj_x1
instance QselectAll_h (QHeaderView ()) (()) where
selectAll_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_selectAll cobj_x0
foreign import ccall "qtc_QHeaderView_selectAll" qtc_QHeaderView_selectAll :: Ptr (TQHeaderView a) -> IO ()
instance QselectAll_h (QHeaderViewSc a) (()) where
selectAll_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_selectAll cobj_x0
instance QsetHandler (QHeaderView ()) (QHeaderView x0 -> QModelIndex t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> Ptr (TQModelIndex t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qHeaderViewFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHeaderView_setHandler9" qtc_QHeaderView_setHandler9 :: Ptr (TQHeaderView a) -> CWString -> Ptr (Ptr (TQHeaderView x0) -> Ptr (TQModelIndex t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHeaderView9 :: (Ptr (TQHeaderView x0) -> Ptr (TQModelIndex t1) -> IO ()) -> IO (FunPtr (Ptr (TQHeaderView x0) -> Ptr (TQModelIndex t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QHeaderView9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHeaderViewSc a) (QHeaderView x0 -> QModelIndex t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> Ptr (TQModelIndex t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qHeaderViewFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetRootIndex_h (QHeaderView ()) ((QModelIndex t1)) where
setRootIndex_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setRootIndex cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_setRootIndex" qtc_QHeaderView_setRootIndex :: Ptr (TQHeaderView a) -> Ptr (TQModelIndex t1) -> IO ()
instance QsetRootIndex_h (QHeaderViewSc a) ((QModelIndex t1)) where
setRootIndex_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setRootIndex cobj_x0 cobj_x1
instance QsetSelectionModel_h (QHeaderView ()) ((QItemSelectionModel t1)) where
setSelectionModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setSelectionModel cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_setSelectionModel" qtc_QHeaderView_setSelectionModel :: Ptr (TQHeaderView a) -> Ptr (TQItemSelectionModel t1) -> IO ()
instance QsetSelectionModel_h (QHeaderViewSc a) ((QItemSelectionModel t1)) where
setSelectionModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setSelectionModel cobj_x0 cobj_x1
instance QsetHandler (QHeaderView ()) (QHeaderView x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qHeaderViewFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHeaderView_setHandler10" qtc_QHeaderView_setHandler10 :: Ptr (TQHeaderView a) -> CWString -> Ptr (Ptr (TQHeaderView x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHeaderView10 :: (Ptr (TQHeaderView x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQHeaderView x0) -> CInt -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QHeaderView10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHeaderViewSc a) (QHeaderView x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qHeaderViewFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsizeHintForColumn_h (QHeaderView ()) ((Int)) where
sizeHintForColumn_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sizeHintForColumn cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_sizeHintForColumn" qtc_QHeaderView_sizeHintForColumn :: Ptr (TQHeaderView a) -> CInt -> IO CInt
instance QsizeHintForColumn_h (QHeaderViewSc a) ((Int)) where
sizeHintForColumn_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sizeHintForColumn cobj_x0 (toCInt x1)
instance QsizeHintForRow_h (QHeaderView ()) ((Int)) where
sizeHintForRow_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sizeHintForRow cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_sizeHintForRow" qtc_QHeaderView_sizeHintForRow :: Ptr (TQHeaderView a) -> CInt -> IO CInt
instance QsizeHintForRow_h (QHeaderViewSc a) ((Int)) where
sizeHintForRow_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sizeHintForRow cobj_x0 (toCInt x1)
instance QcontextMenuEvent_h (QHeaderView ()) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_contextMenuEvent" qtc_QHeaderView_contextMenuEvent :: Ptr (TQHeaderView a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QHeaderViewSc a) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_contextMenuEvent cobj_x0 cobj_x1
instance QqminimumSizeHint_h (QHeaderView ()) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_minimumSizeHint cobj_x0
foreign import ccall "qtc_QHeaderView_minimumSizeHint" qtc_QHeaderView_minimumSizeHint :: Ptr (TQHeaderView a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint_h (QHeaderViewSc a) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_minimumSizeHint cobj_x0
instance QminimumSizeHint_h (QHeaderView ()) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QHeaderView_minimumSizeHint_qth" qtc_QHeaderView_minimumSizeHint_qth :: Ptr (TQHeaderView a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint_h (QHeaderViewSc a) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QwheelEvent_h (QHeaderView ()) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_wheelEvent" qtc_QHeaderView_wheelEvent :: Ptr (TQHeaderView a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent_h (QHeaderViewSc a) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_wheelEvent cobj_x0 cobj_x1
instance QchangeEvent_h (QHeaderView ()) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_changeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_changeEvent" qtc_QHeaderView_changeEvent :: Ptr (TQHeaderView a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent_h (QHeaderViewSc a) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_changeEvent cobj_x0 cobj_x1
instance QactionEvent_h (QHeaderView ()) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_actionEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_actionEvent" qtc_QHeaderView_actionEvent :: Ptr (TQHeaderView a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent_h (QHeaderViewSc a) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_actionEvent cobj_x0 cobj_x1
instance QcloseEvent_h (QHeaderView ()) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_closeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_closeEvent" qtc_QHeaderView_closeEvent :: Ptr (TQHeaderView a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent_h (QHeaderViewSc a) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_closeEvent cobj_x0 cobj_x1
instance QsetHandler (QHeaderView ()) (QHeaderView x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qHeaderViewFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHeaderView_setHandler11" qtc_QHeaderView_setHandler11 :: Ptr (TQHeaderView a) -> CWString -> Ptr (Ptr (TQHeaderView x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHeaderView11 :: (Ptr (TQHeaderView x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQHeaderView x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QHeaderView11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHeaderViewSc a) (QHeaderView x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qHeaderViewFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdevType_h (QHeaderView ()) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_devType cobj_x0
foreign import ccall "qtc_QHeaderView_devType" qtc_QHeaderView_devType :: Ptr (TQHeaderView a) -> IO CInt
instance QdevType_h (QHeaderViewSc a) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_devType cobj_x0
instance QenterEvent_h (QHeaderView ()) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_enterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_enterEvent" qtc_QHeaderView_enterEvent :: Ptr (TQHeaderView a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent_h (QHeaderViewSc a) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_enterEvent cobj_x0 cobj_x1
instance QheightForWidth_h (QHeaderView ()) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_heightForWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_heightForWidth" qtc_QHeaderView_heightForWidth :: Ptr (TQHeaderView a) -> CInt -> IO CInt
instance QheightForWidth_h (QHeaderViewSc a) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_heightForWidth cobj_x0 (toCInt x1)
instance QhideEvent_h (QHeaderView ()) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_hideEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_hideEvent" qtc_QHeaderView_hideEvent :: Ptr (TQHeaderView a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent_h (QHeaderViewSc a) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_hideEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QHeaderView ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_keyReleaseEvent" qtc_QHeaderView_keyReleaseEvent :: Ptr (TQHeaderView a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QHeaderViewSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_keyReleaseEvent cobj_x0 cobj_x1
instance QleaveEvent_h (QHeaderView ()) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_leaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_leaveEvent" qtc_QHeaderView_leaveEvent :: Ptr (TQHeaderView a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent_h (QHeaderViewSc a) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_leaveEvent cobj_x0 cobj_x1
instance QmoveEvent_h (QHeaderView ()) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_moveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_moveEvent" qtc_QHeaderView_moveEvent :: Ptr (TQHeaderView a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent_h (QHeaderViewSc a) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_moveEvent cobj_x0 cobj_x1
instance QsetHandler (QHeaderView ()) (QHeaderView x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qHeaderViewFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHeaderView_setHandler12" qtc_QHeaderView_setHandler12 :: Ptr (TQHeaderView a) -> CWString -> Ptr (Ptr (TQHeaderView x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHeaderView12 :: (Ptr (TQHeaderView x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQHeaderView x0) -> IO (Ptr (TQPaintEngine t0))))
foreign import ccall "wrapper" wrapSetHandler_QHeaderView12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHeaderViewSc a) (QHeaderView x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qHeaderViewFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QpaintEngine_h (QHeaderView ()) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_paintEngine cobj_x0
foreign import ccall "qtc_QHeaderView_paintEngine" qtc_QHeaderView_paintEngine :: Ptr (TQHeaderView a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine_h (QHeaderViewSc a) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_paintEngine cobj_x0
instance QsetHandler (QHeaderView ()) (QHeaderView x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qHeaderViewFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHeaderView_setHandler13" qtc_QHeaderView_setHandler13 :: Ptr (TQHeaderView a) -> CWString -> Ptr (Ptr (TQHeaderView x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHeaderView13 :: (Ptr (TQHeaderView x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQHeaderView x0) -> CBool -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QHeaderView13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHeaderViewSc a) (QHeaderView x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qHeaderViewFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetVisible_h (QHeaderView ()) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QHeaderView_setVisible" qtc_QHeaderView_setVisible :: Ptr (TQHeaderView a) -> CBool -> IO ()
instance QsetVisible_h (QHeaderViewSc a) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setVisible cobj_x0 (toCBool x1)
instance QshowEvent_h (QHeaderView ()) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_showEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_showEvent" qtc_QHeaderView_showEvent :: Ptr (TQHeaderView a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent_h (QHeaderViewSc a) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_showEvent cobj_x0 cobj_x1
instance QtabletEvent_h (QHeaderView ()) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_tabletEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_tabletEvent" qtc_QHeaderView_tabletEvent :: Ptr (TQHeaderView a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent_h (QHeaderViewSc a) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_tabletEvent cobj_x0 cobj_x1
instance QsetHandler (QHeaderView ()) (QHeaderView x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qHeaderViewFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHeaderView_setHandler14" qtc_QHeaderView_setHandler14 :: Ptr (TQHeaderView a) -> CWString -> Ptr (Ptr (TQHeaderView x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHeaderView14 :: (Ptr (TQHeaderView x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQHeaderView x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QHeaderView14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHeaderViewSc a) (QHeaderView x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHeaderView14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHeaderView14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHeaderView_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHeaderView x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qHeaderViewFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QeventFilter_h (QHeaderView ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHeaderView_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QHeaderView_eventFilter" qtc_QHeaderView_eventFilter :: Ptr (TQHeaderView a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QHeaderViewSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHeaderView_eventFilter cobj_x0 cobj_x1 cobj_x2
|
keera-studios/hsQt
|
Qtc/Gui/QHeaderView_h.hs
|
bsd-2-clause
| 78,368 | 0 | 18 | 16,767 | 25,826 | 12,432 | 13,394 | -1 | -1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QLine.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.Core.QLine (
QqqLine(..), QqLine(..)
,QqqLine_nf(..), QqLine_nf(..)
,qLine_delete
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
class QqqLine x1 where
qqLine :: x1 -> IO (QLine ())
class QqLine x1 where
qLine :: x1 -> IO (QLine ())
instance QqLine (()) where
qLine ()
= withQLineResult $
qtc_QLine
foreign import ccall "qtc_QLine" qtc_QLine :: IO (Ptr (TQLine ()))
instance QqqLine ((QLine t1)) where
qqLine (x1)
= withQLineResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLine1 cobj_x1
foreign import ccall "qtc_QLine1" qtc_QLine1 :: Ptr (TQLine t1) -> IO (Ptr (TQLine ()))
instance QqLine ((Line)) where
qLine (x1)
= withQLineResult $
withCLine x1 $ \cline_x1_x1 cline_x1_y1 cline_x1_x2 cline_x1_y2 ->
qtc_QLine2 cline_x1_x1 cline_x1_y1 cline_x1_x2 cline_x1_y2
foreign import ccall "qtc_QLine2" qtc_QLine2 :: CInt -> CInt -> CInt -> CInt -> IO (Ptr (TQLine ()))
instance QqqLine ((QPoint t1, QPoint t2)) where
qqLine (x1, x2)
= withQLineResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QLine3 cobj_x1 cobj_x2
foreign import ccall "qtc_QLine3" qtc_QLine3 :: Ptr (TQPoint t1) -> Ptr (TQPoint t2) -> IO (Ptr (TQLine ()))
instance QqLine ((Point, Point)) where
qLine (x1, x2)
= withQLineResult $
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
withCPoint x2 $ \cpoint_x2_x cpoint_x2_y ->
qtc_QLine4 cpoint_x1_x cpoint_x1_y cpoint_x2_x cpoint_x2_y
foreign import ccall "qtc_QLine4" qtc_QLine4 :: CInt -> CInt -> CInt -> CInt -> IO (Ptr (TQLine ()))
instance QqLine ((Int, Int, Int, Int)) where
qLine (x1, x2, x3, x4)
= withQLineResult $
qtc_QLine5 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QLine5" qtc_QLine5 :: CInt -> CInt -> CInt -> CInt -> IO (Ptr (TQLine ()))
class QqqLine_nf x1 where
qqLine_nf :: x1 -> IO (QLine ())
class QqLine_nf x1 where
qLine_nf :: x1 -> IO (QLine ())
instance QqLine_nf (()) where
qLine_nf ()
= withObjectRefResult $
qtc_QLine
instance QqqLine_nf ((QLine t1)) where
qqLine_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLine1 cobj_x1
instance QqLine_nf ((Line)) where
qLine_nf (x1)
= withObjectRefResult $
withCLine x1 $ \cline_x1_x1 cline_x1_y1 cline_x1_x2 cline_x1_y2 ->
qtc_QLine2 cline_x1_x1 cline_x1_y1 cline_x1_x2 cline_x1_y2
instance QqqLine_nf ((QPoint t1, QPoint t2)) where
qqLine_nf (x1, x2)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QLine3 cobj_x1 cobj_x2
instance QqLine_nf ((Point, Point)) where
qLine_nf (x1, x2)
= withObjectRefResult $
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
withCPoint x2 $ \cpoint_x2_x cpoint_x2_y ->
qtc_QLine4 cpoint_x1_x cpoint_x1_y cpoint_x2_x cpoint_x2_y
instance QqLine_nf ((Int, Int, Int, Int)) where
qLine_nf (x1, x2, x3, x4)
= withObjectRefResult $
qtc_QLine5 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance Qqdx (QLine a) (()) (IO (Int)) where
qdx x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLine_dx cobj_x0
foreign import ccall "qtc_QLine_dx" qtc_QLine_dx :: Ptr (TQLine a) -> IO CInt
instance Qqdy (QLine a) (()) (IO (Int)) where
qdy x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLine_dy cobj_x0
foreign import ccall "qtc_QLine_dy" qtc_QLine_dy :: Ptr (TQLine a) -> IO CInt
instance QqisNull (QLine a) (()) where
qisNull x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLine_isNull cobj_x0
foreign import ccall "qtc_QLine_isNull" qtc_QLine_isNull :: Ptr (TQLine a) -> IO CBool
instance Qqp1 (QLine a) (()) (IO (Point)) where
qp1 x0 ()
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLine_p1_qth cobj_x0 cpoint_ret_x cpoint_ret_y
foreign import ccall "qtc_QLine_p1_qth" qtc_QLine_p1_qth :: Ptr (TQLine a) -> Ptr CInt -> Ptr CInt -> IO ()
instance Qqqp1 (QLine a) (()) (IO (QPoint ())) where
qqp1 x0 ()
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLine_p1 cobj_x0
foreign import ccall "qtc_QLine_p1" qtc_QLine_p1 :: Ptr (TQLine a) -> IO (Ptr (TQPoint ()))
instance Qqp2 (QLine a) (()) (IO (Point)) where
qp2 x0 ()
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLine_p2_qth cobj_x0 cpoint_ret_x cpoint_ret_y
foreign import ccall "qtc_QLine_p2_qth" qtc_QLine_p2_qth :: Ptr (TQLine a) -> Ptr CInt -> Ptr CInt -> IO ()
instance Qqqp2 (QLine a) (()) (IO (QPoint ())) where
qqp2 x0 ()
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLine_p2 cobj_x0
foreign import ccall "qtc_QLine_p2" qtc_QLine_p2 :: Ptr (TQLine a) -> IO (Ptr (TQPoint ()))
instance Qqtranslate (QLine a) ((Int, Int)) (IO ()) where
qtranslate x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLine_translate1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QLine_translate1" qtc_QLine_translate1 :: Ptr (TQLine a) -> CInt -> CInt -> IO ()
instance Qqtranslate (QLine a) ((Point)) (IO ()) where
qtranslate x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QLine_translate_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QLine_translate_qth" qtc_QLine_translate_qth :: Ptr (TQLine a) -> CInt -> CInt -> IO ()
instance Qqqtranslate (QLine a) ((QPoint t1)) where
qqtranslate x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLine_translate cobj_x0 cobj_x1
foreign import ccall "qtc_QLine_translate" qtc_QLine_translate :: Ptr (TQLine a) -> Ptr (TQPoint t1) -> IO ()
instance Qqx1 (QLine a) (()) (IO (Int)) where
qx1 x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLine_x1 cobj_x0
foreign import ccall "qtc_QLine_x1" qtc_QLine_x1 :: Ptr (TQLine a) -> IO CInt
instance Qqx2 (QLine a) (()) (IO (Int)) where
qx2 x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLine_x2 cobj_x0
foreign import ccall "qtc_QLine_x2" qtc_QLine_x2 :: Ptr (TQLine a) -> IO CInt
instance Qqy1 (QLine a) (()) (IO (Int)) where
qy1 x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLine_y1 cobj_x0
foreign import ccall "qtc_QLine_y1" qtc_QLine_y1 :: Ptr (TQLine a) -> IO CInt
instance Qqy2 (QLine a) (()) (IO (Int)) where
qy2 x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLine_y2 cobj_x0
foreign import ccall "qtc_QLine_y2" qtc_QLine_y2 :: Ptr (TQLine a) -> IO CInt
qLine_delete :: QLine a -> IO ()
qLine_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLine_delete cobj_x0
foreign import ccall "qtc_QLine_delete" qtc_QLine_delete :: Ptr (TQLine a) -> IO ()
|
keera-studios/hsQt
|
Qtc/Core/QLine.hs
|
bsd-2-clause
| 7,320 | 0 | 15 | 1,414 | 2,671 | 1,376 | 1,295 | -1 | -1 |
{-|
Copyright : (C) 2012-2016, University of Twente
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <[email protected]>
Data Constructors in CoreHW
-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TemplateHaskell #-}
module CLaSH.Core.DataCon
( DataCon (..)
, DcName
, ConTag
, dataConInstArgTys
)
where
#ifndef MIN_VERSION_unbound_generics
#define MIN_VERSION_unbound_generics(x,y,z)(1)
#endif
import Control.DeepSeq (NFData(..))
import GHC.Generics (Generic)
import Unbound.Generics.LocallyNameless (Alpha(..),Name,Subst(..))
import Unbound.Generics.LocallyNameless.Extra ()
#if MIN_VERSION_unbound_generics(0,3,0)
import Data.Monoid (All (..))
import Unbound.Generics.LocallyNameless (NthPatFind (..),
NamePatFind (..))
#endif
import {-# SOURCE #-} CLaSH.Core.Type (TyName, Type)
import CLaSH.Util
-- | Data Constructor
data DataCon
= MkData
{ dcName :: !DcName -- ^ Name of the DataCon
, dcTag :: !ConTag -- ^ Syntactical position in the type definition
, dcType :: !Type -- ^ Type of the 'DataCon
, dcUnivTyVars :: [TyName] -- ^ Universally quantified type-variables,
-- these type variables are also part of the
-- result type of the DataCon
, dcExtTyVars :: [TyName] -- ^ Existentially quantified type-variables,
-- these type variables are not part of the result
-- of the DataCon, but only of the arguments.
, dcArgTys :: [Type] -- ^ Argument types
} deriving (Generic,NFData)
instance Show DataCon where
show = show . dcName
instance Eq DataCon where
(==) = (==) `on` dcName
instance Ord DataCon where
compare = compare `on` dcName
-- | Syntactical position of the DataCon in the type definition
type ConTag = Int
-- | DataCon reference
type DcName = Name DataCon
instance Alpha DataCon where
aeq' c dc1 dc2 = aeq' c (dcName dc1) (dcName dc2)
fvAny' _ _ dc = pure dc
close _ _ dc = dc
open _ _ dc = dc
isPat _ = mempty
#if MIN_VERSION_unbound_generics(0,3,0)
isTerm _ = All True
nthPatFind _ = NthPatFind Left
namePatFind _ = NamePatFind (const (Left 0))
#else
isTerm _ = True
nthPatFind _ = Left
namePatFind _ _ = Left 0
#endif
swaps' _ _ dc = dc
lfreshen' _ dc cont = cont dc mempty
freshen' _ dc = return (dc,mempty)
acompare' c dc1 dc2 = acompare' c (dcName dc1) (dcName dc2)
instance Subst a DataCon where
subst _ _ dc = dc
substs _ dc = dc
-- | Given a DataCon and a list of types, the type variables of the DataCon
-- type are substituted for the list of types. The argument types are returned.
--
-- The list of types should be equal to the number of type variables, otherwise
-- @Nothing@ is returned.
dataConInstArgTys :: DataCon -> [Type] -> Maybe [Type]
dataConInstArgTys (MkData { dcArgTys = arg_tys
, dcUnivTyVars = univ_tvs
, dcExtTyVars = ex_tvs
})
inst_tys
| length tyvars == length inst_tys
= Just (map (substs (zip tyvars inst_tys)) arg_tys)
| otherwise
= Nothing
where
tyvars = univ_tvs ++ ex_tvs
|
ggreif/clash-compiler
|
clash-lib/src/CLaSH/Core/DataCon.hs
|
bsd-2-clause
| 3,632 | 0 | 12 | 1,124 | 674 | 389 | 285 | 69 | 1 |
module Elm.Package where
import Control.Applicative ((<$>), (<*>))
import Data.Aeson
import Data.Binary
import qualified Data.Char as Char
import Data.Function (on)
import qualified Data.List as List
import qualified Data.Text as T
import System.FilePath ((</>))
-- PACKGE NAMES
data Name = Name
{ user :: String
, project :: String
}
deriving (Eq, Ord, Show)
type Package = (Name, Version)
dummyName :: Name
dummyName =
Name "USER" "PROJECT"
coreName :: Name
coreName =
Name "elm-lang" "core"
toString :: Name -> String
toString name =
user name ++ "/" ++ project name
toUrl :: Name -> String
toUrl name =
user name ++ "/" ++ project name
toFilePath :: Name -> FilePath
toFilePath name =
user name </> project name
fromString :: String -> Either String Name
fromString string =
case break (=='/') string of
( user, '/' : project ) ->
if null user then
Left "You did not provide a user name (USER/PROJECT)"
else if null project then
Left "You did not provide a project name (USER/PROJECT)"
else if all (/='/') project then
Name user <$> validate project
else
Left "Expecting only one slash, separating the user and project name (USER/PROJECT)"
_ ->
Left "There should be a slash separating the user and project name (USER/PROJECT)"
validate :: String -> Either String String
validate str =
if elem ('-','-') (zip str (tail str)) then
Left "There is a double dash -- in your package name. It must be a single dash."
else if elem '_' str then
Left "Underscores are not allowed in package names."
else if any Char.isUpper str then
Left "Upper case characters are not allowed in package names."
else if not (Char.isLetter (head str)) then
Left "Package names must start with a letter."
else
Right str
instance Binary Name where
get = Name <$> get <*> get
put (Name user project) =
do put user
put project
instance FromJSON Name where
parseJSON (String text) =
let
string = T.unpack text
in
case fromString string of
Left msg ->
fail ("Ran into an invalid package name: " ++ string ++ "\n\n" ++ msg)
Right name ->
return name
parseJSON _ =
fail "Project name must be a string."
instance ToJSON Name where
toJSON name =
toJSON (toString name)
-- PACKAGE VERSIONS
data Version = Version
{ _major :: Int
, _minor :: Int
, _patch :: Int
}
deriving (Eq, Ord)
initialVersion :: Version
initialVersion =
Version 1 0 0
dummyVersion :: Version
dummyVersion =
Version 0 0 0
bumpPatch :: Version -> Version
bumpPatch (Version major minor patch) =
Version major minor (patch + 1)
bumpMinor :: Version -> Version
bumpMinor (Version major minor _patch) =
Version major (minor + 1) 0
bumpMajor :: Version -> Version
bumpMajor (Version major _minor _patch) =
Version (major + 1) 0 0
-- FILTERING
filterLatest :: (Ord a) => (Version -> a) -> [Version] -> [Version]
filterLatest characteristic versions =
map last (List.groupBy ((==) `on` characteristic) (List.sort versions))
majorAndMinor :: Version -> (Int,Int)
majorAndMinor (Version major minor _patch) =
(major, minor)
-- CONVERSIONS
versionToString :: Version -> String
versionToString (Version major minor patch) =
show major ++ "." ++ show minor ++ "." ++ show patch
versionFromString :: String -> Either String Version
versionFromString string =
case splitNumbers string of
Just [major, minor, patch] ->
Right (Version major minor patch)
_ ->
Left "Must have format MAJOR.MINOR.PATCH (e.g. 1.0.2)"
where
splitNumbers :: String -> Maybe [Int]
splitNumbers ns =
case span Char.isDigit ns of
("", _) ->
Nothing
(numbers, []) ->
Just [ read numbers ]
(numbers, '.':rest) ->
(read numbers :) <$> splitNumbers rest
_ ->
Nothing
instance Binary Version where
get = Version <$> get <*> get <*> get
put (Version major minor patch) =
do put major
put minor
put patch
instance FromJSON Version where
parseJSON (String text) =
let string = T.unpack text in
case versionFromString string of
Right v ->
return v
Left problem ->
fail $ unlines
[ "Ran into an invalid version number: " ++ string
, problem
]
parseJSON _ =
fail "Version number must be stored as a string."
instance ToJSON Version where
toJSON version =
toJSON (versionToString version)
|
Axure/elm-compiler
|
src/Elm/Package.hs
|
bsd-3-clause
| 4,869 | 3 | 16 | 1,482 | 1,388 | 718 | 670 | 140 | 5 |
{-# LANGUAGE RecursiveDo #-}
module Expr where
import Control.Applicative
import Data.Char
import Test.Tasty
import Test.Tasty.QuickCheck as QC
import Text.Earley
tests :: TestTree
tests = testGroup "Expr"
[ QC.testProperty "Expr: parse . pretty = id" $
\e -> [e] === parseExpr (prettyExpr 0 e)
, QC.testProperty "Ambiguous Expr: parse . pretty ≈ id" $
\e -> e `elem` parseAmbiguousExpr (prettyExpr 0 e)
]
parseExpr :: String -> [Expr]
parseExpr input = fst (fullParses (parser expr) (lexExpr input)) -- We need to annotate types for point-free version
parseAmbiguousExpr :: String -> [Expr]
parseAmbiguousExpr input = fst (fullParses (parser ambiguousExpr) (lexExpr input))
data Expr
= Add Expr Expr
| Mul Expr Expr
| Var String
deriving (Eq, Ord, Show)
instance Arbitrary Expr where
arbitrary = sized arbExpr
where arbIdent = Var <$> elements ["a", "b", "c", "x", "y", "z"]
arbExpr n | n > 0 = oneof [ arbIdent
, Add <$> arbExpr1 <*> arbExpr1
, Mul <$> arbExpr1 <*> arbExpr1
]
where arbExpr1 = arbExpr (n `div` 2)
arbExpr _ = arbIdent
shrink (Var _) = []
shrink (Add a b) = a : b : [ Add a' b | a' <- shrink a ] ++ [ Add a b' | b' <- shrink b ]
shrink (Mul a b) = a : b : [ Mul a' b | a' <- shrink a ] ++ [ Mul a b' | b' <- shrink b ]
expr :: Grammar r (Prod r String String Expr)
expr = mdo
x1 <- rule $ Add <$> x1 <* namedToken "+" <*> x2
<|> x2
<?> "sum"
x2 <- rule $ Mul <$> x2 <* namedToken "*" <*> x3
<|> x3
<?> "product"
x3 <- rule $ Var <$> (satisfy ident <?> "identifier")
<|> namedToken "(" *> x1 <* namedToken ")"
return x1
where
ident (x:_) = isAlpha x
ident _ = False
ambiguousExpr :: Grammar r (Prod r String String Expr)
ambiguousExpr = mdo
x1 <- rule $ Add <$> x1 <* namedToken "+" <*> x1
<|> x2
<?> "sum"
x2 <- rule $ Mul <$> x2 <* namedToken "*" <*> x2
<|> x3
<?> "product"
x3 <- rule $ Var <$> (satisfy ident <?> "identifier")
<|> namedToken "(" *> x1 <* namedToken ")"
return x1
where
ident (x:_) = isAlpha x
ident _ = False
prettyParens :: Bool -> String -> String
prettyParens True s = "(" ++ s ++ ")"
prettyParens False s = s
prettyExpr :: Int -> Expr -> String
prettyExpr _ (Var s) = s
prettyExpr d (Add a b) = prettyParens (d > 0) $ prettyExpr 0 a ++ " + " ++ prettyExpr 1 b
prettyExpr d (Mul a b) = prettyParens (d > 1) $ prettyExpr 1 a ++ " * " ++ prettyExpr 2 b
-- @words@ like lexer, but consider parentheses as separate tokens
lexExpr :: String -> [String]
lexExpr "" = []
lexExpr ('(' : s) = "(" : lexExpr s
lexExpr (')' : s) = ")" : lexExpr s
lexExpr (c : s)
| isSpace c = lexExpr s
| otherwise = let (tok, rest) = span p (c : s)
in tok : lexExpr rest
where p x = not (x == '(' || x == ')' || isSpace x)
|
sboosali/Earley
|
tests/Expr.hs
|
bsd-3-clause
| 3,091 | 0 | 14 | 991 | 1,200 | 603 | 597 | 75 | 2 |
module PackageTests.TestSuiteExeV10.Check (checks) where
import qualified Control.Exception as E (IOException, catch)
import Control.Monad (when)
import Data.Maybe (catMaybes)
import System.Directory ( doesFileExist )
import System.FilePath
import Test.Tasty
import Test.Tasty.HUnit
import Distribution.Compiler (CompilerFlavor(..), CompilerId(..))
import Distribution.PackageDescription (package)
import Distribution.Simple.Compiler (compilerId)
import Distribution.Simple.Configure (getPersistBuildConfig)
import Distribution.Simple.LocalBuildInfo (compiler, localPkgDescr, pkgKey)
import Distribution.Simple.Hpc
import Distribution.Simple.Program.Builtin (hpcProgram)
import Distribution.Simple.Program.Db
( emptyProgramDb, configureProgram, requireProgramVersion )
import Distribution.Text (display)
import qualified Distribution.Verbosity as Verbosity
import Distribution.Version (Version(..), orLaterVersion)
import PackageTests.PackageTester
checks :: SuiteConfig -> [TestTree]
checks config =
[ testCase "Test" $ checkTest config ]
++ hpcTestMatrix config ++
[ testCase "TestNoHpc/NoTix" $ checkTestNoHpcNoTix config
, testCase "TestNoHpc/NoMarkup" $ checkTestNoHpcNoMarkup config
]
hpcTestMatrix :: SuiteConfig -> [TestTree]
hpcTestMatrix config = do
libProf <- [True, False]
exeProf <- [True, False]
exeDyn <- [True, False]
shared <- [True, False]
let name = concat
[ "WithHpc-"
, if libProf then "LibProf" else ""
, if exeProf then "ExeProf" else ""
, if exeDyn then "ExeDyn" else ""
, if shared then "Shared" else ""
]
enable cond flag
| cond = Just $ "--enable-" ++ flag
| otherwise = Nothing
opts = catMaybes
[ enable libProf "library-profiling"
, enable exeProf "profiling"
, enable exeDyn "executable-dynamic"
, enable shared "shared"
]
return $ testCase name $ checkTestWithHpc config name opts
dir :: FilePath
dir = "PackageTests" </> "TestSuiteExeV10"
checkTest :: SuiteConfig -> Assertion
checkTest config = buildAndTest config "Default" [] []
shouldExist :: FilePath -> Assertion
shouldExist path = doesFileExist path >>= assertBool (path ++ " should exist")
shouldNotExist :: FilePath -> Assertion
shouldNotExist path =
doesFileExist path >>= assertBool (path ++ " should exist") . not
-- | Ensure that both .tix file and markup are generated if coverage is enabled.
checkTestWithHpc :: SuiteConfig -> String -> [String] -> Assertion
checkTestWithHpc config name extraOpts = do
isCorrectVersion <- correctHpcVersion
when isCorrectVersion $ do
let distPref' = dir </> "dist-" ++ name
buildAndTest config name [] ("--enable-coverage" : extraOpts)
lbi <- getPersistBuildConfig distPref'
let way = guessWay lbi
CompilerId comp version = compilerId (compiler lbi)
subdir
| comp == GHC && version >= Version [7, 10] [] =
display (pkgKey lbi)
| otherwise = display (package $ localPkgDescr lbi)
mapM_ shouldExist
[ mixDir distPref' way "my-0.1" </> subdir </> "Foo.mix"
, mixDir distPref' way "test-Foo" </> "Main.mix"
, tixFilePath distPref' way "test-Foo"
, htmlDir distPref' way "test-Foo" </> "hpc_index.html"
]
-- | Ensures that even if -fhpc is manually provided no .tix file is output.
checkTestNoHpcNoTix :: SuiteConfig -> Assertion
checkTestNoHpcNoTix config = do
buildAndTest config "NoHpcNoTix" []
[ "--ghc-option=-fhpc"
, "--ghc-option=-hpcdir"
, "--ghc-option=dist-NoHpcNoTix/hpc/vanilla" ]
lbi <- getPersistBuildConfig (dir </> "dist-NoHpcNoTix")
let way = guessWay lbi
shouldNotExist $ tixFilePath (dir </> "dist-NoHpcNoTix") way "test-Foo"
-- | Ensures that even if a .tix file happens to be left around
-- markup isn't generated.
checkTestNoHpcNoMarkup :: SuiteConfig -> Assertion
checkTestNoHpcNoMarkup config = do
let tixFile = tixFilePath "dist-NoHpcNoMarkup" Vanilla "test-Foo"
buildAndTest config "NoHpcNoMarkup"
[("HPCTIXFILE", Just tixFile)]
[ "--ghc-option=-fhpc"
, "--ghc-option=-hpcdir"
, "--ghc-option=dist-NoHpcNoMarkup/hpc/vanilla" ]
shouldNotExist $ htmlDir (dir </> "dist-NoHpcNoMarkup") Vanilla "test-Foo" </> "hpc_index.html"
-- | Build and test a package and ensure that both were successful.
--
-- The flag "--enable-tests" is provided in addition to the given flags.
buildAndTest :: SuiteConfig -> String -> [(String, Maybe String)] -> [String] -> IO ()
buildAndTest config name envOverrides flags = do
let spec = PackageSpec
{ directory = dir
, distPref = Just $ "dist-" ++ name
, configOpts = "--enable-tests" : flags
}
buildResult <- cabal_build config spec
assertBuildSucceeded buildResult
testResult <- cabal_test config spec envOverrides []
assertTestSucceeded testResult
-- | Checks for a suitable HPC version for testing.
correctHpcVersion :: IO Bool
correctHpcVersion = do
let programDb' = emptyProgramDb
let verbosity = Verbosity.normal
let verRange = orLaterVersion (Version [0,7] [])
programDb <- configureProgram verbosity hpcProgram programDb'
(requireProgramVersion verbosity hpcProgram verRange programDb
>> return True) `catchIO` (\_ -> return False)
where
-- Distribution.Compat.Exception is hidden.
catchIO :: IO a -> (E.IOException -> IO a) -> IO a
catchIO = E.catch
|
ian-ross/cabal
|
Cabal/tests/PackageTests/TestSuiteExeV10/Check.hs
|
bsd-3-clause
| 5,629 | 0 | 18 | 1,246 | 1,373 | 720 | 653 | 113 | 5 |
module Aws.Ddb.Commands.JTypes (
Attribute (..),
ExpectedAttribute (..),
AttrValue (..),
ConsumedCapacity (..),
ReturnConsumedCapacity (..),
ReturnCollectionMetrics (..)
) where
import qualified Data.Either as E
import qualified Data.Vector as V
import qualified Data.Text as T
import qualified Data.ByteString as B
import qualified Data.List as L
import qualified Data.Text.Read as TR
import qualified Data.HashMap.Strict as HM
import Control.Monad (mzero)
import Control.Applicative ((<$>), (<*>))
import Data.Aeson (Value (Object, Array, String),
ToJSON (..), FromJSON (..), object, (.:), (.=))
data AttrValue = S T.Text | SS [T.Text] |
B B.ByteString | BS [B.ByteString] |
I Int | IS [Int] |
D Double | DS [Double]
deriving Show
data Attribute = Attribute { iname :: T.Text,
ivalue :: AttrValue }
deriving Show
instance ToJSON Attribute where
toJSON (Attribute name value) =
object [ name .= value ]
-- instance FromJSON Attribute where
-- parseJSON (Object o) = let keys = HM.keys o
-- in map parseAttr keys
-- where
-- parseAttr key = Attribute <$>
-- o .:? "" .!= key <*>
-- o .: key
data ExpectedAttribute = ExpectedAttribute { ename :: T.Text,
exists :: Bool,
evalue :: AttrValue }
deriving Show
instance ToJSON ExpectedAttribute where
toJSON (ExpectedAttribute name exists value) =
object [ "Exists" .= exists,
name .= value ]
instance ToJSON AttrValue where
toJSON av =
case av of
S txt -> object [ "S" .= txt ]
SS txts -> object [ "SS" .= txts]
B bs -> object [ "B" .= bs ]
BS bss -> object [ "BS" .= bss ]
I i -> object [ "N" .= show i ]
IS is -> object [ "NS" .= map show is ]
D d -> object [ "N" .= show d ]
DS ds -> object [ "NS" .= map show ds ]
-- FIXME RPR :: Aeson must have a better way.
isMaybeInt :: Maybe Value -> Bool
isMaybeInt (Just (String s)) = case TR.decimal s :: E.Either String (Integer, T.Text) of
Right _ -> True
Left _ -> False
isMaybeInt _ = False
-- FIXME RPR - OUCH OUCH!! parsing the string twice :(
allInts :: Maybe Value -> Bool
allInts (Just (Array vs)) = L.all isInt (V.toList vs)
where
isInt (String s) = case TR.decimal s :: E.Either String (Integer, T.Text) of
Right _ -> True
Left _ -> False
isInt _ = False
allInts _ = False
instance FromJSON AttrValue where
parseJSON (Object o) = let typeCode = L.head (HM.keys o)
in
case typeCode of
"S" -> S <$> (o .: "S")
"SS" -> SS <$> (o .: "SS")
"B" -> B <$> (o .: "B")
"BS" -> BS <$> (o .: "BB")
"N" -> parseN
"NS" -> parseNS
_ -> mzero
where
parseN = if isMaybeInt $ HM.lookup "N" o then parseI
else parseD
parseNS = if allInts $ HM.lookup "NS" o then parseIS
else parseDS
parseI = I <$> (o .: "N")
parseD = D <$> (o .: "N")
parseIS = IS <$> (o .: "N")
parseDS = DS <$> (o .: "N")
parseJSON _ = mzero
newtype ReturnConsumedCapacity = ReturnConsumedCapacity Bool
deriving Show
instance ToJSON ReturnConsumedCapacity where
toJSON (ReturnConsumedCapacity rcc) = if rcc then "TOTAL" else "NONE"
newtype ReturnCollectionMetrics = ReturnCollectionMetrics Bool
deriving Show
instance ToJSON ReturnCollectionMetrics where
toJSON (ReturnCollectionMetrics ricm) = if ricm then "SIZE" else "NONE"
data ConsumedCapacity = ConsumedCapacity { ccTableName :: T.Text,
ccUnits :: Int }
deriving Show
instance FromJSON ConsumedCapacity where
parseJSON (Object o) = ConsumedCapacity <$>
o .: "TableName" <*>
o .: "CapacityUnits"
parseJSON _ = mzero
|
RayRacine/aws
|
Aws/Ddb/Commands/JTypes.hs
|
bsd-3-clause
| 4,689 | 0 | 13 | 1,945 | 1,202 | 668 | 534 | 95 | 3 |
module Problem104 where
import Data.Array
import Data.List
lim :: Int
lim = 500000
main :: IO ()
main =
print
. head
. filter
(\x -> isPandigital (take 9 . show . fst $ fib1 ! x)
&& isPandigital (show $ fib2 ! x)
)
$ [1 ..]
where
fib1 :: Array Int (Integer, Int)
fib1 = array (1, lim) (zip [1 ..] $ map fib1' [1 .. lim])
fib1' x
| x == 1 = (1, 0)
| x == 2 = (1, 0)
| extra == 0 && n == n' = (v'', n)
| otherwise = (read (take 20 $ show v''), n + extra)
where
extra = max 0 (length (show v'') - 20)
v'' = v + read (take (length (show v') - (n - n')) $ show v')
(v , n ) = fib1 ! (x - 1)
(v', n') = fib1 ! (x - 2)
fib2 = array (1, lim) (zip [1 ..] $ map fib2' [1 .. lim])
fib2' x
| x == 1 = 1
| x == 2 = 1
| otherwise = (x' + x'') `mod` 1000000000
where
x' = fib2 ! (x - 1)
x'' = fib2 ! (x - 2)
isPandigital xs = length xs == 9 && and (zipWith (==) ['1' .. '9'] (sort xs))
|
adityagupta1089/Project-Euler-Haskell
|
src/problems/Problem104.hs
|
bsd-3-clause
| 1,141 | 0 | 18 | 489 | 569 | 301 | 268 | 32 | 1 |
module Air.Cli.Interpretation where
import Database.Persist
import System.Log.FastLogger (LoggerSet)
import Air.Cli
import qualified Air.Domain as D
import qualified Air.Persistence as P
-- The persistence layer interpretation of a given command. A branch is selected
-- for the given command, and with the result, the continuation computation
-- is called.
interpretation :: (PersistQuery m) => LoggerSet -> Command -> m Result
interpretation logger = commandCata
createFlatmate
deactivateFlatmate
activateFlatmate
createBill
attendBill
flatmateInformation
payBill
flatmateBalance
flatmateDeposit
payment
quit
help
where
createFlatmate username fullname
= do P.insertFlatMate (D.FlatMate (D.User username) fullname)
return NoResult
deactivateFlatmate username
= do P.deactivateFlatmate (D.User username)
return NoResult
activateFlatmate username
= do let user = D.User username
inactives <- P.inactiveFlatmates
case elem user inactives of
True -> do P.activateFlatmate user
return NoResult
False -> return $ ErrResult $ "Not an inactive user" ++ show inactives
createBill billname usernames
= do P.saveBill (D.Bill billname (map D.User usernames))
return NoResult
attendBill username billname
= do P.attendBill (D.User username) billname
return NoResult
flatmateInformation username
= undefined
payBill billname amount
= do P.logBalance logger
P.payBill logger billname (fromIntegral amount)
P.logBalance logger
return NoResult
flatmateBalance username
= do P.userBalance (D.User username)
return NoResult
flatmateDeposit username amount
= do P.logBalance logger
P.deposit logger (D.User username) (D.Deposit (fromIntegral amount))
P.logBalance logger
return NoResult
payment usernames amount desc
= do P.logBalance logger
P.payment (D.createPayment (map D.User usernames) (fromIntegral amount) desc)
P.logBalance logger
return NoResult
quit = return NoResult
help = return NoResult
-- The result of the interpreted command
data Result
= NoResult -- No additional information is computed
| ErrResult String -- Some error happened, with a given message
| FlatmateInfo D.FlatMate -- The description of the flatmate
deriving (Show, Eq)
resultCata noResult errResult flatmateInfo r = case r of
NoResult -> noResult
ErrResult msg -> errResult msg
FlatmateInfo flatmate -> flatmateInfo flatmate
-- Computational context containing users, bills, balances and the flatbalance.
newtype Context = Context ([D.User], [String], D.Account, D.FlatBalance)
deriving (Show, Eq)
contextCata f (Context (users, bills, balances, flatBalance)) =
f users bills balances flatBalance
-- Read the stored context from the persistent layer
storedContext :: (PersistQuery m) => m Context
storedContext = do
us <- P.users
bs <- P.bills
(balance, flat) <- P.loadBalance
return (Context (us, bs, balance, flat))
|
andorp/air
|
src/Air/Cli/Interpretation.hs
|
bsd-3-clause
| 3,193 | 0 | 15 | 774 | 824 | 405 | 419 | 80 | 3 |
module Main where
import qualified Lexer
import qualified Parser
main :: IO ()
main = do
input <- getContents
let parsed = Parser.parse "" =<< Lexer.lex "" input
either print (mapM_ print) parsed
|
letsbreelhere/egg
|
app/Parsegg.hs
|
bsd-3-clause
| 204 | 0 | 12 | 41 | 75 | 38 | 37 | 8 | 1 |
{-# LANGUAGE
DeriveGeneric
, LambdaCase
, MultiParamTypeClasses #-}
module Type.BindingFlag
( BindingFlag (..)
, flexible
, rigid
) where
import Control.Lens
import Data.Semigroup
import GHC.Generics (Generic)
import Text.PrettyPrint.Free (Pretty (pretty), char)
data BindingFlag = Flexible | Rigid deriving (Show, Eq, Generic)
instance Semigroup BindingFlag where
Rigid <> _ = Rigid
_ <> Rigid = Rigid
Flexible <> Flexible = Flexible
instance Monoid BindingFlag where
mempty = Flexible
mappend = (<>)
instance Pretty BindingFlag where
pretty = \ case
Flexible -> char '>'
Rigid -> char '='
instance VariantA BindingFlag BindingFlag () ()
instance VariantB BindingFlag BindingFlag () ()
flexible :: Prism' BindingFlag ()
flexible = _A
rigid :: Prism' BindingFlag ()
rigid = _B
|
sonyandy/mlf
|
src/Type/BindingFlag.hs
|
bsd-3-clause
| 844 | 0 | 9 | 181 | 247 | 134 | 113 | 30 | 1 |
module Idris.Lexer where
import Data.Char
import Debug.Trace
import Idris.AbsSyntax
type LineNumber = Int
type P a = String -> String -> LineNumber -> Fixities -> Result a
getLineNo :: P LineNumber
getLineNo = \s fn l ops -> Success l
getFileName :: P String
getFileName = \s fn l ops -> Success fn
getContent :: P String
getContent = \s fn l ops -> Success s
getOps :: P Fixities
getOps = \s fn l ops -> Success ops
thenP :: P a -> (a -> P b) -> P b
m `thenP` k = \s fn l ops ->
case m s fn l ops of
Success a -> k a s fn l ops
Failure e f ln -> Failure e f ln
returnP :: a -> P a
returnP a = \s fn l ops -> Success a
failP :: String -> P a
failP err = \s fn l ops -> Failure err fn l
catchP :: P a -> (String -> P a) -> P a
catchP m k = \s fn l ops ->
case m s fn l ops of
Success a -> Success a
Failure e f ln -> k e s fn l ops
happyError :: P a
happyError = reportError "Parse error"
reportError :: String -> P a
reportError err = getFileName `thenP` \fn ->
getLineNo `thenP` \line ->
getContent `thenP` \str ->
failP (fn ++ ":" ++ show line ++ ":" ++ err ++
" - before " ++ take 80 str ++ "...")
data Token
= TokenName Id
| TokenNSep
| TokenInfixName String
| TokenBrackName Id
| TokenString String
| TokenInt Int
| TokenFloat Double
| TokenChar Char
| TokenBool Bool
| TokenMetavar Id
| TokenIntType
| TokenCharType
| TokenBoolType
| TokenFloatType
| TokenStringType
| TokenHandleType
| TokenLockType
| TokenPtrType
| TokenDataType
| TokenInfix
| TokenInfixL
| TokenInfixR
| TokenParams
| TokenUsing
| TokenIdiom
| TokenNoElim
| TokenCollapsible
| TokenPartial
| TokenSyntax
| TokenLazy
| TokenStatic
| TokenWhere
| TokenWith
| TokenType
| TokenLazyBracket
| TokenOB
| TokenCB
| TokenOCB
| TokenCCB
| TokenHashOB
| TokenLPair
| TokenRPair
| TokenOSB
| TokenCSB
| TokenOId
| TokenCId
-- | TokenExists
| TokenConcat
| TokenTilde
| TokenPlus
| TokenMinus
| TokenTimes
| TokenDivide
| TokenEquals
| TokenOr
| TokenAnd
| TokenMightEqual
| TokenEQ
| TokenGE
| TokenLE
| TokenGT
| TokenLT
| TokenArrow
| TokenFatArrow
| TokenTransArrow
| TokenLeftArrow
| TokenColon
| TokenSemi
| TokenComma
| TokenTuple
| TokenBar
| TokenStars
| TokenDot
| TokenEllipsis
| TokenLambda
| TokenInclude
| TokenModule
| TokenNamespace
| TokenPublic
| TokenPrivate
| TokenAbstract
| TokenImport
| TokenExport
| TokenInline
| TokenDo
| TokenReturn
| TokenIf
| TokenThen
| TokenElse
| TokenLet
| TokenIn
| TokenRefl
| TokenEmptyType
| TokenUnitType
| TokenUnderscore
| TokenBang
-- Tactics
| TokenProof
| TokenIntro
| TokenRefine
| TokenExists
| TokenGeneralise
| TokenReflP
| TokenRewrite
| TokenRewriteAll
| TokenCompute
| TokenUnfold
| TokenUndo
| TokenInduction
| TokenFill
| TokenTrivial
| TokenMkTac
| TokenBelieve
| TokenUse
| TokenDecide
| TokenAbandon
| TokenProofTerm
| TokenQED
-- Directives
| TokenLaTeX
| TokenNoCG
| TokenEval
| TokenSpec
| TokenFreeze
| TokenThaw
| TokenTransform
| TokenCInclude
| TokenCLib
| TokenEOF
deriving (Show, Eq)
lexer :: (Token -> P a) -> P a
lexer cont [] = cont TokenEOF []
lexer cont ('\n':cs) = \fn line -> lexer cont cs fn (line+1)
-- empty type
lexer cont ('_':'|':'_':cs) = cont TokenEmptyType cs
lexer cont ('_':c:cs) | not (isAlpha c) && c/='_' = cont TokenUnderscore (c:cs)
lexer cont (c:cs)
| isSpace c = \fn line -> lexer cont cs fn line
| isAlpha c = lexVar cont (c:cs)
| isDigit c = lexNum cont (c:cs)
| c == '_' = lexVar cont (c:cs)
-- unit type
lexer cont ('(':')':cs) = cont TokenUnitType cs
lexer cont ('"':cs) = lexString cont cs
lexer cont ('\'':cs) = lexChar cont cs
lexer cont ('{':'-':cs) = lexerEatComment 0 cont cs
lexer cont ('-':'-':cs) = lexerEatToNewline cont cs
lexer cont ('(':cs) = cont TokenOB cs
lexer cont (')':cs) = cont TokenCB cs
lexer cont ('{':c:cs)
| isAlpha c || c=='_' = lexBrackVar cont (c:cs)
lexer cont ('{':cs) = cont TokenOCB cs
lexer cont ('}':cs) = cont TokenCCB cs
lexer cont ('[':'|':cs) = cont TokenOId cs
lexer cont ('|':']':cs) = cont TokenCId cs
lexer cont ('[':cs) = cont TokenOSB cs
lexer cont (']':cs) = cont TokenCSB cs
lexer cont ('?':'=':cs) = cont TokenMightEqual cs
lexer cont (';':cs) = cont TokenSemi cs
lexer cont ('\\':cs) = cont TokenLambda cs
lexer cont ('#':'(':cs) = cont TokenHashOB cs
-- lexer cont ('#':cs) = cont TokenType cs
lexer cont (',':cs) = cont TokenComma cs
lexer cont ('|':'(':cs) = cont TokenLazyBracket cs
lexer cont ('%':cs) = lexSpecial cont cs
lexer cont ('?':cs) = lexMeta cont cs
lexer cont (c:cs) | isOpPrefix c = lexOp cont (c:cs)
lexer cont (c:cs) = lexError c cs
lexError c s l ops = failP (show l ++ ": Unrecognised token '" ++ [c] ++ "'\n") s l ops
lexerEatComment nls cont ('-':'}':cs)
= \fn line -> lexer cont cs fn (line+nls)
lexerEatComment nls cont ('\n':cs) = lexerEatComment (nls+1) cont cs
lexerEatComment nls cont (c:cs) = lexerEatComment nls cont cs
lexerEatToNewline cont ('\n':cs)
= \fn line -> lexer cont cs fn (line+1)
lexerEatToNewline cont []
= \fn line -> lexer cont [] fn line
lexerEatToNewline cont (c:cs) = lexerEatToNewline cont cs
lexNum cont cs = case readNum cs of
(num,rest,isreal) ->
cont (tok num isreal) rest
where tok num isreal | isreal = TokenFloat (read num)
| otherwise = TokenInt (read num)
readNum :: String -> (String,String,Bool)
readNum x = rn' False "" x
where rn' dot acc [] = (acc,[],dot)
rn' False acc ('.':xs) | head xs /= '.' = rn' True (acc++".") xs
rn' dot acc (x:xs) | isDigit x = rn' dot (acc++[x]) xs
rn' dot acc ('e':'+':xs) = rn' True (acc++"e+") xs
rn' dot acc ('e':'-':xs) = rn' True (acc++"e-") xs
rn' dot acc ('e':xs) = rn' True (acc++"e") xs
rn' dot acc xs = (acc,xs,dot)
lexString cont cs =
\fn line ops ->
case getstr cs of
Just (str,rest,nls) -> cont (TokenString str) rest fn (nls+line) ops
Nothing -> failP (fn++":"++show line++":Unterminated string contant")
cs fn line ops
lexChar cont cs =
\fn line ops ->
case getchar cs of
Just (str,rest) -> cont (TokenChar str) rest fn line ops
Nothing ->
failP (fn++":"++show line++":Unterminated character constant")
cs fn line ops
isAllowed c = isAlpha c || isDigit c || c `elem` "_\'?#."
lexVar cont cs =
case span isAllowed cs of
-- Keywords
("proof",rest) -> cont TokenProof rest
("data",rest) -> cont TokenDataType rest
("using",rest) -> cont TokenUsing rest
("idiom",rest) -> cont TokenIdiom rest
("params",rest) -> cont TokenParams rest
("namespace",rest) -> cont TokenNamespace rest
("public",rest) -> cont TokenPublic rest
("private",rest) -> cont TokenPrivate rest
("abstract",rest) -> cont TokenAbstract rest
("module",rest) -> cont TokenModule rest
("import",rest) -> cont TokenImport rest
("export",rest) -> cont TokenExport rest
("inline",rest) -> cont TokenInline rest
("noElim",rest) -> cont TokenNoElim rest
("collapsible",rest) -> cont TokenCollapsible rest
("where",rest) -> cont TokenWhere rest
("with",rest) -> cont TokenWith rest
("partial",rest) -> cont TokenPartial rest
("syntax",rest) -> cont TokenSyntax rest
("lazy",rest) -> cont TokenLazy rest
("static",rest) -> cont TokenStatic rest
("infix",rest) -> cont TokenInfix rest
("infixl",rest) -> cont TokenInfixL rest
("infixr",rest) -> cont TokenInfixR rest
("exists",rest) -> cont TokenExists rest
-- Types
("Set",rest) -> cont TokenType rest
("Int",rest) -> cont TokenIntType rest
("Char",rest) -> cont TokenCharType rest
("Float",rest) -> cont TokenFloatType rest
("String",rest) -> cont TokenStringType rest
("Lock",rest) -> cont TokenLockType rest
("Handle",rest) -> cont TokenHandleType rest
("Ptr",rest) -> cont TokenPtrType rest
("refl",rest) -> cont TokenRefl rest
("include",rest) -> cont TokenInclude rest
("do",rest) -> cont TokenDo rest
("return",rest) -> cont TokenReturn rest
("if",rest) -> cont TokenIf rest
("then",rest) -> cont TokenThen rest
("else",rest) -> cont TokenElse rest
("let",rest) -> cont TokenLet rest
("in",rest) -> cont TokenIn rest
-- values
-- expressions
(var,rest) -> cont (mkname var) rest
lexOp cont cs = case span isOpChar cs of
(":",rest) -> cont TokenColon rest
-- ("+",rest) -> cont TokenPlus rest
("-",rest) -> cont TokenMinus rest
-- ("*",rest) -> cont TokenTimes rest
-- ("/",rest) -> cont TokenDivide rest
("=",rest) -> cont TokenEquals rest
-- ("==",rest) -> cont TokenEQ rest
(">",rest) -> cont TokenGT rest
("<",rest) -> cont TokenLT rest
-- (">=",rest) -> cont TokenGE rest
-- ("<=",rest) -> cont TokenLE rest
-- ("++",rest) -> cont TokenConcat rest
-- ("&&",rest) -> cont TokenAnd rest
("<|",rest) -> cont TokenLPair rest
("|>",rest) -> cont TokenRPair rest
("&",rest) -> cont TokenTuple rest
-- ("||",rest) -> cont TokenOr rest
("...",rest) -> cont TokenEllipsis rest
("**",rest) -> cont TokenStars rest
("|",rest) -> cont TokenBar rest
("!",rest) -> cont TokenBang rest
("->", rest) -> cont TokenArrow rest
("=>", rest) -> cont TokenFatArrow rest
-- ("==>", rest) -> cont TokenTransArrow rest
("<-", rest) -> cont TokenLeftArrow rest
("~", rest) -> cont TokenTilde rest
(op,rest) -> cont (TokenInfixName op) rest
isOpPrefix c = c `elem` ":+-*/=_.?|&><!@$%^~#"
isOpChar = isOpPrefix
lexBrackVar cont cs =
case span isAllowed cs of
(var,rest) -> cont (TokenBrackName (UN var)) rest
lexSpecial cont cs =
case span isAllowed cs of
("latex",rest) -> cont TokenLaTeX rest
("nocg",rest) -> cont TokenNoCG rest
("eval",rest) -> cont TokenEval rest
("spec",rest) -> cont TokenSpec rest
("freeze",rest) -> cont TokenFreeze rest
("thaw",rest) -> cont TokenThaw rest
("transform",rest) -> cont TokenTransform rest
("include",rest) -> cont TokenCInclude rest
("lib",rest) -> cont TokenCLib rest
-- tactics
-- FIXME: it'd be better to have a 'theorem proving' state so that these
-- don't need the ugly syntax...
("intro",rest) -> cont TokenIntro rest
("refine",rest) -> cont TokenRefine rest
("exists",rest) -> cont TokenExists rest
("generalise",rest) -> cont TokenGeneralise rest
("refl",rest) -> cont TokenReflP rest
("rewrite",rest) -> cont TokenRewrite rest
("rewriteall",rest) -> cont TokenRewriteAll rest
("compute",rest) -> cont TokenCompute rest
("unfold",rest) -> cont TokenUnfold rest
("undo",rest) -> cont TokenUndo rest
("induction",rest) -> cont TokenInduction rest
("fill", rest) -> cont TokenFill rest
("trivial", rest) -> cont TokenTrivial rest
("mktac", rest) -> cont TokenMkTac rest
("believe", rest) -> cont TokenBelieve rest
("use", rest) -> cont TokenUse rest
("decide", rest) -> cont TokenDecide rest
("abandon", rest) -> cont TokenAbandon rest
("prf", rest) -> cont TokenProofTerm rest
("qed", rest) -> cont TokenQED rest
(thing,rest) -> lexError '%' rest
-- Read everything up to '[whitespace]Qed'
{-
lexProof cont cs =
\fn line ->
case getprf cs of
Just (str,rest,nls) -> cont (TokenProof str) rest fn (nls+line)
Nothing -> failP (fn++":"++show line++":No QED in Proof")
cs fn line
-}
lexMeta cont cs =
case span isAllowed cs of
(thing,rest) -> cont (TokenMetavar (UN thing)) rest
mkname :: String -> Token
mkname c = TokenName (mkNS c)
mkNS c = let xs = mkNS' [] [] c in
case xs of
[x] -> UN x
(x:xs) -> NS (map UN (reverse xs)) (UN x)
where
mkNS' acc wds [] = reverse acc:wds
mkNS' acc wds ('.':cs) = mkNS' [] (reverse acc:wds) cs
mkNS' acc wds (c:cs) = mkNS' (c:acc) wds cs
getstr :: String -> Maybe (String,String,Int)
getstr cs = case getstr' "" cs 0 of
Just (str,rest,nls) -> Just (reverse str,rest,nls)
_ -> Nothing
getstr' acc ('\"':xs) = \nl -> Just (acc,xs,nl)
getstr' acc ('\\':'n':xs) = getstr' ('\n':acc) xs -- Newline
getstr' acc ('\\':'r':xs) = getstr' ('\r':acc) xs -- CR
getstr' acc ('\\':'t':xs) = getstr' ('\t':acc) xs -- Tab
getstr' acc ('\\':'b':xs) = getstr' ('\b':acc) xs -- Backspace
getstr' acc ('\\':'a':xs) = getstr' ('\a':acc) xs -- Alert
getstr' acc ('\\':'f':xs) = getstr' ('\f':acc) xs -- Formfeed
getstr' acc ('\\':'0':xs) = getstr' ('\0':acc) xs -- null
getstr' acc ('\\':x:xs) = getstr' (x:acc) xs -- Literal
getstr' acc ('\n':xs) = \nl ->getstr' ('\n':acc) xs (nl+1) -- Count the newline
getstr' acc (x:xs) = getstr' (x:acc) xs
getstr' _ _ = \nl -> Nothing
getchar :: String -> Maybe (Char,String)
getchar ('\\':'n':'\'':xs) = Just ('\n',xs) -- Newline
getchar ('\\':'r':'\'':xs) = Just ('\r',xs) -- CR
getchar ('\\':'t':'\'':xs) = Just ('\t',xs) -- Tab
getchar ('\\':'b':'\'':xs) = Just ('\b',xs) -- Backspace
getchar ('\\':'a':'\'':xs) = Just ('\a',xs) -- Alert
getchar ('\\':'f':'\'':xs) = Just ('\f',xs) -- Formfeed
getchar ('\\':'0':'\'':xs) = Just ('\0',xs) -- null
getchar ('\\':x:'\'':xs) = Just (x,xs) -- Literal
getchar (x:'\'':xs) = Just (x,xs)
getchar _ = Nothing
getprf :: String -> Maybe (String, String, Int)
getprf s = case getprf' "" s 0 of
Just (str,rest,nls) -> Just (reverse str,rest,nls)
_ -> Nothing
getprf' acc (c:'Q':'E':'D':rest)
| isSpace c = \nl -> Just (acc,rest,nl)
getprf' acc ('\n':xs) = \nl ->getprf' ('\n':acc) xs (nl+1) -- Count the newline
getprf' acc (x:xs) = getprf' (x:acc) xs
getprf' acc _ = \nl -> Nothing
|
avsm/Idris
|
Idris/Lexer.hs
|
bsd-3-clause
| 15,030 | 2 | 19 | 4,353 | 5,548 | 2,934 | 2,614 | 385 | 43 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-|
Module : Sig.Sign
Description : Haskell Package Signing Tool: Signing Packages
Copyright : (c) FPComplete.com, 2015
License : BSD3
Maintainer : Tim Dysinger <[email protected]>
Stability : experimental
Portability : POSIX
-}
module Sig.Sign where
import BasePrelude
import Control.Monad.Catch ( MonadThrow )
import Control.Monad.IO.Class ( MonadIO, liftIO )
import Control.Monad.Trans.Control ( MonadBaseControl )
import qualified Data.Text as T ( unpack )
import Data.UUID ( toString )
import Data.UUID.V4 ( nextRandom )
import Distribution.Package
( PackageName(PackageName),
PackageIdentifier(pkgName, pkgVersion) )
import Network.HTTP.Conduit
( Response(responseStatus),
RequestBody(RequestBodyBS),
Request(method, requestBody),
withManager,
httpLbs,
parseUrl )
import Network.HTTP.Types ( status200, methodPut )
import Sig.Cabal
( cabalFetch,
cabalFilePackageId,
packagesFromIndex,
getPackageTarballPath )
import Sig.Doc
import qualified Sig.GPG as GPG
import Sig.Hackage
import Sig.Types
import System.Directory
( getTemporaryDirectory,
getDirectoryContents,
createDirectoryIfMissing )
import System.FilePath ( (</>) )
import System.Process ( readProcessWithExitCode )
sign :: FilePath -> IO ()
sign filePath =
do putHeader "Signing Package"
tempDir <- getTemporaryDirectory
uuid <- nextRandom
let workDir = tempDir </> toString uuid
createDirectoryIfMissing True workDir
(_code,_out,_err) <-
readProcessWithExitCode "tar"
["xf",filePath,"-C",workDir,"--strip","1"]
mempty
cabalFiles <-
(filter (isSuffixOf ".cabal")) <$>
(getDirectoryContents workDir)
if length cabalFiles < 1
then undefined
else do pkg <-
cabalFilePackageId (workDir </> head cabalFiles)
signPackage pkg filePath
putPkgOK pkg
signAll :: forall (m :: * -> *).
(MonadIO m,MonadThrow m,MonadBaseControl IO m)
=> String -> m ()
signAll uname =
do putHeader "Signing Packages"
fromHackage <- packagesForMaintainer uname
fromIndex <- packagesFromIndex
forM_ (filter (\x ->
(pkgName x) `elem`
(map pkgName fromHackage))
fromIndex)
(\pkg ->
liftIO (do cabalFetch ["--no-dependencies"] pkg
filePath <- getPackageTarballPath pkg
signPackage pkg filePath
putPkgOK pkg))
signPackage :: PackageIdentifier -> FilePath -> IO ()
signPackage pkg filePath =
do sig@(Signature signature) <- GPG.sign filePath
let (PackageName name) = pkgName pkg
version = showVersion (pkgVersion pkg)
fingerprint <-
GPG.fingerprintFromVerify sig filePath
req <-
parseUrl ("http://sig-service-elb-vpc-e1757b84-1712462868.us-east-1.elb.amazonaws.com/upload/signature/" <> name <> "/" <>
version <> "/" <>
T.unpack (fingerprintSample fingerprint))
let put =
req {method = methodPut
,requestBody =
RequestBodyBS signature}
res <- withManager (httpLbs put)
if responseStatus res /= status200
then throwIO (GPGSignException "unable to sign & upload package")
else return ()
|
ekmett/sig-tool
|
src/Sig/Sign.hs
|
bsd-3-clause
| 3,682 | 0 | 15 | 1,001 | 824 | 443 | 381 | 96 | 2 |
{-|
Module : IRTS.JavaScript.LangTransforms
Description : The JavaScript LDecl Transformations.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings, StandaloneDeriving #-}
module IRTS.JavaScript.LangTransforms( removeDeadCode
, globlToCon
) where
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import Idris.Core.CaseTree
import Idris.Core.TT
import IRTS.Lang
import Data.Data
import Data.Generics.Uniplate.Data
deriving instance Typeable FDesc
deriving instance Data FDesc
deriving instance Typeable LVar
deriving instance Data LVar
deriving instance Typeable PrimFn
deriving instance Data PrimFn
deriving instance Typeable CaseType
deriving instance Data CaseType
deriving instance Typeable LExp
deriving instance Data LExp
deriving instance Typeable LDecl
deriving instance Data LDecl
deriving instance Typeable LOpt
deriving instance Data LOpt
restrictKeys :: Ord k => Map k a -> Set k -> Map k a
restrictKeys m s = Map.filterWithKey (\k _ -> k `Set.member` s) m
extractGlobs :: Map Name LDecl -> LDecl -> [Name]
extractGlobs defs (LConstructor _ _ _) = []
extractGlobs defs (LFun _ _ _ e) =
let f (LV x) = Just x
f (LLazyApp x _) = Just x
f _ = Nothing
in [x | Just x <- map f $ universe e, Map.member x defs]
usedFunctions :: Map Name LDecl -> Set Name -> [Name] -> [Name]
usedFunctions _ _ [] = []
usedFunctions alldefs done names =
let decls = catMaybes $ map (\x -> Map.lookup x alldefs) names
used_names = (nub $ concat $ map (extractGlobs alldefs) decls) \\ names
new_names = filter (\x -> not $ Set.member x done) used_names
in used_names ++ usedFunctions alldefs (Set.union done $ Set.fromList new_names) new_names
usedDecls :: Map Name LDecl -> [Name] -> Map Name LDecl
usedDecls dcls start =
let used = reverse $ start ++ usedFunctions dcls (Set.fromList start) start
in restrictKeys dcls (Set.fromList used)
getUsedConstructors :: Map Name LDecl -> Set Name
getUsedConstructors x = Set.fromList [ n | LCon _ _ n _ <- universeBi x]
removeUnusedBranches :: Set Name -> Map Name LDecl -> Map Name LDecl
removeUnusedBranches used x =
transformBi f x
where
f :: [LAlt] -> [LAlt]
f ((LConCase x n y z):r) =
if Set.member n used then ((LConCase x n y z):r)
else r
f x = x
removeDeadCode :: Map Name LDecl -> [Name] -> Map Name LDecl
removeDeadCode dcls start =
let used = usedDecls dcls start
remCons = removeUnusedBranches (getUsedConstructors used) used
in if Map.keys remCons == Map.keys dcls then remCons
else removeDeadCode remCons start
globlToCon :: Map Name LDecl -> Map Name LDecl
globlToCon x =
transformBi (f x) x
where
f :: Map Name LDecl -> LExp -> LExp
f y x@(LV n) =
case Map.lookup n y of
Just (LConstructor _ conId arity) -> LCon Nothing conId n []
_ -> x
f y x = x
|
uuhan/Idris-dev
|
src/IRTS/JavaScript/LangTransforms.hs
|
bsd-3-clause
| 3,091 | 0 | 14 | 696 | 1,098 | 557 | 541 | 73 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Evalso.Cruncher.Unsandboxed (version) where
import Evalso.Cruncher.Language (Language, rpm)
import Control.Lens
import qualified Data.Text as T
import qualified Shelly as S
version :: Language -> IO (Maybe T.Text)
version l = S.shelly . S.errExit False . S.silently $ do
versionOut <- S.run "rpm" ["-qv", T.pack (l ^. rpm)]
exitCode <- S.lastExitCode
return $ if exitCode == 0
then Just . T.strip $ versionOut
else Nothing
|
eval-so/cruncher
|
src/Evalso/Cruncher/Unsandboxed.hs
|
bsd-3-clause
| 497 | 0 | 13 | 100 | 165 | 91 | 74 | 13 | 2 |
module Module (constructModule, showNameError) where
import qualified Data.Map as Map
import Data.List
import Debug.Trace
import Tokenizer -- reservedOperators
import Annotation
import Ast
import Span
-- TODO: Add warnings
type PathS = [String]
data Module =
Module { moduleAliases :: Map.Map PathS PathS
, moduleFunctions :: Map.Map PathS UFuncDef
, moduleDatatypes :: Map.Map PathS DataDef
, moduleTypeAliases :: Map.Map PathS AliasDef }
deriving (Show)
data AliasOrData = ADAlias AliasDef | ADData DataDef
data NameError =
FuncAlreadyDefined PathS UFuncDef UFuncDef
| DataAlreadyDefined PathS DataDef DataDef
| AliasAlreadyDefined PathS AliasDef AliasDef
| AliasOverlapsData PathS AliasDef DataDef
| UndefinedIdentifier PathS UExpr UFuncDef
showNameError' what p ori new src =
"Error: " ++ what ++ " '" ++ pn ++ "' has multiple definitions\n"
++ "Occuring at:\n" ++ showSpan new src
++ "\n'" ++ pn ++ "' was originally defined at:\n" ++ showSpan ori src
where
pn = (intercalate "::" p)
showNameError (UndefinedIdentifier p (Fix e) f) src =
"Error: undefined identifier '" ++ (intercalate "::" p)
++ "' in expression:\n" ++ showSpan e src ++ "\nIn function '"
++ (identName $ funcDefName f) ++ "'"
showNameError (FuncAlreadyDefined p ori new) src =
showNameError' "function" p ori new src
showNameError (DataAlreadyDefined p ori new) src =
showNameError' "type" p ori new src
showNameError (AliasAlreadyDefined p ori new) src =
showNameError' "type alias" p ori new src
showNameError (AliasOverlapsData p al da) src =
"Error: type alias '" ++ pn ++ "' overlaps with an already existing type\n"
++ "Occuring at:\n" ++ showSpan al src
++ "\nThe type '" ++ pn ++ "' is defined at:\n" ++ showSpan da src
where
pn = intercalate "::" p
constructModule :: [UConstruct] -> Either [NameError] Module
constructModule constr =
case checkReferences $ checkAliasOverlap
$ embedLetExprs $ buildModule constr of
(mod, []) -> Right mod
(_, errs) -> Left errs
buildModule :: [UConstruct] -> (Module, [NameError])
buildModule constr =
foldl (\(mod, errs) x -> registerConstruct mod errs x)
(initialModule, []) constr
where
initialModule = Module Map.empty Map.empty Map.empty Map.empty
registerConstruct mod@(Module a f d t) errs (Construct (CFuncDef fn) _) =
case Map.lookup funcName f of
Just original -> (mod, (FuncAlreadyDefined funcName original fn):errs)
Nothing -> (Module a (Map.insert funcName fn f) d t, errs)
where
funcName = [ identName $ funcDefName fn ]
registerConstruct mod@(Module a f d t) errs (Construct (CDataDef da) _) =
case Map.lookup dataName d of
Just original -> (mod, (DataAlreadyDefined dataName original da):errs)
Nothing -> (Module a f (Map.insert dataName da d) t, errs)
where
dataName = [ tyIdentName $ dataDefName da ]
registerConstruct mod@(Module a f d t) errs (Construct (CAliasDef al) _) =
case Map.lookup aliasName t of
Just original -> (mod, (AliasAlreadyDefined aliasName original al):errs)
Nothing -> (Module a f d (Map.insert aliasName al t), errs)
where
aliasName = [ tyIdentName $ aliasDefName al ]
embedLetExprs :: (Module, [NameError]) -> (Module, [NameError])
embedLetExprs (mod, errs) =
(embedEachFuncs mod, errs)
where
embedEachFuncs (Module a f d t) =
Module a (Map.map embedFunc f) d t
embedFunc :: UFuncDef -> UFuncDef
embedFunc f@(FuncDef _ _ _ Nothing _) = f
embedFunc (FuncDef n a r (Just expr) s) =
FuncDef n a r (Just $ embedExpr expr) s
embedExpr :: UExpr -> UExpr
embedExpr (Fix (Expression expr sp)) =
Fix $ Expression doIt sp
where
doIt =
case expr of
ECall called args -> ECall (embedExpr called) (map embedExpr args)
n@(ENamed _) -> n
l@(ELiteral _) -> l
f@(EField _) -> f
EGet f e -> EGet f (embedExpr e)
ESet a b -> ESet (embedExpr a) (embedExpr b)
EIf (IfExpr c t e s) ->
EIf $ IfExpr (embedExpr c) (embedExpr t) (embedExpr `fmap` e) s
EReturn a -> EReturn (embedExpr a)
ETuple a -> ETuple $ map embedExpr a
ECase (CaseExpr v c s) ->
ECase $ CaseExpr (embedExpr v)
(map (\(p, e) -> (p, embedExpr e)) c) s
ELet (LetExpr b e s) ->
ELet $ LetExpr (map (\(p, be) ->
(p, (embedExpr be))) b)
(embedExpr `fmap` e) s
ESequence seq -> ESequence $ embedSeq seq
embedSeq :: [UExpr] -> [UExpr]
embedSeq [] = []
embedSeq le@((Fix (Expression (ELet (LetExpr bs Nothing esp)) sp)):[]) = map embedExpr le
embedSeq ((Fix (Expression (ELet (LetExpr bs Nothing esp)) sp)):rst) =
[ embedExpr $ ulet (LetExpr bs (Just $ usequence rst seqSpan) esp) sp ]
where
seqSpan = enclosingSpan (exprSpan $ unfix $ head rst) (exprSpan $ unfix $ last rst)
embedSeq (e:rst) = (embedExpr e):(embedSeq rst)
checkAliasOverlap :: (Module, [NameError]) -> (Module, [NameError])
checkAliasOverlap (mod, errs) =
(mod, Map.foldlWithKey checkOverlap errs (moduleTypeAliases mod))
where
checkOverlap acc aln al =
case Map.lookup aln (moduleDatatypes mod) of
Just ori -> (AliasOverlapsData aln al ori):acc
Nothing -> acc
checkReferences :: (Module, [NameError]) -> (Module, [NameError])
checkReferences (mod, errs) =
checkTypeNameRefs $ checkIdentRefs (mod, errs)
data NameContext =
NameContext [PathS] (Maybe NameContext)
deriving Show
addToContext :: NameContext -> PathS -> NameContext
addToContext (NameContext ns parent) n =
NameContext (n : ns) parent
childContexct :: NameContext -> NameContext -> NameContext
childContexct parent (NameContext ns Nothing) =
NameContext ns $ Just parent
childContexct _ (NameContext _ (Just _)) = error "Context already has child"
parentContext :: NameContext -> NameContext
parentContext (NameContext _ Nothing) = error "Context has no parent"
parentContext (NameContext _ (Just parent)) = parent
memberOfContext :: PathS -> NameContext -> Bool
memberOfContext elm (NameContext nms mparent) =
if elm `elem` nms
then True
else maybe False (memberOfContext elm) mparent
pathToPathS :: Path -> PathS
pathToPathS (IPath (IdentPath (TypePath frags) ident)) =
map (\(tyid, _) -> tyIdentName tyid) frags ++ [(identName ident)]
pathToPathS (CPath (TypePath frags)) =
map (\(tyid, _) -> tyIdentName tyid) frags
extractBindings :: Pattern -> [PathS]
extractBindings (Pattern kind _) =
case kind of
PBind i -> [[identName i]]
PApply _ ps -> fromManyPatterns ps
PTuple ps -> fromManyPatterns ps
_ -> []
where
fromManyPatterns ps = foldl (\acc p -> acc ++ extractBindings p) [] ps
checkIdentRefs :: (Module, [NameError]) -> (Module, [NameError])
checkIdentRefs (mod, es) =
(mod, Map.fold checkFunctionRefs es funcs)
where
initialContext =
Map.fold (\fn ctx -> addToContext ctx [identName (funcDefName fn)])
(NameContext (map (:[]) reservedOperators) Nothing) funcs
funcs = moduleFunctions mod
checkFunctionRefs :: UFuncDef -> [NameError] -> [NameError]
checkFunctionRefs fn errs =
let argumentContext = foldl (\ctx nm -> addToContext ctx [(identName nm)])
(NameContext [] Nothing)
(map fst $ funcDefArgs fn)
functionContext = childContexct initialContext argumentContext
in case (funcDefBody fn) of
Nothing -> errs
Just body -> checkExprRefs body functionContext errs fn
checkExprRefs :: UExpr -> NameContext -> [NameError] -> UFuncDef
-> [NameError]
checkExprRefs (Fix expr) ctx errs fn =
(reverse errsFromCheck) ++ errs
where
errsFromCheck :: [NameError]
errsFromCheck =
case (exprKind expr) of
ECall called args ->
foldl (\aerss aexpr -> checkExprRefs aexpr ctx aerss fn)
(checkExprRefs called ctx [] fn) args
ENamed n ->
if memberOfContext (pathToPathS n) ctx
then []
else [(UndefinedIdentifier (pathToPathS n) (Fix expr) fn)]
EGet _ ge -> checkExprRefs ge ctx [] fn
ESet se ve -> checkExprRefs ve ctx (checkExprRefs se ctx [] fn) fn
EIf (IfExpr ce te ee _) ->
let ifAndThen = checkExprRefs te ctx (checkExprRefs ce ctx [] fn) fn
in maybe ifAndThen (\ex -> (checkExprRefs ex ctx ifAndThen fn)) ee
EReturn re -> checkExprRefs re ctx [] fn
ETuple te -> foldl (\terrs teex -> checkExprRefs teex ctx terrs fn)
[] te
ECase (CaseExpr subj cas _) ->
let subjerss = checkExprRefs subj ctx [] fn
caseContext =
foldl (\cctx (pat, _) ->
foldl (addToContext) cctx $ extractBindings pat)
(NameContext [] $ Just ctx) cas
in foldl (\cerss (_, cexpr) ->
checkExprRefs cexpr caseContext cerss fn)
subjerss cas
ELet (LetExpr binds mexpr _) ->
let letContext =
foldl (\lctx (pat, _) ->
foldl (addToContext) lctx $ extractBindings pat)
(NameContext [] $ Just ctx) binds
binderss =
foldl (\accerss (_, bexpr) ->
checkExprRefs bexpr letContext accerss fn )
[] binds
in case mexpr of
Nothing -> binderss
Just ex -> checkExprRefs ex letContext binderss fn
ESequence ses ->
foldl (\serrs sqex -> checkExprRefs sqex ctx serrs fn) [] ses
_ -> []
checkTypeNameRefs (mod, errs) =
(mod, errs)
|
nulldatamap/bastet
|
src/Module.hs
|
bsd-3-clause
| 10,234 | 2 | 21 | 3,064 | 3,541 | 1,825 | 1,716 | 212 | 16 |
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
-- | Given a file, guess settings from it by looking at the hints.
module Config.Compute(computeSettings) where
import GHC.All
import GHC.Util
import Config.Type
import Fixity
import Data.Generics.Uniplate.DataOnly
import GHC.Hs hiding (Warning)
import GHC.Types.Name.Reader
import GHC.Types.Name
import GHC.Data.Bag
import GHC.Types.SrcLoc
import Language.Haskell.GhclibParserEx.GHC.Hs.ExtendInstances
import Language.Haskell.GhclibParserEx.GHC.Hs.Expr
import Language.Haskell.GhclibParserEx.GHC.Utils.Outputable
import Language.Haskell.GhclibParserEx.GHC.Types.Name.Reader
import Prelude
-- | Given a source file, guess some hints that might apply.
-- Returns the text of the hints (if you want to save it down) along with the settings to be used.
computeSettings :: ParseFlags -> FilePath -> IO (String, [Setting])
computeSettings flags file = do
x <- parseModuleEx flags file Nothing
case x of
Left (ParseError sl msg _) ->
pure ("# Parse error " ++ showSrcSpan sl ++ ": " ++ msg, [])
Right ModuleEx{ghcModule=m} -> do
let xs = concatMap findSetting (hsmodDecls $ unLoc m)
s = unlines $ ["# hints found in " ++ file] ++ concatMap renderSetting xs ++ ["# no hints found" | null xs]
pure (s,xs)
renderSetting :: Setting -> [String]
-- Only need to convert the subset of Setting we generate
renderSetting (SettingMatchExp HintRule{..}) =
["- warn: {lhs: " ++ show (unsafePrettyPrint hintRuleLHS) ++ ", rhs: " ++ show (unsafePrettyPrint hintRuleRHS) ++ "}"]
renderSetting (Infix x) =
["- fixity: " ++ show (unsafePrettyPrint $ toFixitySig x)]
renderSetting _ = []
findSetting :: LocatedA (HsDecl GhcPs) -> [Setting]
findSetting (L _ (ValD _ x)) = findBind x
findSetting (L _ (InstD _ (ClsInstD _ ClsInstDecl{cid_binds}))) =
concatMap (findBind . unLoc) $ bagToList cid_binds
findSetting (L _ (SigD _ (FixSig _ x))) = map Infix $ fromFixitySig x
findSetting x = []
findBind :: HsBind GhcPs -> [Setting]
findBind VarBind{var_id, var_rhs} = findExp var_id [] $ unLoc var_rhs
findBind FunBind{fun_id, fun_matches} = findExp (unLoc fun_id) [] $ HsLam noExtField fun_matches
findBind _ = []
findExp :: IdP GhcPs -> [String] -> HsExpr GhcPs -> [Setting]
findExp name vs (HsLam _ MG{mg_alts=L _ [L _ Match{m_pats, m_grhss=GRHSs{grhssGRHSs=[L _ (GRHS _ [] x)], grhssLocalBinds=(EmptyLocalBinds _)}}]})
= if length m_pats == length ps then findExp name (vs++ps) $ unLoc x else []
where ps = [rdrNameStr x | L _ (VarPat _ x) <- m_pats]
findExp name vs HsLam{} = []
findExp name vs HsVar{} = []
findExp name vs (OpApp _ x dot y) | isDot dot = findExp name (vs++["_hlint"]) $
HsApp EpAnnNotUsed x $ noLocA $ HsPar EpAnnNotUsed $ noLocA $ HsApp EpAnnNotUsed y $ noLocA $ mkVar "_hlint"
findExp name vs bod = [SettingMatchExp $
HintRule Warning defaultHintName []
mempty (extendInstances lhs) (extendInstances $ fromParen rhs) Nothing]
where
lhs = fromParen $ noLocA $ transform f bod
rhs = apps $ map noLocA $ HsVar noExtField (noLocA name) : map snd rep
rep = zip vs $ map (mkVar . pure) ['a'..]
f (HsVar _ x) | Just y <- lookup (rdrNameStr x) rep = y
f (OpApp _ x dol y) | isDol dol = HsApp EpAnnNotUsed x $ noLocA $ HsPar EpAnnNotUsed y
f x = x
mkVar :: String -> HsExpr GhcPs
mkVar = HsVar noExtField . noLocA . Unqual . mkVarOcc
|
ndmitchell/hlint
|
src/Config/Compute.hs
|
bsd-3-clause
| 3,469 | 0 | 24 | 704 | 1,262 | 648 | 614 | 63 | 4 |
{-|
Module : Idris.Elab.Clause
Description : Code to elaborate clauses.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE PatternGuards #-}
module Idris.Elab.Clause where
import Idris.AbsSyntax
import Idris.ASTUtils
import Idris.DSL
import Idris.Error
import Idris.Delaborate
import Idris.Imports
import Idris.Elab.Term
import Idris.Coverage
import Idris.DataOpts
import Idris.Providers
import Idris.Primitives
import Idris.Inliner
import Idris.PartialEval
import Idris.Transforms
import Idris.DeepSeq
import Idris.Output (iputStrLn, pshow, iWarn, iRenderResult, sendHighlighting)
import IRTS.Lang
import Idris.Elab.AsPat
import Idris.Elab.Type
import Idris.Elab.Transform
import Idris.Elab.Utils
import Idris.Core.TT
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.Evaluate
import Idris.Core.Execute
import Idris.Core.Typecheck
import Idris.Core.CaseTree
import Idris.Docstrings hiding (Unchecked)
import Util.Pretty hiding ((<$>))
import Prelude hiding (id, (.))
import Control.Category
import Control.Applicative hiding (Const)
import Control.DeepSeq
import Control.Monad
import Control.Monad.State.Strict as State
import qualified Control.Monad.State.Lazy as LState
import Data.List
import Data.Maybe
import Data.Word
import Debug.Trace
import qualified Data.Map as Map
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Char(isLetter, toLower)
import Data.List.Split (splitOn)
import Util.Pretty(pretty, text)
import Numeric
-- | Elaborate a collection of left-hand and right-hand pairs - that is, a
-- top-level definition.
elabClauses :: ElabInfo -> FC -> FnOpts -> Name -> [PClause] -> Idris ()
elabClauses info' fc opts n_in cs =
do let n = liftname info n_in
info = info' { elabFC = Just fc }
ctxt <- getContext
ist <- getIState
optimise <- getOptimise
let petrans = PETransform `elem` optimise
inacc <- map fst <$> fgetState (opt_inaccessible . ist_optimisation n)
-- Check n actually exists, with no definition yet
let tys = lookupTy n ctxt
let reflect = Reflection `elem` opts
checkUndefined n ctxt
unless (length tys > 1) $ do
fty <- case tys of
[] -> -- TODO: turn into a CAF if there's no arguments
-- question: CAFs in where blocks?
tclift $ tfail $ At fc (NoTypeDecl n)
[ty] -> return ty
let atys_in = map snd (getArgTys (normalise ctxt [] fty))
let atys = map (\x -> (x, isCanonical x ctxt)) atys_in
cs_elab <- mapM (elabClause info opts)
(zip [0..] cs)
ctxt <- getContext
-- pats_raw is the version we'll work with at compile time:
-- no simplification or PE
let (pats_in, cs_full) = unzip cs_elab
let pats_raw = map (simple_lhs ctxt) pats_in
logElab 3 $ "Elaborated patterns:\n" ++ show pats_raw
solveDeferred fc n
-- just ensure that the structure exists
fmodifyState (ist_optimisation n) id
addIBC (IBCOpt n)
ist <- getIState
ctxt <- getContext
-- Don't apply rules if this is a partial evaluation definition,
-- or we'll make something that just runs itself!
let tpats = case specNames opts of
Nothing -> transformPats ist pats_in
_ -> pats_in
-- If the definition is specialisable, this reduces the
-- RHS
pe_tm <- doPartialEval ist tpats
let pats_pe = if petrans
then map (simple_lhs ctxt) pe_tm
else pats_raw
let tcase = opt_typecase (idris_options ist)
-- Look for 'static' names and generate new specialised
-- definitions for them, as well as generating rewrite rules
-- for partially evaluated definitions
newrules <- if petrans
then mapM (\ e -> case e of
Left _ -> return []
Right (l, r) -> elabPE info fc n r) pats_pe
else return []
-- Redo transforms with the newly generated transformations, so
-- that the specialised application we've just made gets
-- used in place of the general one
ist <- getIState
let pats_transformed = if petrans
then transformPats ist pats_pe
else pats_pe
-- Summary of what's about to happen: Definitions go:
--
-- pats_in -> pats -> pdef -> pdef'
-- addCaseDef builds case trees from <pdef> and <pdef'>
-- pdef is the compile-time pattern definition.
-- This will get further inlined to help with totality checking.
let pdef = map (\(ns, lhs, rhs) -> (map fst ns, lhs, rhs)) $ map debind pats_raw
-- pdef_pe is the one which will get further optimised
-- for run-time, and, partially evaluated
let pdef_pe = map debind pats_transformed
logElab 5 $ "Initial typechecked patterns:\n" ++ show pats_raw
logElab 5 $ "Initial typechecked pattern def:\n" ++ show pdef
-- NOTE: Need to store original definition so that proofs which
-- rely on its structure aren't affected by any changes to the
-- inliner. Just use the inlined version to generate pdef' and to
-- help with later inlinings.
ist <- getIState
let pdef_inl = inlineDef ist pdef
numArgs <- tclift $ sameLength pdef
case specNames opts of
Just _ ->
do logElab 3 $ "Partially evaluated:\n" ++ show pats_pe
_ -> return ()
logElab 3 $ "Transformed:\n" ++ show pats_transformed
erInfo <- getErasureInfo <$> getIState
tree@(CaseDef scargs sc _) <- tclift $
simpleCase tcase (UnmatchedCase "Error") reflect CompileTime fc inacc atys pdef erInfo
cov <- coverage
pmissing <-
if cov && not (hasDefault pats_raw)
then do -- Generate clauses from the given possible cases
missing <- genClauses fc n (map getLHS pdef) cs_full
-- missing <- genMissing n scargs sc
missing' <- filterM (checkPossible info fc True n) missing
-- Filter out the ones which match one of the
-- given cases (including impossible ones)
let clhs = map getLHS pdef
logElab 2 $ "Must be unreachable:\n" ++
showSep "\n" (map showTmImpls missing') ++
"\nAgainst: " ++
showSep "\n" (map (\t -> showTmImpls (delab ist t)) (map getLHS pdef))
-- filter out anything in missing' which is
-- matched by any of clhs. This might happen since
-- unification may force a variable to take a
-- particular form, rather than force a case
-- to be impossible.
return (filter (noMatch ist clhs) missing')
else return []
let pcover = null pmissing
-- pdef' is the version that gets compiled for run-time,
-- so we start from the partially evaluated version
pdef_in' <- applyOpts $ map (\(ns, lhs, rhs) -> (map fst ns, lhs, rhs)) pdef_pe
ctxt <- getContext
let pdef' = map (simple_rt ctxt) pdef_in'
logElab 5 $ "After data structure transformations:\n" ++ show pdef'
ist <- getIState
let tot | pcover = Unchecked -- finish later
| AssertTotal `elem` opts = Total []
| PEGenerated `elem` opts = Generated
| otherwise = Partial NotCovering -- already know it's not total
case tree of
CaseDef _ _ [] -> return ()
CaseDef _ _ xs -> mapM_ (\x ->
iputStrLn $ show fc ++
":warning - Unreachable case: " ++
show (delab ist x)) xs
let knowncovering = (pcover && cov) || AssertTotal `elem` opts
let defaultcase = if knowncovering
then STerm Erased
else UnmatchedCase $ "*** " ++
show fc ++
":unmatched case in " ++ show n ++
" ***"
tree' <- tclift $ simpleCase tcase defaultcase reflect
RunTime fc inacc atys pdef' erInfo
logElab 3 $ "Unoptimised " ++ show n ++ ": " ++ show tree
logElab 3 $ "Optimised: " ++ show tree'
ctxt <- getContext
ist <- getIState
let opt = idris_optimisation ist
putIState (ist { idris_patdefs = addDef n (force pdef_pe, force pmissing)
(idris_patdefs ist) })
let caseInfo = CaseInfo (inlinable opts) (inlinable opts) (dictionary opts)
case lookupTyExact n ctxt of
Just ty ->
do ctxt' <- do ctxt <- getContext
tclift $
addCasedef n erInfo caseInfo
tcase defaultcase
reflect
(AssertTotal `elem` opts)
atys
inacc
pats_pe
pdef
pdef -- compile time
pdef_inl -- inlined
pdef' ty
ctxt
setContext ctxt'
addIBC (IBCDef n)
addDefinedName n
setTotality n tot
when (not reflect && PEGenerated `notElem` opts) $
do totcheck (fc, n)
defer_totcheck (fc, n)
when (tot /= Unchecked) $ addIBC (IBCTotal n tot)
i <- getIState
ctxt <- getContext
case lookupDef n ctxt of
(CaseOp _ _ _ _ _ cd : _) ->
let (scargs, sc) = cases_compiletime cd in
do let calls = map fst $ findCalls sc scargs
-- let scg = buildSCG i sc scargs
-- add SCG later, when checking totality
logElab 2 $ "Called names: " ++ show calls
-- if the definition is public, make sure
-- it only uses public names
nvis <- getFromHideList n
case nvis of
Just Public -> mapM_ (checkVisibility fc n Public Public) calls
_ -> return ()
addCalls n calls
addIBC (IBCCG n)
_ -> return ()
return ()
-- addIBC (IBCTotal n tot)
_ -> return ()
-- Check it's covering, if 'covering' option is used. Chase
-- all called functions, and fail if any of them are also
-- 'Partial NotCovering'
when (CoveringFn `elem` opts) $ checkAllCovering fc [] n n
where
noMatch i cs tm = all (\x -> case trim_matchClause i (delab' i x True True) tm of
Right _ -> False
Left miss -> True) cs
where
trim_matchClause i (PApp fcl fl ls) (PApp fcr fr rs)
= let args = min (length ls) (length rs) in
matchClause i (PApp fcl fl (take args ls))
(PApp fcr fr (take args rs))
checkUndefined n ctxt = case lookupDef n ctxt of
[] -> return ()
[TyDecl _ _] -> return ()
_ -> tclift $ tfail (At fc (AlreadyDefined n))
debind (Right (x, y)) = let (vs, x') = depat [] x
(_, y') = depat [] y in
(vs, x', y')
debind (Left x) = let (vs, x') = depat [] x in
(vs, x', Impossible)
depat acc (Bind n (PVar t) sc) = depat ((n, t) : acc) (instantiate (P Bound n t) sc)
depat acc x = (acc, x)
getPVs (Bind x (PVar _) tm) = let (vs, tm') = getPVs tm
in (x:vs, tm')
getPVs tm = ([], tm)
isPatVar vs (P Bound n _) = n `elem` vs
isPatVar _ _ = False
hasDefault cs | (Right (lhs, rhs) : _) <- reverse cs
, (pvs, tm) <- getPVs (explicitNames lhs)
, (f, args) <- unApply tm = all (isPatVar pvs) args
hasDefault _ = False
getLHS (_, l, _) = l
-- Simplify the left hand side of a definition, to remove any lets
-- that may have arisen during elaboration
simple_lhs ctxt (Right (x, y)) = Right (Idris.Core.Evaluate.simplify ctxt [] x, y)
simple_lhs ctxt t = t
simple_rt ctxt (p, x, y) = (p, x, force (uniqueBinders p
(rt_simplify ctxt [] y)))
specNames [] = Nothing
specNames (Specialise ns : _) = Just ns
specNames (_ : xs) = specNames xs
sameLength ((_, x, _) : xs)
= do l <- sameLength xs
let (f, as) = unApply x
if (null xs || l == length as) then return (length as)
else tfail (At fc (Msg "Clauses have differing numbers of arguments "))
sameLength [] = return 0
-- Partially evaluate, if the definition is marked as specialisable
doPartialEval ist pats =
case specNames opts of
Nothing -> return pats
Just ns -> case partial_eval (tt_ctxt ist) ns pats of
Just t -> return t
Nothing -> ierror (At fc (Msg "No specialisation achieved"))
-- | Find 'static' applications in a term and partially evaluate them.
-- Return any new transformation rules
elabPE :: ElabInfo -> FC -> Name -> Term -> Idris [(Term, Term)]
-- Don't go deeper than 5 nested partially evaluated definitions in one go
-- (make this configurable? It's a good limit for most cases, certainly for
-- interfaces and polymorphic definitions, but maybe not for DSLs and
-- interpreters in complicated cases.
-- Possibly only worry about the limit if we've specialised the same function
-- a number of times in one go.)
elabPE info fc caller r | pe_depth info > 5 = return []
elabPE info fc caller r =
do ist <- getIState
let sa = filter (\ap -> fst ap /= caller) $ getSpecApps ist [] r
rules <- mapM mkSpecialised sa
return $ concat rules
where
-- Make a specialised version of the application, and
-- add a PTerm level transformation rule, which is basically the
-- new definition in reverse (before specialising it).
-- RHS => LHS where implicit arguments are left blank in the
-- transformation.
-- Transformation rules are applied after every PClause elaboration
mkSpecialised :: (Name, [(PEArgType, Term)]) -> Idris [(Term, Term)]
mkSpecialised specapp_in = do
ist <- getIState
ctxt <- getContext
let (specTy, specapp) = getSpecTy ist specapp_in
let (n, newnm, specdecl) = getSpecClause ist specapp
let lhs = pe_app specdecl
let rhs = pe_def specdecl
let undef = case lookupDefExact newnm ctxt of
Nothing -> True
_ -> False
logElab 5 $ show (newnm, undef, map (concreteArg ist) (snd specapp))
idrisCatch
(if (undef && all (concreteArg ist) (snd specapp)) then do
cgns <- getAllNames n
-- on the RHS of the new definition, we should reduce
-- everything that's not itself static (because we'll
-- want to be a PE version of those next)
let cgns' = filter (\x -> x /= n &&
notStatic ist x) cgns
-- set small reduction limit on partial/productive things
let maxred = case lookupTotal n ctxt of
[Total _] -> 65536
[Productive] -> 16
_ -> 1
let opts = [Specialise ((if pe_simple specdecl
then map (\x -> (x, Nothing)) cgns'
else []) ++
(n, Just maxred) :
mapMaybe (specName (pe_simple specdecl))
(snd specapp))]
logElab 3 $ "Specialising application: " ++ show specapp
++ " in " ++ show caller ++
" with " ++ show opts
logElab 3 $ "New name: " ++ show newnm
logElab 3 $ "PE definition type : " ++ (show specTy)
++ "\n" ++ show opts
logElab 5 $ "PE definition " ++ show newnm ++ ":\n" ++
showSep "\n"
(map (\ (lhs, rhs) ->
(showTmImpls lhs ++ " = " ++
showTmImpls rhs)) (pe_clauses specdecl))
logElab 2 $ show n ++ " transformation rule: " ++
showTmImpls rhs ++ " ==> " ++ showTmImpls lhs
elabType info defaultSyntax emptyDocstring [] fc opts newnm NoFC specTy
let def = map (\(lhs, rhs) ->
let lhs' = mapPT hiddenToPH $ stripUnmatchable ist lhs in
PClause fc newnm lhs' [] rhs [])
(pe_clauses specdecl)
trans <- elabTransform info fc False rhs lhs
elabClauses (info {pe_depth = pe_depth info + 1}) fc
(PEGenerated:opts) newnm def
return [trans]
else return [])
-- if it doesn't work, just don't specialise. Could happen for lots
-- of valid reasons (e.g. local variables in scope which can't be
-- lifted out).
(\e -> do logElab 3 $ "Couldn't specialise: " ++ (pshow ist e)
return [])
hiddenToPH (PHidden _) = Placeholder
hiddenToPH x = x
specName simpl (ImplicitS, tm)
| (P Ref n _, _) <- unApply tm = Just (n, Just (if simpl then 1 else 0))
specName simpl (ExplicitS, tm)
| (P Ref n _, _) <- unApply tm = Just (n, Just (if simpl then 1 else 0))
specName simpl _ = Nothing
notStatic ist n = case lookupCtxtExact n (idris_statics ist) of
Just s -> not (or s)
_ -> True
concreteArg ist (ImplicitS, tm) = concreteTm ist tm
concreteArg ist (ExplicitS, tm) = concreteTm ist tm
concreteArg ist _ = True
concreteTm ist tm | (P _ n _, _) <- unApply tm =
case lookupTy n (tt_ctxt ist) of
[] -> False
_ -> True
concreteTm ist (Constant _) = True
concreteTm ist (Bind n (Lam _) sc) = True
concreteTm ist (Bind n (Pi _ _ _) sc) = True
concreteTm ist (Bind n (Let _ _) sc) = concreteTm ist sc
concreteTm ist _ = False
-- get the type of a specialised application
getSpecTy ist (n, args)
= case lookupTy n (tt_ctxt ist) of
[ty] -> let (specty_in, args') = specType args (explicitNames ty)
specty = normalise (tt_ctxt ist) [] (finalise specty_in)
t = mkPE_TyDecl ist args' (explicitNames specty) in
(t, (n, args'))
-- (normalise (tt_ctxt ist) [] (specType args ty))
_ -> error "Can't happen (getSpecTy)"
-- get the clause of a specialised application
getSpecClause ist (n, args)
= let newnm = sUN ("PE_" ++ show (nsroot n) ++ "_" ++
qhash 5381 (showSep "_" (map showArg args))) in
-- UN (show n ++ show (map snd args)) in
(n, newnm, mkPE_TermDecl ist newnm n args)
where showArg (ExplicitS, n) = qshow n
showArg (ImplicitS, n) = qshow n
showArg _ = ""
qshow (Bind _ _ _) = "fn"
qshow (App _ f a) = qshow f ++ qshow a
qshow (P _ n _) = show n
qshow (Constant c) = show c
qshow _ = ""
-- Simple but effective string hashing...
-- Keep it to 32 bits for readability/debuggability
qhash :: Word64 -> String -> String
qhash hash [] = showHex (abs hash `mod` 0xffffffff) ""
qhash hash (x:xs) = qhash (hash * 33 + fromIntegral(fromEnum x)) xs
-- | Checks if the clause is a possible left hand side.
checkPossible :: ElabInfo -> FC -> Bool -> Name -> PTerm -> Idris Bool
checkPossible info fc tcgen fname lhs_in
= do ctxt <- getContext
i <- getIState
let lhs = addImplPat i lhs_in
-- if the LHS type checks, it is possible
case elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "patLHS") infP initEState
(erun fc (buildTC i info ELHS [] fname
(allNamesIn lhs_in)
(infTerm lhs))) of
OK (ElabResult lhs' _ _ ctxt' newDecls highlights newGName, _) ->
do setContext ctxt'
processTacticDecls info newDecls
sendHighlighting highlights
updateIState $ \i -> i { idris_name = newGName }
let lhs_tm = orderPats (getInferTerm lhs')
case recheck (constraintNS info) ctxt' [] (forget lhs_tm) lhs_tm of
OK _ -> return True
err -> return False
-- if it's a recoverable error, the case may become possible
Error err -> if tcgen then return (recoverableCoverage ctxt err)
else return (validCoverageCase ctxt err ||
recoverableCoverage ctxt err)
findUnique :: Context -> Env -> Term -> [Name]
findUnique ctxt env (Bind n b sc)
= let rawTy = forgetEnv (map fst env) (binderTy b)
uniq = case check ctxt env rawTy of
OK (_, UType UniqueType) -> True
OK (_, UType NullType) -> True
OK (_, UType AllTypes) -> True
_ -> False in
if uniq then n : findUnique ctxt ((n, b) : env) sc
else findUnique ctxt ((n, b) : env) sc
findUnique _ _ _ = []
-- | Return the elaborated LHS/RHS, and the original LHS with implicits added
elabClause :: ElabInfo -> FnOpts -> (Int, PClause) ->
Idris (Either Term (Term, Term), PTerm)
elabClause info opts (_, PClause fc fname lhs_in [] PImpossible [])
= do let tcgen = Dictionary `elem` opts
i <- get
let lhs = addImpl [] i lhs_in
b <- checkPossible info fc tcgen fname lhs_in
case b of
True -> tclift $ tfail (At fc
(Msg $ show lhs_in ++ " is a valid case"))
False -> do ptm <- mkPatTm lhs_in
logElab 5 $ "Elaborated impossible case " ++ showTmImpls lhs ++
"\n" ++ show ptm
return (Left ptm, lhs)
elabClause info opts (cnum, PClause fc fname lhs_in_as withs rhs_in_as whereblock)
= do let tcgen = Dictionary `elem` opts
push_estack fname False
ctxt <- getContext
let (lhs_in, rhs_in) = desugarAs lhs_in_as rhs_in_as
-- Build the LHS as an "Infer", and pull out its type and
-- pattern bindings
i <- getIState
inf <- isTyInferred fname
-- Check if we have "with" patterns outside of "with" block
when (isOutsideWith lhs_in && (not $ null withs)) $
ierror (At fc (Elaborating "left hand side of " fname Nothing
(Msg "unexpected patterns outside of \"with\" block")))
-- get the parameters first, to pass through to any where block
let fn_ty = case lookupTy fname ctxt of
[t] -> t
_ -> error "Can't happen (elabClause function type)"
let fn_is = case lookupCtxt fname (idris_implicits i) of
[t] -> t
_ -> []
let norm_ty = normalise ctxt [] fn_ty
let params = getParamsInType i [] fn_is norm_ty
let tcparams = getTCParamsInType i [] fn_is norm_ty
let lhs = mkLHSapp $ stripLinear i $ stripUnmatchable i $
propagateParams i params norm_ty (allNamesIn lhs_in) (addImplPat i lhs_in)
-- let lhs = mkLHSapp $
-- propagateParams i params fn_ty (addImplPat i lhs_in)
logElab 10 (show (params, fn_ty) ++ " " ++ showTmImpls (addImplPat i lhs_in))
logElab 5 ("LHS: " ++ show opts ++ "\n" ++ show fc ++ " " ++ showTmImpls lhs)
logElab 4 ("Fixed parameters: " ++ show params ++ " from " ++ showTmImpls lhs_in ++
"\n" ++ show (fn_ty, fn_is))
((ElabResult lhs' dlhs [] ctxt' newDecls highlights newGName, probs, inj), _) <-
tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "patLHS") infP initEState
(do res <- errAt "left hand side of " fname Nothing
(erun fc (buildTC i info ELHS opts fname
(allNamesIn lhs_in)
(infTerm lhs)))
probs <- get_probs
inj <- get_inj
return (res, probs, inj))
setContext ctxt'
processTacticDecls info newDecls
sendHighlighting highlights
updateIState $ \i -> i { idris_name = newGName }
when inf $ addTyInfConstraints fc (map (\(x,y,_,_,_,_,_) -> (x,y)) probs)
let lhs_tm = orderPats (getInferTerm lhs')
let lhs_ty = getInferType lhs'
let static_names = getStaticNames i lhs_tm
logElab 3 ("Elaborated: " ++ show lhs_tm)
logElab 3 ("Elaborated type: " ++ show lhs_ty)
logElab 5 ("Injective: " ++ show fname ++ " " ++ show inj)
-- If we're inferring metavariables in the type, don't recheck,
-- because we're only doing this to try to work out those metavariables
ctxt <- getContext
(clhs_c, clhsty) <- if not inf
then recheckC_borrowing False (PEGenerated `notElem` opts)
[] (constraintNS info) fc id [] lhs_tm
else return (lhs_tm, lhs_ty)
let clhs = Idris.Core.Evaluate.simplify ctxt [] clhs_c
let borrowed = borrowedNames [] clhs
-- These are the names we're not allowed to use on the RHS, because
-- they're UniqueTypes and borrowed from another function.
-- FIXME: There is surely a nicer way than this...
-- Issue #1615 on the Issue Tracker.
-- https://github.com/idris-lang/Idris-dev/issues/1615
when (not (null borrowed)) $
logElab 5 ("Borrowed names on LHS: " ++ show borrowed)
logElab 3 ("Normalised LHS: " ++ showTmImpls (delabMV i clhs))
rep <- useREPL
when rep $ do
addInternalApp (fc_fname fc) (fst . fc_start $ fc) (delabMV i clhs) -- TODO: Should use span instead of line and filename?
addIBC (IBCLineApp (fc_fname fc) (fst . fc_start $ fc) (delabMV i clhs))
logElab 5 ("Checked " ++ show clhs ++ "\n" ++ show clhsty)
-- Elaborate where block
ist <- getIState
ctxt <- getContext
windex <- getName
let decls = nub (concatMap declared whereblock)
let defs = nub (decls ++ concatMap defined whereblock)
let newargs_all = pvars ist lhs_tm
-- Unique arguments must be passed to the where block explicitly
-- (since we can't control "usage" easlily otherwise). Remove them
-- from newargs here
let uniqargs = findUnique ctxt [] lhs_tm
let newargs = filter (\(n,_) -> n `notElem` uniqargs) newargs_all
let winfo = (pinfo info newargs defs windex) { elabFC = Just fc }
let wb = map (mkStatic static_names) $
map (expandInstanceScope ist decorate newargs defs) $
map (expandParamsD False ist decorate newargs defs) whereblock
-- Split the where block into declarations with a type, and those
-- without
-- Elaborate those with a type *before* RHS, those without *after*
let (wbefore, wafter) = sepBlocks wb
logElab 5 $ "Where block:\n " ++ show wbefore ++ "\n" ++ show wafter
mapM_ (rec_elabDecl info EAll winfo) wbefore
-- Now build the RHS, using the type of the LHS as the goal.
i <- getIState -- new implicits from where block
logElab 5 (showTmImpls (expandParams decorate newargs defs (defs \\ decls) rhs_in))
let rhs = rhs_trans info $
addImplBoundInf i (map fst newargs_all) (defs \\ decls)
(expandParams decorate newargs defs (defs \\ decls) rhs_in)
logElab 2 $ "RHS: " ++ show (map fst newargs_all) ++ " " ++ showTmImpls rhs
ctxt <- getContext -- new context with where block added
logElab 5 "STARTING CHECK"
((rhs', defer, holes, is, probs, ctxt', newDecls, highlights, newGName), _) <-
tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "patRHS") clhsty initEState
(do pbinds ist lhs_tm
-- proof search can use explicitly written names
mapM_ addPSname (allNamesIn lhs_in)
ulog <- getUnifyLog
traceWhen ulog ("Setting injective: " ++ show (nub (tcparams ++ inj))) $
mapM_ setinj (nub (tcparams ++ inj))
setNextName
(ElabResult _ _ is ctxt' newDecls highlights newGName) <-
errAt "right hand side of " fname (Just clhsty)
(erun fc (build i winfo ERHS opts fname rhs))
errAt "right hand side of " fname (Just clhsty)
(erun fc $ psolve lhs_tm)
tt <- get_term
aux <- getAux
let (tm, ds) = runState (collectDeferred (Just fname)
(map fst $ case_decls aux) ctxt tt) []
probs <- get_probs
hs <- get_holes
return (tm, ds, hs, is, probs, ctxt', newDecls, highlights, newGName))
setContext ctxt'
processTacticDecls info newDecls
sendHighlighting highlights
updateIState $ \i -> i { idris_name = newGName }
when inf $ addTyInfConstraints fc (map (\(x,y,_,_,_,_,_) -> (x,y)) probs)
logElab 5 "DONE CHECK"
logElab 4 $ "---> " ++ show rhs'
when (not (null defer)) $ logElab 1 $ "DEFERRED " ++
show (map (\ (n, (_,_,t,_)) -> (n, t)) defer)
-- If there's holes, set the metavariables as undefinable
def' <- checkDef info fc (\n -> Elaborating "deferred type of " n Nothing) (null holes) defer
let def'' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, False, null holes))) def'
addDeferred def''
mapM_ (\(n, _) -> addIBC (IBCDef n)) def''
when (not (null def')) $ do
mapM_ defer_totcheck (map (\x -> (fc, fst x)) def'')
-- Now the remaining deferred (i.e. no type declarations) clauses
-- from the where block
mapM_ (rec_elabDecl info EAll winfo) wafter
mapM_ (elabCaseBlock winfo opts) is
ctxt <- getContext
logElab 5 "Rechecking"
logElab 6 $ " ==> " ++ show (forget rhs')
(crhs, crhsty) -- if there's holes && deferred things, it's okay
-- but we'll need to freeze the definition and not
-- allow the deferred things to be definable
-- (this is just to allow users to inspect intermediate
-- things)
<- if (null holes || null def') && not inf
then recheckC_borrowing True (PEGenerated `notElem` opts)
borrowed (constraintNS info) fc id [] rhs'
else return (rhs', clhsty)
logElab 6 $ " ==> " ++ showEnvDbg [] crhsty ++ " against " ++ showEnvDbg [] clhsty
-- If there's holes, make sure this definition is frozen
when (not (null holes)) $ do
logElab 5 $ "Making " ++ show fname ++ " frozen due to " ++ show holes
setAccessibility fname Frozen
ctxt <- getContext
let constv = next_tvar ctxt
tit <- typeInType
case LState.runStateT (convertsC ctxt [] crhsty clhsty) (constv, []) of
OK (_, cs) -> when (PEGenerated `notElem` opts && not tit) $ do
addConstraints fc cs
mapM_ (\c -> addIBC (IBCConstraint fc c)) (snd cs)
logElab 6 $ "CONSTRAINTS ADDED: " ++ show cs ++ "\n" ++ show (clhsty, crhsty)
return ()
Error e -> ierror (At fc (CantUnify False (clhsty, Nothing) (crhsty, Nothing) e [] 0))
i <- getIState
checkInferred fc (delab' i crhs True True) rhs
-- if the function is declared '%error_reverse', or its type,
-- then we'll try running it in reverse to improve error messages
let (ret_fam, _) = unApply (getRetTy crhsty)
rev <- case ret_fam of
P _ rfamn _ ->
case lookupCtxt rfamn (idris_datatypes i) of
[TI _ _ dopts _ _] ->
return (DataErrRev `elem` dopts)
_ -> return False
_ -> return False
when (rev || ErrorReverse `elem` opts) $ do
addIBC (IBCErrRev (crhs, clhs))
addErrRev (crhs, clhs)
pop_estack
return (Right (clhs, crhs), lhs)
where
pinfo :: ElabInfo -> [(Name, PTerm)] -> [Name] -> Int -> ElabInfo
pinfo info ns ds i
= let newps = params info ++ ns
dsParams = map (\n -> (n, map fst newps)) ds
newb = addAlist dsParams (inblock info)
l = liftname info in
info { params = newps,
inblock = newb,
liftname = id -- (\n -> case lookupCtxt n newb of
-- Nothing -> n
-- _ -> MN i (show n)) . l
}
-- Find the variable names which appear under a 'Ownership.Read' so that
-- we know they can't be used on the RHS
borrowedNames :: [Name] -> Term -> [Name]
borrowedNames env (App _ (App _ (P _ (NS (UN lend) [owner]) _) _) arg)
| owner == txt "Ownership" &&
(lend == txt "lend" || lend == txt "Read") = getVs arg
where
getVs (V i) = [env!!i]
getVs (App _ f a) = nub $ getVs f ++ getVs a
getVs _ = []
borrowedNames env (App _ f a) = nub $ borrowedNames env f ++ borrowedNames env a
borrowedNames env (Bind n b sc) = nub $ borrowedB b ++ borrowedNames (n:env) sc
where borrowedB (Let t v) = nub $ borrowedNames env t ++ borrowedNames env v
borrowedB b = borrowedNames env (binderTy b)
borrowedNames _ _ = []
mkLHSapp t@(PRef _ _ _) = PApp fc t []
mkLHSapp t = t
decorate (NS x ns)
= NS (SN (WhereN cnum fname x)) ns
decorate x
= SN (WhereN cnum fname x)
sepBlocks bs = sepBlocks' [] bs where
sepBlocks' ns (d@(PTy _ _ _ _ _ n _ t) : bs)
= let (bf, af) = sepBlocks' (n : ns) bs in
(d : bf, af)
sepBlocks' ns (d@(PClauses _ _ n _) : bs)
| not (n `elem` ns) = let (bf, af) = sepBlocks' ns bs in
(bf, d : af)
sepBlocks' ns (b : bs) = let (bf, af) = sepBlocks' ns bs in
(b : bf, af)
sepBlocks' ns [] = ([], [])
-- term is not within "with" block
isOutsideWith :: PTerm -> Bool
isOutsideWith (PApp _ (PRef _ _ (SN (WithN _ _))) _) = False
isOutsideWith _ = True
elabClause info opts (_, PWith fc fname lhs_in withs wval_in pn_in withblock)
= do let tcgen = Dictionary `elem` opts
ctxt <- getContext
-- Build the LHS as an "Infer", and pull out its type and
-- pattern bindings
i <- getIState
-- get the parameters first, to pass through to any where block
let fn_ty = case lookupTy fname ctxt of
[t] -> t
_ -> error "Can't happen (elabClause function type)"
let fn_is = case lookupCtxt fname (idris_implicits i) of
[t] -> t
_ -> []
let params = getParamsInType i [] fn_is (normalise ctxt [] fn_ty)
let lhs = stripLinear i $ stripUnmatchable i $
propagateParams i params fn_ty (allNamesIn lhs_in)
(addImplPat i lhs_in)
logElab 2 ("LHS: " ++ show lhs)
(ElabResult lhs' dlhs [] ctxt' newDecls highlights newGName, _) <-
tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "patLHS") infP initEState
(errAt "left hand side of with in " fname Nothing
(erun fc (buildTC i info ELHS opts fname
(allNamesIn lhs_in)
(infTerm lhs))) )
setContext ctxt'
processTacticDecls info newDecls
sendHighlighting highlights
updateIState $ \i -> i { idris_name = newGName }
ctxt <- getContext
let lhs_tm = orderPats (getInferTerm lhs')
let lhs_ty = getInferType lhs'
let ret_ty = getRetTy (explicitNames (normalise ctxt [] lhs_ty))
let static_names = getStaticNames i lhs_tm
logElab 5 (show lhs_tm ++ "\n" ++ show static_names)
(clhs, clhsty) <- recheckC (constraintNS info) fc id [] lhs_tm
logElab 5 ("Checked " ++ show clhs)
let bargs = getPBtys (explicitNames (normalise ctxt [] lhs_tm))
let wval = rhs_trans info $ addImplBound i (map fst bargs) wval_in
logElab 5 ("Checking " ++ showTmImpls wval)
-- Elaborate wval in this context
((wval', defer, is, ctxt', newDecls, highlights, newGName), _) <-
tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "withRHS")
(bindTyArgs PVTy bargs infP) initEState
(do pbinds i lhs_tm
-- proof search can use explicitly written names
mapM_ addPSname (allNamesIn lhs_in)
setNextName
-- TODO: may want where here - see winfo abpve
(ElabResult _ d is ctxt' newDecls highlights newGName) <- errAt "with value in " fname Nothing
(erun fc (build i info ERHS opts fname (infTerm wval)))
erun fc $ psolve lhs_tm
tt <- get_term
return (tt, d, is, ctxt', newDecls, highlights, newGName))
setContext ctxt'
processTacticDecls info newDecls
sendHighlighting highlights
updateIState $ \i -> i { idris_name = newGName }
def' <- checkDef info fc iderr True defer
let def'' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, False, True))) def'
addDeferred def''
mapM_ (elabCaseBlock info opts) is
logElab 5 ("Checked wval " ++ show wval')
ctxt <- getContext
(cwval, cwvalty) <- recheckC (constraintNS info) fc id [] (getInferTerm wval')
let cwvaltyN = explicitNames (normalise ctxt [] cwvalty)
let cwvalN = explicitNames (normalise ctxt [] cwval)
logElab 3 ("With type " ++ show cwvalty ++ "\nRet type " ++ show ret_ty)
-- We're going to assume the with type is not a function shortly,
-- so report an error if it is (you can't match on a function anyway
-- so this doesn't lose anything)
case getArgTys cwvaltyN of
[] -> return ()
(_:_) -> ierror $ At fc (WithFnType cwvalty)
let pvars = map fst (getPBtys cwvalty)
-- we need the unelaborated term to get the names it depends on
-- rather than a de Bruijn index.
let pdeps = usedNamesIn pvars i (delab i cwvalty)
let (bargs_pre, bargs_post) = split pdeps bargs []
let mpn = case pn_in of
Nothing -> Nothing
Just (n, nfc) -> Just (uniqueName n (map fst bargs))
-- Highlight explicit proofs
sendHighlighting [(fc, AnnBoundName n False) | (n, fc) <- maybeToList pn_in]
logElab 10 ("With type " ++ show (getRetTy cwvaltyN) ++
" depends on " ++ show pdeps ++ " from " ++ show pvars)
logElab 10 ("Pre " ++ show bargs_pre ++ "\nPost " ++ show bargs_post)
windex <- getName
-- build a type declaration for the new function:
-- (ps : Xs) -> (withval : cwvalty) -> (ps' : Xs') -> ret_ty
let wargval = getRetTy cwvalN
let wargtype = getRetTy cwvaltyN
let wargname = sMN windex "warg"
logElab 5 ("Abstract over " ++ show wargval ++ " in " ++ show wargtype)
let wtype = bindTyArgs (flip (Pi Nothing) (TType (UVar [] 0))) (bargs_pre ++
(wargname, wargtype) :
map (abstract wargname wargval wargtype) bargs_post ++
case mpn of
Just pn -> [(pn, mkApp (P Ref eqTy Erased)
[wargtype, wargtype,
P Bound wargname Erased, wargval])]
Nothing -> [])
(substTerm wargval (P Bound wargname wargtype) ret_ty)
logElab 3 ("New function type " ++ show wtype)
let wname = SN (WithN windex fname)
let imps = getImps wtype -- add to implicits context
putIState (i { idris_implicits = addDef wname imps (idris_implicits i) })
let statics = getStatics static_names wtype
logElab 5 ("Static positions " ++ show statics)
i <- getIState
putIState (i { idris_statics = addDef wname statics (idris_statics i) })
addIBC (IBCDef wname)
addIBC (IBCImp wname)
addIBC (IBCStatic wname)
def' <- checkDef info fc iderr True [(wname, (-1, Nothing, wtype, []))]
let def'' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, False, True))) def'
addDeferred def''
-- in the subdecls, lhs becomes:
-- fname pats | wpat [rest]
-- ==> fname' ps wpat [rest], match pats against toplevel for ps
wb <- mapM (mkAuxC mpn wname lhs (map fst bargs_pre) (map fst bargs_post))
withblock
logElab 3 ("with block " ++ show wb)
-- propagate totality assertion to the new definitions
setFlags wname [Inlinable]
when (AssertTotal `elem` opts) $ setFlags wname [Inlinable, AssertTotal]
i <- getIState
let rhstrans' = updateWithTerm i mpn wname lhs (map fst bargs_pre) (map fst (bargs_post))
. rhs_trans info
mapM_ (rec_elabDecl info EAll (info { rhs_trans = rhstrans' })) wb
-- rhs becomes: fname' ps_pre wval ps_post Refl
let rhs = PApp fc (PRef fc [] wname)
(map (pexp . (PRef fc []) . fst) bargs_pre ++
pexp wval :
(map (pexp . (PRef fc []) . fst) bargs_post) ++
case mpn of
Nothing -> []
Just _ -> [pexp (PApp NoFC (PRef NoFC [] eqCon)
[ pimp (sUN "A") Placeholder False
, pimp (sUN "x") Placeholder False
])])
logElab 5 ("New RHS " ++ showTmImpls rhs)
ctxt <- getContext -- New context with block added
i <- getIState
((rhs', defer, is, ctxt', newDecls, highlights, newGName), _) <-
tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "wpatRHS") clhsty initEState
(do pbinds i lhs_tm
setNextName
(ElabResult _ d is ctxt' newDecls highlights newGName) <-
erun fc (build i info ERHS opts fname rhs)
psolve lhs_tm
tt <- get_term
return (tt, d, is, ctxt', newDecls, highlights, newGName))
setContext ctxt'
processTacticDecls info newDecls
sendHighlighting highlights
updateIState $ \i -> i { idris_name = newGName }
def' <- checkDef info fc iderr True defer
let def'' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, False, True))) def'
addDeferred def''
mapM_ (elabCaseBlock info opts) is
logElab 5 ("Checked RHS " ++ show rhs')
(crhs, crhsty) <- recheckC (constraintNS info) fc id [] rhs'
return (Right (clhs, crhs), lhs)
where
getImps (Bind n (Pi _ _ _) t) = pexp Placeholder : getImps t
getImps _ = []
mkAuxC pn wname lhs ns ns' (PClauses fc o n cs)
= do cs' <- mapM (mkAux pn wname lhs ns ns') cs
return $ PClauses fc o wname cs'
mkAuxC pn wname lhs ns ns' d = return d
mkAux pn wname toplhs ns ns' (PClause fc n tm_in (w:ws) rhs wheres)
= do i <- getIState
let tm = addImplPat i tm_in
logElab 2 ("Matching " ++ showTmImpls tm ++ " against " ++
showTmImpls toplhs)
case matchClause i toplhs tm of
Left (a,b) -> ifail $ show fc ++ ":with clause does not match top level"
Right mvars ->
do logElab 3 ("Match vars : " ++ show mvars)
lhs <- updateLHS n pn wname mvars ns ns' (fullApp tm) w
return $ PClause fc wname lhs ws rhs wheres
mkAux pn wname toplhs ns ns' (PWith fc n tm_in (w:ws) wval pn' withs)
= do i <- getIState
let tm = addImplPat i tm_in
logElab 2 ("Matching " ++ showTmImpls tm ++ " against " ++
showTmImpls toplhs)
withs' <- mapM (mkAuxC pn wname toplhs ns ns') withs
case matchClause i toplhs tm of
Left (a,b) -> trace ("matchClause: " ++ show a ++ " =/= " ++ show b) (ifail $ show fc ++ "with clause does not match top level")
Right mvars ->
do lhs <- updateLHS n pn wname mvars ns ns' (fullApp tm) w
return $ PWith fc wname lhs ws wval pn' withs'
mkAux pn wname toplhs ns ns' c
= ifail $ show fc ++ ":badly formed with clause"
addArg (PApp fc f args) w = PApp fc f (args ++ [pexp w])
addArg (PRef fc hls f) w = PApp fc (PRef fc hls f) [pexp w]
-- ns, arguments which don't depend on the with argument
-- ns', arguments which do
updateLHS n pn wname mvars ns_in ns_in' (PApp fc (PRef fc' hls' n') args) w
= let ns = map (keepMvar (map fst mvars) fc') ns_in
ns' = map (keepMvar (map fst mvars) fc') ns_in' in
return $ substMatches mvars $
PApp fc (PRef fc' [] wname)
(map pexp ns ++ pexp w : (map pexp ns') ++
case pn of
Nothing -> []
Just pnm -> [pexp (PRef fc [] pnm)])
updateLHS n pn wname mvars ns_in ns_in' tm w
= updateLHS n pn wname mvars ns_in ns_in' (PApp fc tm []) w
-- Only keep a var as a pattern variable in the with block if it's
-- matched in the top level pattern
keepMvar mvs fc v | v `elem` mvs = PRef fc [] v
| otherwise = Placeholder
updateWithTerm :: IState -> Maybe Name -> Name -> PTerm -> [Name] -> [Name] -> PTerm -> PTerm
updateWithTerm ist pn wname toplhs ns_in ns_in' tm
= mapPT updateApp tm
where
arity (PApp _ _ as) = length as
arity _ = 0
lhs_arity = arity toplhs
currentFn fname (PAlternative _ _ as)
| Just tm <- getApp as = tm
where getApp (tm@(PApp _ (PRef _ _ f) _) : as)
| f == fname = Just tm
getApp (_ : as) = getApp as
getApp [] = Nothing
currentFn _ tm = tm
updateApp wtm@(PWithApp fcw tm_in warg) =
let tm = currentFn fname tm_in in
case matchClause ist toplhs tm of
Left _ -> PElabError (Msg (show fc ++ ":with application does not match top level "))
Right mvars ->
let ns = map (keepMvar (map fst mvars) fcw) ns_in
ns' = map (keepMvar (map fst mvars) fcw) ns_in'
wty = lookupTyExact wname (tt_ctxt ist)
res = substMatches mvars $
PApp fcw (PRef fcw [] wname)
(map pexp ns ++ pexp warg : (map pexp ns') ++
case pn of
Nothing -> []
Just pnm -> [pexp (PRef fc [] pnm)]) in
case wty of
Nothing -> res -- can't happen!
Just ty -> addResolves ty res
updateApp tm = tm
addResolves ty (PApp fc f args) = PApp fc f (addResolvesArgs fc ty args)
addResolves ty tm = tm
-- if an argument's type is a type class, and is otherwise to
-- be inferred, then resolve it with instance search
-- This is something of a hack, because matching on the top level
-- application won't find this information for us
addResolvesArgs :: FC -> Term -> [PArg] -> [PArg]
addResolvesArgs fc (Bind n (Pi _ ty _) sc) (a : args)
| (P _ cn _, _) <- unApply ty,
getTm a == Placeholder
= case lookupCtxtExact cn (idris_classes ist) of
Just _ -> a { getTm = PResolveTC fc } : addResolvesArgs fc sc args
Nothing -> a : addResolvesArgs fc sc args
addResolvesArgs fc (Bind n (Pi _ ty _) sc) (a : args)
= a : addResolvesArgs fc sc args
addResolvesArgs fc _ args = args
fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs))
fullApp x = x
split [] rest pre = (reverse pre, rest)
split deps ((n, ty) : rest) pre
| n `elem` deps = split (deps \\ [n]) rest ((n, ty) : pre)
| otherwise = split deps rest ((n, ty) : pre)
split deps [] pre = (reverse pre, [])
abstract wn wv wty (n, argty) = (n, substTerm wv (P Bound wn wty) argty)
-- | Apply a transformation to all RHSes and nested RHSs
mapRHS :: (PTerm -> PTerm) -> PClause -> PClause
mapRHS f (PClause fc n lhs args rhs ws)
= PClause fc n lhs args (f rhs) (map (mapRHSdecl f) ws)
mapRHS f (PWith fc n lhs args warg prf ws)
= PWith fc n lhs args (f warg) prf (map (mapRHSdecl f) ws)
mapRHS f (PClauseR fc args rhs ws)
= PClauseR fc args (f rhs) (map (mapRHSdecl f) ws)
mapRHS f (PWithR fc args warg prf ws)
= PWithR fc args (f warg) prf (map (mapRHSdecl f) ws)
mapRHSdecl :: (PTerm -> PTerm) -> PDecl -> PDecl
mapRHSdecl f (PClauses fc opt n cs)
= PClauses fc opt n (map (mapRHS f) cs)
mapRHSdecl f t = t
|
ozgurakgun/Idris-dev
|
src/Idris/Elab/Clause.hs
|
bsd-3-clause
| 53,914 | 9 | 28 | 21,427 | 15,346 | 7,619 | 7,727 | 843 | 51 |
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
import Distribution.Simple
import Distribution.Simple.Program.Builtin
import Distribution.Simple.Program.Types
import Distribution.Simple.Program
import Distribution.PackageDescription
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Setup
--main = defaultMain
main :: IO ()
#if x86_64_HOST_ARCH
main =
do
--putStrLn "Please have a recent clang or gcc installed or the build will fail"
defaultMainWithHooks myhook
#else
main = error "only x86_64 architectures are currently supported"
#endif
{-
this is to work around mac having a really old GCC version and AS (assembler)
can't use nice simd with the apple gcc, have to make GHC use Clang instead
darwin = OSX
-}
#if darwin_HOST_OS
myhook = set lensBuildHook2UserHooks myBuildHook simpleUserHooks
where
oldbuildhook = get lensBuildHook2UserHooks simpleUserHooks
myBuildHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> BuildFlags -> IO ()
myBuildHook packDesc locBuildInfo =
oldbuildhook packDesc (set lensProgramConfig2LocBuildInfo newProgramConfig locBuildInfo)
where !(Just !oldGhcConf) =lookupProgram ghcProgram oldProgramConfig
oldProgramConfig = get lensProgramConfig2LocBuildInfo locBuildInfo
oldOverrideArgs = get lensProgramOverrideArgs2ConfiguredProgram oldGhcConf
newOverrideArgs = oldOverrideArgs++["-pgma clang", "-pgmc clang"]
newGhcConf = set lensProgramOverrideArgs2ConfiguredProgram newOverrideArgs oldGhcConf
newProgramConfig = updateProgram newGhcConf oldProgramConfig
#else
myhook = simpleUserHooks
#endif
{-
On mac we need to use Clang as the assembler and C compiler to enable
-}
--simpleUserHooks { hookedPrograms = [ghcProgram { programPostConf = \ a b -> return ["-pgma clang", "-pgmc clang"] }] }
lensProgramOverrideArgs2ConfiguredProgram :: Lens [String] ConfiguredProgram
lensProgramOverrideArgs2ConfiguredProgram =
Lens (\ConfiguredProgram{programOverrideArgs}-> programOverrideArgs)
(\newargs confprog -> confprog{programOverrideArgs = newargs})
lensBuildHook2UserHooks :: Lens (PackageDescription -> LocalBuildInfo -> UserHooks -> BuildFlags -> IO ()) UserHooks
lensBuildHook2UserHooks = Lens (\UserHooks{buildHook}->buildHook) (\ bh uhook -> uhook{buildHook=bh})
lensProgramConfig2LocBuildInfo :: Lens (ProgramConfiguration) (LocalBuildInfo)
lensProgramConfig2LocBuildInfo = Lens (\LocalBuildInfo{withPrograms}-> withPrograms)
(\wprog lbi -> lbi{withPrograms= wprog})
-- my mini lens!
data Lens a b = Lens (b->a) (a ->b -> b)
infixr 9 #
(#) :: Lens a b -> Lens b c -> Lens a c
(#) lenA@(Lens getA setA) lenB@(Lens getB setB)= Lens (getA . getB) (\a c -> setB (setA a $ getB c) c)
get :: Lens a b -> b -> a
get (Lens lensGet _) b = lensGet b
set :: Lens a b -> a -> b -> b
set (Lens _ lensSet) a b = lensSet a b
{-
minier lens thats lens compatible proposed by kmett on irc
http://hpaste.org/89830
-- {-# LANGUAGE Rank2Types, DeriveFunctor #-}
-- import Control.Applicative
-- type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t
-- type Lens' s a = forall f. Functor f => (a -> f a) -> s -> f s
-- infixl 1 &
-- infixr 4 .~, %~
-- infixl 8 ^.
-- s ^. l = getConst (l Const s)
-- x & f = f x
-- (%~) l f s = l (\a () -> f a) s ()
-- (.~) l b s = l (\_ () -> b) s ()
-}
|
wellposed/vector-vectorized
|
Setup.hs
|
bsd-3-clause
| 3,592 | 3 | 12 | 788 | 673 | 355 | 318 | 30 | 1 |
{-# LANGUAGE CPP #-}
#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-unused-top-binds #-}
module Test.Control.Monad.TestFixture.THSpec (spec) where
import Test.Hspec
import Control.Applicative ((<|>))
import Control.Monad (when)
import Control.Monad.Except (runExcept, throwError)
import Control.Monad.Fail (MonadFail(..))
import Language.Haskell.TH.Syntax
import Control.Monad.TestFixture
import Control.Monad.TestFixture.TH
import Control.Monad.TestFixture.TH.Internal (methodNameToFieldName)
class MultiParam a b where
mkFixture "Fixture" [ts| MonadFail, Quasi |]
spec :: Spec
spec = do
describe "mkFixture" $
it "raises an error for multi-parameter typeclasses" $ do
let fixture = def
{ _qReport = \b s -> when b $ throwError s
, _qNewName = \s -> return $ Name (OccName s) (NameU 0)
, _qReify = \_ -> return $(lift =<< reify ''MultiParam)
}
let result = runExcept $ unTestFixtureT (runQ $ mkFixture "Fixture" [ts| MultiParam |]) fixture
result `shouldBe` (Left $
"mkFixture: cannot derive instance for multi-parameter typeclass\n"
++ " in: Test.Control.Monad.TestFixture.THSpec.MultiParam\n"
++ " expected: * -> GHC.Types.Constraint\n"
++ " given: * -> * -> GHC.Types.Constraint")
describe "methodNameToFieldName" $ do
it "prepends an underscore to ordinary names" $ do
nameBase (methodNameToFieldName 'id) `shouldBe` "_id"
nameBase (methodNameToFieldName '_fail) `shouldBe` "__fail"
it "prepends a tilde to infix operators" $ do
nameBase (methodNameToFieldName '(>>=)) `shouldBe` "~>>="
nameBase (methodNameToFieldName '(<|>)) `shouldBe` "~<|>"
#else
module Test.Control.Monad.TestFixture.THSpec (spec) where
import Test.Hspec
spec :: Spec
spec = return ()
#endif
|
cjdev/test-fixture
|
test/Test/Control/Monad/TestFixture/THSpec.hs
|
bsd-3-clause
| 2,054 | 2 | 14 | 398 | 420 | 242 | 178 | 5 | 1 |
module ColorSound where
import FFT
import Data.WAVE
import Data.Complex
import Graphics.Gloss
import Debug.Trace
windowSize :: Num a => a
windowSize = 1024
edge1Hz :: Num a => a
edge1Hz = 200
edge2Hz :: Num a => a
edge2Hz = 800
split3 :: (Int, Int) -> [a] -> ([a], [a], [a])
split3 (e1, e2) l = (x, y, z)
where
(x, xs) = splitAt e1 l
(y, z) = splitAt e2 xs
re2cx :: Num a => a -> Complex a
re2cx a = a :+ 0
uncurry3 :: (a -> b -> c -> d) -> ((a,b,c) -> d)
uncurry3 f = (\(a,b,c) -> f a b c)
colorSound :: WAVE -> Float -> Picture
colorSound w t =
trace debugStr $
color rgbSpec $ circleSolid 80
where
rate = fromIntegral $ waveFrameRate $ waveHeader w
pose = round $ t * rate
hz2ix = round . ((*) (windowSize / rate * 2))
edge1 = hz2ix edge1Hz
edge2 = hz2ix edge2Hz
mono = map head
sample = (take windowSize) . (drop pose) . mono . waveSamples
spec = fft . (map (re2cx . sampleToDouble)) . sample
spec3 = split3 (edge1, edge2) $ spec w
energy = (foldl1 (+)) . (map magnitude)
eNorm v = energy v / (fromIntegral (length v))
energy3 (rs, gs, bs) =
let r = eNorm rs
g = eNorm gs
b = eNorm bs
m = sum [r, g, b]
in ( realToFrac (r / m)
, realToFrac (g / m)
, realToFrac (b / m))
rgbSpec = uncurry3 makeColor (energy3 spec3) 1
debugStr = show rgbSpec ++ " T:" ++ show t ++ " P:" ++ show pose
|
akru/ColorSound
|
src/ColorSound.hs
|
bsd-3-clause
| 1,533 | 2 | 17 | 520 | 683 | 366 | 317 | 45 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
module FPNLA.Operations.BLAS.Strategies.SYRK.DefSeq () where
import FPNLA.Matrix (MatrixVector,
foldr_v,
generate_m,
generate_v)
import FPNLA.Operations.BLAS (SYRK (syrk))
import FPNLA.Operations.BLAS.Strategies.DataTypes (DefSeq)
import FPNLA.Operations.Parameters (Elt,
TransType (..),
blasResultM,
dimTrans_m,
dimTriang,
elemSymm,
elemTrans_m)
instance (Elt e, MatrixVector m v e) => SYRK DefSeq m v e where
syrk _ alpha pmA beta pmB
| p /= p' = error "syrk: incompatible ranges"
| otherwise = blasResultM $ generate_m p p (\i j -> (alpha * pmAMultIJ i j) + beta * elemSymm i j pmB)
where
(p, p') = dimTriang pmB
matMultIJ i j tmA tmB = foldr_v (+) 0 (generate_v (snd $ dimTrans_m tmA) (\k -> (*) (elemTrans_m i k tmA) (elemTrans_m k j tmB)) :: v e)
pmAMultIJ i j =
case pmA of
(NoTrans mA) -> matMultIJ i j pmA (Trans mA)
(Trans mA) -> matMultIJ i j (Trans mA) pmA
(ConjTrans mA) -> matMultIJ i j (Trans mA) pmA
|
mauroblanco/fpnla-examples
|
src/FPNLA/Operations/BLAS/Strategies/SYRK/DefSeq.hs
|
bsd-3-clause
| 1,833 | 0 | 15 | 965 | 409 | 222 | 187 | 28 | 0 |
{-# LANGUAGE Trustworthy,
TypeOperators,
PolyKinds, DataKinds,
TypeFamilies,
UndecidableInstances #-}
module Type.BST.Compare (
-- * Comparison
Compare, LargestK(Largest), SmallestK(Smallest), CompareUser
) where
import GHC.TypeLits
import Type.BST.Item
type family (a :: Ordering) $$ (b :: Ordering) :: Ordering
type instance LT $$ b = LT
type instance GT $$ b = GT
type instance EQ $$ b = b
infixl 0 $$
-- | The largest type (and kind) on 'Compare'.
data LargestK = Largest
-- | The smallest type (and kind) on 'Compare'.
data SmallestK = Smallest
-- | Compare two types.
type family Compare (a :: k) (b :: k') :: Ordering where
Compare Largest Largest = EQ
Compare _' Largest = LT
Compare Largest _' = GT
Compare Smallest Smallest = EQ
Compare _' Smallest = GT
Compare Smallest _' = LT
Compare False False = EQ
Compare False True = LT
Compare True False = GT
Compare True True = EQ
Compare LT LT = EQ
Compare LT EQ = LT
Compare LT GT = LT
Compare EQ LT = GT
Compare EQ EQ = EQ
Compare EQ GT = LT
Compare GT LT = GT
Compare GT EQ = GT
Compare GT GT = EQ
Compare m n = CmpNat m n
Compare s t = CmpSymbol s t
Compare Nothing Nothing = EQ
Compare Nothing (Just b) = LT
Compare (Just a) Nothing = GT
Compare (Just a) (Just b) = Compare a b
Compare (Left _') (Right _'') = LT
Compare (Right _') (Left _'') = GT
Compare (Left a) (Left b) = Compare a b
Compare (Right a) (Right b) = Compare a b
Compare '[] '[] = EQ
Compare '[] (b ': bs) = LT
Compare (a ': as) '[] = GT
Compare (a ': as) (b ': bs) = Compare a b $$ Compare as bs
Compare '(a1, a2) '(b1, b2) = Compare a1 b1 $$ Compare a2 b2
Compare '(a1, a2, a3) '(b1, b2, b3) = Compare a1 b1 $$ Compare a2 b2 $$ Compare a3 b3
Compare '(a1, a2, a3, a4) '(b1, b2, b3, b4) = Compare a1 b1 $$ Compare a2 b2 $$ Compare a3 b3 $$ Compare a4 b4
Compare '(a1, a2, a3, a4, a5) '(b1, b2, b3, b4, b5) = Compare a1 b1 $$ Compare a2 b2 $$ Compare a3 b3 $$ Compare a4 b4 $$ Compare a5 b5
Compare '(a1, a2, a3, a4, a5, a6) '(b1, b2, b3, b4, b5, b6) = Compare a1 b1 $$ Compare a2 b2 $$ Compare a3 b3 $$ Compare a4 b4 $$ Compare a5 b5 $$ Compare a6 b6
Compare '(a1, a2, a3, a4, a5, a6, a7) '(b1, b2, b3, b4, b5, b6, b7) = Compare a1 b1 $$ Compare a2 b2 $$ Compare a3 b3 $$ Compare a4 b4 $$ Compare a5 b5 $$ Compare a6 b6 $$ Compare a7 b7
Compare '(a1, a2, a3, a4, a5, a6, a7, a8) '(b1, b2, b3, b4, b5, b6, b7, b8) = Compare a1 b1 $$ Compare a2 b2 $$ Compare a3 b3 $$ Compare a4 b4 $$ Compare a5 b5 $$ Compare a6 b6 $$ Compare a7 b7 $$ Compare a8 b8
Compare '(a1, a2, a3, a4, a5, a6, a7, a8, a9) '(b1, b2, b3, b4, b5, b6, b7, b8, b9) = Compare a1 b1 $$ Compare a2 b2 $$ Compare a3 b3 $$ Compare a4 b4 $$ Compare a5 b5 $$ Compare a6 b6 $$ Compare a7 b7 $$ Compare a8 b8 $$ Compare a9 b9
Compare '(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) '(b1, b2, b3, b4, b5, b6, b7, b8, b9, b10) = Compare a1 b1 $$ Compare a2 b2 $$ Compare a3 b3 $$ Compare a4 b4 $$ Compare a5 b5 $$ Compare a6 b6 $$ Compare a7 b7 $$ Compare a8 b8 $$ Compare a9 b9 $$ Compare a10 b10
Compare (Item key a) (Item key' b) = Compare key key'
Compare a b = CompareUser a b
-- | Compare two types. Users can add instances.
type family CompareUser (a :: k) (b :: k') :: Ordering
|
Kinokkory/type-level-bst
|
src/Type/BST/Compare.hs
|
bsd-3-clause
| 3,359 | 6 | 15 | 869 | 1,608 | 855 | 753 | 67 | 0 |
{-# LANGUAGE TypeOperators, ScopedTypeVariables #-}
module Web.Routes.Regular where
import Control.Applicative hiding ((<|>))
import Data.Text (Text, pack, toLower)
import Generics.Regular
import Text.ParserCombinators.Parsec.Prim
import Text.ParserCombinators.Parsec.Combinator
import Web.Routes.PathInfo (PathInfo(fromPathSegments, toPathSegments), URLParser, segment)
class GToURL f where
gtoPathSegments :: f a -> [Text]
gfromPathSegments :: URLParser (f a)
instance PathInfo a => GToURL (K a) where
gtoPathSegments (K a) = toPathSegments a
gfromPathSegments = K <$> fromPathSegments
instance (GToURL f, GToURL g) => GToURL (f :+: g) where
gtoPathSegments (L x) = gtoPathSegments x
gtoPathSegments (R y) = gtoPathSegments y
gfromPathSegments = try (L <$> gfromPathSegments) <|> (R <$> gfromPathSegments)
instance (GToURL f, GToURL g) => GToURL (f :*: g) where
gtoPathSegments (x :*: y) = gtoPathSegments x ++ gtoPathSegments y
gfromPathSegments =
do x <- gfromPathSegments
y <- gfromPathSegments
return (x :*: y)
instance GToURL U where
gtoPathSegments U = []
gfromPathSegments = eof >> return U
instance GToURL f => GToURL (S s f) where
gtoPathSegments (S x) = gtoPathSegments x
gfromPathSegments = S <$> gfromPathSegments
instance forall c f. (Constructor c, GToURL f) => GToURL (C c f) where
gtoPathSegments c@(C x) = (toLower $ pack $ conName c) : gtoPathSegments x
gfromPathSegments =
let constr = undefined :: C c f r
in do segment (toLower $ pack $ conName constr) <|> segment (pack $ conName constr)
C <$> gfromPathSegments
|
Happstack/web-routes-regular
|
Web/Routes/Regular.hs
|
bsd-3-clause
| 1,669 | 0 | 14 | 353 | 565 | 296 | 269 | 36 | 0 |
{-# LANGUAGE Arrows, FlexibleContexts, MultiParamTypeClasses #-}
module Karamaan.Opaleye.Operators2 where
import Prelude hiding (and, or, not)
import Karamaan.Opaleye.Wire (Wire(Wire), unWire)
import Karamaan.Opaleye.OperatorsPrimatives (binrel)
import Karamaan.Opaleye.QueryArr (Query, QueryArr(QueryArr), next, tagWith)
import Database.HaskellDB.Query (ShowConstant, showConstant)
import Database.HaskellDB.PrimQuery (RelOp(Union, Intersect, Difference, UnionAll),
extend,
PrimExpr(AttrExpr),
Literal(OtherLit))
import qualified Database.HaskellDB.PrimQuery as PrimQuery
import Control.Arrow ((***), Arrow, (&&&), (<<<), second)
import Control.Applicative (Applicative, pure, (<*>))
import Data.Time.Calendar (Day)
import qualified Karamaan.Opaleye.Values as Values
import Karamaan.Opaleye.QueryColspec (QueryColspec)
import Data.Profunctor.Product.Default (Default, def)
import qualified Karamaan.Opaleye.ExprArr as E
import Karamaan.Plankton.Arrow (replaceWith)
import qualified Karamaan.Plankton.Arrow as A
import Karamaan.Plankton.Arrow.ReaderCurry (readerCurry2)
import Data.Profunctor (Profunctor, dimap)
import Data.Profunctor.Product (ProductProfunctor, (***!), empty, defaultEmpty,
defaultProfunctorProduct)
-- The only reason this is called Operators2 rather than Operators is that
-- I had to split the Operators module in two to avoid circular dependencies.
-- At some point I should come up with a better naming system.
eq :: QueryArr (Wire a, Wire a) (Wire Bool)
eq = E.toQueryArrDef E.eq
and :: QueryArr (Wire Bool, Wire Bool) (Wire Bool)
and = E.toQueryArrDef E.and
or :: QueryArr (Wire Bool, Wire Bool) (Wire Bool)
or = E.toQueryArrDef E.or
not :: QueryArr (Wire Bool) (Wire Bool)
not = E.toQueryArrDef E.not
notEq :: QueryArr (Wire a, Wire a) (Wire Bool)
notEq = E.toQueryArrDef E.notEq
doesntEqualAnyOf :: ShowConstant a => [a] -> QueryArr (Wire a) (Wire Bool)
doesntEqualAnyOf xs = not <<< equalsOneOf xs
equalsOneOf :: ShowConstant a => [a] -> QueryArr (Wire a) (Wire Bool)
equalsOneOf = E.toQueryArrDef . E.equalsOneOf
-- TODO: HaskellDB's 'cat' or '.++.' is implemented as SQL's '+' even when
-- using the PostgreSQL generator. The correct fix is probably to fix
-- the PostgreSQL generator (Database.HaskellDB.Sql.PostgreSQL).
cat :: QueryArr (Wire String, Wire String) (Wire String)
cat = E.toQueryArrDef E.cat
constantLit :: Literal -> Query (Wire a)
constantLit = E.toQueryArrDef . E.constantLit
-- TODO: is this type signature right?
-- Doesn't seem to work for string with postgresql-simple
-- because postgresql-simple seems to need a type sig on its strings
constant :: ShowConstant a => a -> Query (Wire a)
constant = constantLit . showConstant
-- Postgres seems to need type signatures on constant strings
constantString :: String -> Query (Wire String)
constantString = unsafeConstant . ("'" ++) . (++"' :: text")
-- HaskellDB doesn't have a ShowConstant instance for Day, only for
-- CalendarTime from old-time. We could perhaps just add an orphan
-- instance.
constantDay :: Day -> Query (Wire Day)
constantDay = unsafeConstant . Values.dayToSQL
unsafeConstant :: String -> Query (Wire a)
unsafeConstant = constantLit . OtherLit
-- Note that the natural type for 'intersect' and 'union' would be
-- ... => QueryArr (a, a) a. However I am not sure what it means to
-- implement such a signature in SQL. I don't know if SQL is limited
-- so that such a thing would not make sense, or whether my
-- understanding of what is necessary is insufficient.
type RelOpT a b = QueryArr () a -> QueryArr () a -> QueryArr () b
intersect :: Default QueryColspec a a => RelOpT a a
intersect = intersect' def
union :: Default QueryColspec a a => RelOpT a a
union = union' def
unionAll :: Default QueryColspec a a => RelOpT a a
unionAll = unionAll' def
difference :: Default QueryColspec a a => RelOpT a a
difference = difference' def
intersect' :: QueryColspec a b -> RelOpT a b
intersect' = binrel Intersect
union' :: QueryColspec a b -> RelOpT a b
union' = binrel Union
unionAll' :: QueryColspec a b -> RelOpT a b
unionAll' = binrel UnionAll
difference' :: QueryColspec a b -> RelOpT a b
difference' = binrel Difference
-- Case stuff
type CaseArg a = ([(Wire Bool, a)], a)
fmapCaseArg :: (a -> b) -> CaseArg a -> CaseArg b
fmapCaseArg f = map (second f) *** f
newtype CaseRunner a b = CaseRunner (QueryArr (CaseArg a) b)
instance Profunctor CaseRunner where
dimap f g (CaseRunner q) = CaseRunner (dimap (fmapCaseArg f) g q)
instance Functor (CaseRunner a) where
fmap f (CaseRunner c) = CaseRunner (fmap f c)
instance Applicative (CaseRunner a) where
pure = CaseRunner . pure
CaseRunner f <*> CaseRunner x = CaseRunner (f <*> x)
instance ProductProfunctor CaseRunner where
empty = defaultEmpty
(***!) = defaultProfunctorProduct
instance Default CaseRunner (Wire a) (Wire a) where
def = CaseRunner case_
runCase :: CaseRunner a b -> QueryArr (CaseArg a) b
runCase (CaseRunner q) = q
caseDef :: Default CaseRunner a b => QueryArr (CaseArg a) b
caseDef = runCase def
case_ :: QueryArr ([(Wire Bool, Wire a)], Wire a) (Wire a)
case_ = QueryArr f where
f ((cases, otherwise_), primQ, t0) = (w_out, primQ', t1)
where t1 = next t0
attrname_out = tagWith t0 "case_result"
w_out = Wire attrname_out
cases' = map (wireToPrimExpr *** wireToPrimExpr) cases
otherwise' = wireToPrimExpr otherwise_
caseExpr = PrimQuery.CaseExpr cases' otherwise'
primQ' = extend [(attrname_out, caseExpr)] primQ
-- End of case stuff
ifThenElse :: Default CaseRunner a b
=> QueryArr (Wire Bool, a, a) b
ifThenElse = proc (cond, ifTrue, ifFalse) ->
caseDef -< ([(cond, ifTrue)], ifFalse)
wireToPrimExpr :: Wire a -> PrimExpr
wireToPrimExpr = AttrExpr . unWire
-- ReaderCurried versions
-- TODO: What is the right way to be polymorphic over SQL's numeric types?
-- Num is not really appropriate (though it's what HaskellDB chose)
type NumBinOpG a b = NumBinOp2G a b b
type NumBinOp2G a b c = QueryArr a (Wire b) -> QueryArr a (Wire b)
-> QueryArr a (Wire c)
-- A short name since we will be using it a lot. Probably not a good idea to
-- import this into application code, though!
r :: QueryArr (Wire b, Wire b) (Wire c) -> NumBinOp2G a b c
r = readerCurry2
constantRC :: ShowConstant b => b -> QueryArr a (Wire b)
constantRC = replaceWith . constant
(.==.) :: NumBinOp2G a b Bool
(.==.) = r eq
(./=.) :: NumBinOp2G a b Bool
(./=.) = r notEq
(.&&.) :: NumBinOpG a Bool
(.&&.) = r and
(.||.) :: NumBinOpG a Bool
(.||.) = r or
(.++.) :: NumBinOp2G a String String
(.++.) = r cat
-- TODO: this signature could now be generalised to something involving
-- CaseRunner
ifThenElseRC :: QueryArr t (Wire Bool)
-> QueryArr t (Wire a)
-> QueryArr t (Wire a)
-> QueryArr t (Wire a)
ifThenElseRC cond ifTrue ifFalse = proc a -> do
cond' <- cond -< a
ifTrue' <- ifTrue -< a
ifFalse' <- ifFalse -< a
ifThenElse -< (cond', ifTrue', ifFalse')
caseRC :: [(QueryArr a (Wire Bool), QueryArr a (Wire b))]
-> QueryArr a (Wire b) -> QueryArr a (Wire b)
caseRC cases else_ = case_ <<< (cases' &&& else_)
where cases' = A.traverseArr (uncurry (&&&)) cases
|
karamaan/karamaan-opaleye
|
Karamaan/Opaleye/Operators2.hs
|
bsd-3-clause
| 7,410 | 2 | 11 | 1,494 | 2,207 | 1,203 | 1,004 | 134 | 1 |
{-# LANGUAGE RecordWildCards #-}
{-| @happstack-lite@ provides a simplied introduction to
@happstack-server@. (Nearly) all the functions in @happstack-lite@ are simple re-exports from the @happstack-server@ package. @happstack-lite@ offers two
key advantages over @happstack-server@:
1. it only contains the most commonly used functions, gathered in one convenient location.
2. the type signatures have been simplified to remove most references
to type classes, monad transformers, and other potentially confusing
type signatures.
The beautiful part about @happstack-lite@ is that because it merely @re-exports@ functions and types from @happstack-server@ it is possible to gradually import extra functionality from @happstack-server@ on an as-need basis.
There is a brief introduction to @happstack-lite@ located here:
<http://www.happstack.com/C/ViewPage/9>
More detailed examples and information can be found in the Happstack Crash Course:
<http://www.happstack.com/docs/crashcourse/index.html>
The Happstack Crash Course is written against @happstack-server@ but the behavior of the functions available in @happstack-lite@ is almost identical.
-}
module Happstack.Lite
( -- * Core Types
Request
, Response
, ServerPart
-- * Starting the Server
, ServerConfig(..)
, defaultServerConfig
, serve
-- * Routing an Incoming Request
, method
, Method(..)
, MatchMethod(..)
, dir
, path
, FromReqURI(..)
, nullDir
, guardRq
-- * Creating a Response
, ToMessage(..)
, toResponseBS
-- * Setting the Response Code
, ok
, internalServerError
, unauthorized
, notFound
, seeOther
, setResponseCode
-- * Looking up Request Parameters
, lookBS
, lookBSs
, lookText
, lookTexts
, lookFile
, ContentType(..)
-- * Cookies
, Cookie(..)
, CookieLife(..)
, mkCookie
, addCookies
, expireCookie
, lookCookieValue
-- * HTTP Headers
, addHeaderM
, setHeaderM
, getHeaderM
-- * File Serving
, Browsing(..)
, serveDirectory
, serveFile
, asContentType
, MimeMap
, guessContentTypeM
, mimeTypes
-- * Other
, MonadPlus(..)
, msum
) where
import Control.Monad (MonadPlus(..), msum)
import Control.Monad.Trans (liftIO)
import qualified Data.ByteString as B
import Data.ByteString.Lazy.Char8 (ByteString)
import Data.Int (Int64)
import Data.Maybe (fromMaybe)
import Data.Text.Lazy (Text)
import Happstack.Server (ContentType, Request, Response, ServerPart, FromReqURI, Method(..), MatchMethod, MimeMap, ToMessage(..), Cookie(..), CookieLife(..), Browsing, mimeTypes, mkCookie)
import Happstack.Server.SURI (ToSURI)
import qualified Happstack.Server as S
-- * Starting the server
-- | configuration to be used with 'serve' function
data ServerConfig =
ServerConfig { port :: Int -- ^ port to listen on
, ramQuota :: Int64 -- ^ maximum amount of POST data (in bytes)
, diskQuota :: Int64 -- ^ maximum file upload size (in bytes)
, tmpDir :: FilePath -- ^ temporary directory for file uploads
}
-- | a reasonable default 'ServerConfig'
--
-- > ServerConfig { port = 8000
-- > , ramQuota = 1 * 10^6
-- > , diskQuota = 20 * 10^6
-- > , tmpDir = "/tmp/"
-- > }
defaultServerConfig :: ServerConfig
defaultServerConfig =
ServerConfig { port = 8000
, ramQuota = 1 * 10^6
, diskQuota = 20 * 10^6
, tmpDir = "/tmp/"
}
-- | start the server and handle requests using the supplied 'ServerPart'
serve :: Maybe ServerConfig -- ^ if Nothing, then use 'defaultServerConfig'
-> ServerPart Response -- ^ request handler
-> IO ()
serve mServerConf part =
let ServerConfig{..} = fromMaybe defaultServerConfig mServerConf
in S.simpleHTTP (S.nullConf { S.port = port }) $
do S.decodeBody (S.defaultBodyPolicy tmpDir diskQuota ramQuota (ramQuota `div` 10))
part
-- * Routing on a URI path segment
-- | Pop a path element and run the supplied handler if it matches the
-- given string.
--
-- > handler :: ServerPart Response
-- > handler = dir "foo" $ dir "bar" $ subHandler
--
-- The path element can not contain \'/\'. See also 'dirs'.
dir :: String -> ServerPart a -> ServerPart a
dir = S.dir
-- | Pop a path element and parse it using the 'fromReqURI' in the
-- 'FromReqURI' class.
path :: (FromReqURI a) => (a -> ServerPart b) -> ServerPart b
path = S.path
-- | guard which only succeeds if there are no remaining path segments
--
-- Often used if you want to explicitly assign a route for '/'
--
nullDir :: ServerPart ()
nullDir = S.nullDir
-- | Guard using an arbitrary function on the 'Request'.
guardRq :: (Request -> Bool) -> ServerPart ()
guardRq = S.guardRq
-- * Routing on the HTTP Request method
-- | Guard against the request method
--
-- Example:
--
-- > handler :: ServerPart Response
-- > handler =
-- > do method [GET, HEAD]
-- > ...
method :: (MatchMethod method) => method -> ServerPart ()
method = S.method
-- * Creating a Response
toResponse :: (ToMessage a) => a -> Response
toResponse = S.toResponse
-- | A low-level function to build a 'Response' from a content-type
-- and a 'ByteString'.
--
-- Creates a 'Response' in a manner similar to the 'ToMessage' class,
-- but without requiring an instance declaration.
--
-- example:
--
-- > import Data.ByteString.Char8 as C
-- > import Data.ByteString.Lazy.Char8 as L
-- > import Happstack.Lite
-- >
-- > main = serve Nothing $ ok $ toResponseBS (C.pack "text/plain") (L.pack "hello, world")
--
-- (note: 'C.pack' and 'L.pack' only work for ascii. For unicode strings you would need to use @utf8-string@, @text@, or something similar to create a valid 'ByteString').
toResponseBS :: B.ByteString -- ^ content-type
-> ByteString -- ^ response body
-> Response
toResponseBS = S.toResponseBS
-- * Response code
-- | Respond with @200 OK@.
--
-- > main = serve Nothing $ ok "Everything is OK"
ok :: a -> ServerPart a
ok = S.ok
-- | Respond with @204 No Content@
--
-- A @204 No Content@ response may not contain a message-body. If you try to supply one, it will be dutifully ignored.
--
-- > main = serve Nothing $ noContent "This will be ignored."
noContent :: a -> ServerPart a
noContent = S.noContent
-- | Respond with @500 Internal Server Error@.
--
-- > main = serve Nothing $ internalServerError "Sorry, there was an internal server error."
internalServerError :: a -> ServerPart a
internalServerError = S.internalServerError
-- | Responds with @502 Bad Gateway@.
--
-- > main = serve Nothing $ badGateway "Bad Gateway."
badGateway :: a -> ServerPart a
badGateway = S.badGateway
-- | Respond with @400 Bad Request@.
--
-- > main = serve Nothing $ badRequest "Bad Request."
badRequest :: a -> ServerPart a
badRequest = S.badRequest
-- | Respond with @401 Unauthorized@.
--
-- > main = serve Nothing $ unauthorized "You are not authorized."
unauthorized :: a -> ServerPart a
unauthorized = S.unauthorized
-- | Respond with @403 Forbidden@.
--
-- > main = serve Nothing $ forbidden "Sorry, it is forbidden."
forbidden :: a -> ServerPart a
forbidden = S.forbidden
-- | Respond with @404 Not Found@.
--
-- > main = serve Nothing $ notFound "What you are looking for has not been found."
notFound :: a -> ServerPart a
notFound = S.notFound
-- | Set an arbitrary return code in your response.
--
-- A filter for setting the response code. Generally you will use a
-- helper function like 'ok' or 'seeOther'.
--
-- > main = serve Nothing $ do setResponseCode 200
-- > return "Everything is OK"
--
setResponseCode :: Int -- ^ response code
-> ServerPart ()
setResponseCode = S.setResponseCode
-- | Respond with @413 Request Entity Too Large@.
--
-- > main = serve Nothing $ requestEntityTooLarge "That's too big for me to handle."
requestEntityTooLarge :: a -> ServerPart a
requestEntityTooLarge = S.requestEntityTooLarge
-- | Respond with @303 See Other@.
--
-- > main = serve Nothing $ seeOther "http://example.org/" "What you are looking for is now at http://example.org/"
--
-- NOTE: The second argument of 'seeOther' is the message body which will sent to the browser. According to the HTTP 1.1 spec,
--
-- @the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).@
--
-- This is because pre-HTTP\/1.1 user agents do not support 303. However, in practice you can probably just use @\"\"@ as the second argument.
seeOther :: (ToSURI uri) => uri -> a -> ServerPart a
seeOther = S.seeOther
-- | Respond with @302 Found@.
--
-- You probably want 'seeOther'. This method is not in popular use anymore, and is generally treated like 303 by most user-agents anyway.
found :: (ToSURI uri) => uri -> a -> ServerPart a
found = S.found
-- | Respond with @301 Moved Permanently@.
--
-- > main = serve Nothing $ movedPermanently "http://example.org/" "What you are looking for is now at http://example.org/"
movedPermanently :: (ToSURI uri) => uri -> a -> ServerPart a
movedPermanently = S.movedPermanently
-- | Respond with @307 Temporary Redirect@.
--
-- > main = serve Nothing $ tempRedirect "http://example.org/" "What you are looking for is temporarily at http://example.org/"
tempRedirect :: (ToSURI uri) => uri -> a -> ServerPart a
tempRedirect = S.tempRedirect
-- * Request Parameters
-- | Gets the first matching named input parameter as a lazy 'ByteString'
--
-- Searches the QUERY_STRING followed by the Request body.
--
-- see also: 'lookBSs'
lookBS :: String -> ServerPart ByteString
lookBS = S.lookBS
-- | Gets all matches for the named input parameter as lazy 'ByteString's
--
-- Searches the QUERY_STRING followed by the Request body.
--
-- see also: 'lookBS'
lookBSs :: String -> ServerPart [ByteString]
lookBSs = S.lookBSs
-- | Gets the first matching named input parameter as a lazy 'Text'
--
-- Searches the QUERY_STRING followed by the Request body.
--
-- This function assumes the underlying octets are UTF-8 encoded.
--
-- see also: 'lookTexts'
lookText :: String -> ServerPart Text
lookText = S.lookText
-- | Gets all matches for the named input parameter as lazy 'Text's
--
-- Searches the QUERY_STRING followed by the Request body.
--
-- This function assumes the underlying octets are UTF-8 encoded.
--
-- see also: 'lookText'
lookTexts :: String -> ServerPart [Text]
lookTexts = S.lookTexts
-- | Gets the first matching named file
--
-- Files can only appear in the request body. Additionally, the form
-- must set enctype=\"multipart\/form-data\".
--
-- This function returns a tuple consisting of:
--
-- (1) The temporary location of the uploaded file
--
-- (2) The local filename supplied by the browser
--
-- (3) The content-type supplied by the browser
--
-- NOTE: You must move the file from the temporary location before the
-- 'Response' is sent. The temporary files are automatically removed
-- after the 'Response' is sent.
lookFile :: String -- ^ name of input field to search for
-> ServerPart (FilePath, FilePath, ContentType) -- ^ (temporary file location, uploaded file name, content-type)
lookFile = S.lookFile
-- * Cookies
-- | gets the named cookie as a string
lookCookieValue :: String -> ServerPart String
lookCookieValue = S.lookCookieValue
-- | Add the list 'Cookie' to the 'Response'.
--
addCookies :: [(CookieLife, Cookie)] -> ServerPart ()
addCookies = S.addCookies
-- | Expire the named cookie immediately and set the cookie value to @\"\"@
--
-- > main = serve Nothing $
-- > do expireCookie "name"
-- > ok $ "The cookie has been expired."
expireCookie :: String -> ServerPart ()
expireCookie = S.expireCookie
-- * Headers
-- | Get a header out of the request.
getHeaderM :: String -> ServerPart (Maybe B.ByteString)
getHeaderM = S.getHeaderM
-- | Add headers into the response. This method does not overwrite
-- any existing header of the same name, hence the name 'addHeaderM'.
-- If you want to replace a header use 'setHeaderM'.
addHeaderM :: String -> String -> ServerPart ()
addHeaderM = S.addHeaderM
-- | Set a header into the response. This will replace an existing
-- header of the same name. Use 'addHeaderM' if you want to add more
-- than one header of the same name.
setHeaderM :: String -> String -> ServerPart ()
setHeaderM = S.setHeaderM
-- * File Serving
-- | Serve files and directories from a directory and its subdirectories using 'sendFile'.
--
-- Usage:
--
-- > serveDirectory EnableBrowsing ["index.html"] "path/to/files/on/disk"
--
-- If the requested path does not match a file or directory on the
-- disk, then 'serveDirectory' calls 'mzero'.
--
-- If the requested path is a file then the file is served normally.
--
-- If the requested path is a directory, then the result depends on
-- what the first two arguments to the function are.
--
-- The first argument controls whether directory browsing is
-- enabled.
--
-- The second argument is a list of index files (such as
-- index.html).
--
-- When a directory is requested, 'serveDirectory' will first try to
-- find one of the index files (in the order they are listed). If that
-- fails, it will show a directory listing if 'EnableBrowsing' is set,
-- otherwise it will return @forbidden \"Directory index forbidden\"@.
--
-- Here is an explicit list of all the possible outcomes when the
-- argument is a (valid) directory:
--
-- [@'DisableBrowsing', empty index file list@]
--
-- This will always return, forbidden \"Directory index forbidden\"
--
-- [@'DisableBrowsing', non-empty index file list@]
--
-- 1. If an index file is found it will be shown.
--
-- 2. Otherwise returns, forbidden \"Directory index forbidden\"
--
-- [@'EnableBrowsing', empty index file list@]
--
-- Always shows a directory index.
--
-- [@'EnableBrowsing', non-empty index file list@]
--
-- 1. If an index file is found it will be shown
--
-- 2. Otherwise shows a directory index
--
-- see also: 'serveFile'
serveDirectory :: Browsing -- ^ allow directory browsing
-> [FilePath] -- ^ index file names, in case the requested path is a directory
-> FilePath -- ^ file/directory to serve
-> ServerPart Response
serveDirectory = S.serveDirectory
-- | Serve a single, specified file. The name of the file being served is specified explicity. It is not derived automatically from the 'Request' url.
--
-- example 1:
--
-- Serve as a specific content-type:
--
-- > serveFile (asContentType "image/jpeg") "/srv/data/image.jpg"
--
--
-- example 2:
--
-- Serve guessing the content-type from the extension:
--
-- > serveFile (guessContentTypeM mimeTypes) "/srv/data/image.jpg"
--
-- If the specified path does not exist or is not a file, this function will return 'mzero'.
--
-- WARNING: No security checks are performed.
--
-- NOTE: alias for 'serveFileUsing' 'filePathSendFile'
serveFile :: (FilePath -> ServerPart String) -- ^ function for determining content-type of file. Typically 'asContentType'
-> FilePath -- ^ path to the file to serve
-> ServerPart Response
serveFile asContentType fp = S.serveFile asContentType fp
-- | returns a specific content type, completely ignoring the 'FilePath' argument.
--
-- Use this with 'serveFile' if you want to explicitly specify the
-- content-type.
--
-- see also: 'serveFile'
asContentType :: String -- ^ the content-type to return
-> (FilePath -> ServerPart String)
asContentType ct = liftIO . S.asContentType ct
-- | try to guess the content-type of a file based on its extension
--
-- defaults to "application/octet-stream" if no match was found.
--
-- Useful as an argument to 'serveFile'
--
-- see also: 'serveFile', 'mimeTypes'
guessContentTypeM :: MimeMap -- ^ map from file extensions to mime-types (usually 'mimeTypes')
-> (FilePath -> ServerPart String)
guessContentTypeM mm = liftIO . S.guessContentTypeM mm
|
Happstack/happstack-lite
|
Happstack/Lite.hs
|
bsd-3-clause
| 16,269 | 0 | 14 | 3,458 | 1,734 | 1,099 | 635 | 161 | 1 |
{-# LANGUAGE Arrows #-}
{-# LANGUAGE GADTs #-}
module CodeGen where
import Control.Arrow
import Control.Arrow.Operations
import Control.Arrow.Transformer.Writer
import Control.Monad.Identity
import Expr
import X86_64 hiding (push, pop)
type X86_64 a b = WriterArrow [Instr] (Kleisli Identity) a b
op :: (Register -> Register -> X86_64 n n) -> X86_64 (Succ (Succ n)) (Succ n)
op instr = pop EAX >>>
pop EBX >>>
instr EAX EBX >>>
push EAX
output :: Instr -> X86_64 n m
output instr = proc _ -> do
write -< [instr]
returnA -< undefined
set :: Register -> Int -> X86_64 n n
set r n = output $ Set r n
push :: Register -> X86_64 n (Succ n)
push reg = output $ Push reg
pop :: Register -> X86_64 (Succ n) n
pop reg = output $ Pop reg
add :: Register -> Register -> X86_64 n n
add r r' = output $ Add r r'
mul :: Register -> Register -> X86_64 n n
mul r r' = output $ Mul r r'
compile :: Expr t -> X86_64 n (Succ n)
compile (Lit n) = set EAX n >>>
push EAX
compile (e :+: e') = compile e >>>
compile e' >>>
op add
compile (e :*: e') = compile e >>>
compile e' >>>
op mul
assemble :: X86_64 n (Succ n) -> [Instr]
assemble program = snd $ runIdentity $ runKleisli (elimWriter program) initial
where initial = undefined :: n
|
faineance/minigen
|
src/CodeGen.hs
|
bsd-3-clause
| 1,442 | 1 | 10 | 469 | 553 | 279 | 274 | 41 | 1 |
{-|
Module : Data.Blob
Stability : Experimental
Portability : non-portable (requires POSIX)
This module provides interface for handling large objects -
also known as blobs.
One of the use cases for bloc is storing large objects in databases.
Instead of storing the entire blob in the database, you can just store
the 'BlobId' of the blob.
Multiple values in the database can share a 'BlobId' and we provide an
interface for garbage collection for such cases.
-}
module Data.Blob ( Blob (..)
, BlobId
, BlobStore
, WriteContext
, ReadContext
, openBlobStore
, newBlob
, writePartial
, endWrite
, createBlob
, startRead
, readPartial
, skipBytes
, endRead
, readBlob
, deleteBlob
) where
import Control.Monad ((<=<))
import qualified Crypto.Hash.SHA512 as SHA512
import Data.Blob.Directories
import qualified Data.Blob.FileOperations as F
import Data.Blob.Types
import System.Directory (renameFile)
-- | All the blobs of an application are stored in the
-- same directory. 'openBlobStore' returns the 'BlobStore'
-- corresponding to a given directory.
openBlobStore :: FilePath -> IO BlobStore
openBlobStore dir = do
mapM_ F.createDir [dir, tempDir dir, currDir dir]
F.createFileInDir (currDir dir) metadataFile
F.recoverFromGC dir
return $ BlobStore dir
-- | Creates an empty blob in the given BlobStore.
--
-- Use 'writePartial' to write contents to the newly
-- created blob.
newBlob :: BlobStore -> IO WriteContext
newBlob (BlobStore dir) = do
filename <- F.createUniqueFile dir
let temploc = TempLocation dir filename
h <- F.openFileForWrite $ getFullPath tempDirName temploc
return $ WriteContext temploc h SHA512.init
-- | 'writePartial' appends the given blob to the
-- blob referenced by the 'WriteContext'.
writePartial :: WriteContext -> Blob -> IO WriteContext
writePartial (WriteContext l h ctx) (Blob b) = do
F.writeToHandle h b
let newctx = SHA512.update ctx b
return $ WriteContext l h newctx
-- | Finalize the write to the given blob.
--
-- After calling 'endWrite' no more updates are possible
-- on the blob.
endWrite :: WriteContext -> IO BlobId
endWrite (WriteContext l h ctx) = do
F.syncAndClose h
renameFile (getFullPath tempDirName l) (getFullPath currDirName blobId)
F.syncDir (currDir (baseDir l))
return blobId
where
newfilename = "sha512-" ++ F.toFileName (SHA512.finalize ctx)
blobId = BlobId (baseDir l) newfilename
-- | Create a blob from the given contents.
--
-- Use 'createBlob' only for small contents.
-- For large contents, use the partial write interface
-- ('newBlob' followed by calls to 'writePartial').
createBlob :: BlobStore -> Blob -> IO BlobId
createBlob blobstore blob = newBlob blobstore
>>= \wc -> writePartial wc blob
>>= endWrite
-- | Open blob for reading.
startRead :: BlobId -> IO ReadContext
startRead = fmap ReadContext . F.getHandle
-- | Read given number of bytes from the blob.
readPartial :: ReadContext -> Int -> IO Blob
readPartial (ReadContext h) sz = fmap Blob $ F.readFromHandle h sz
-- | Skip given number of bytes ahead in the blob.
skipBytes :: ReadContext -> Integer -> IO ()
skipBytes (ReadContext h) = F.seekHandle h
-- | Complete reading from a blob.
endRead :: ReadContext -> IO ()
endRead (ReadContext h) = F.closeHandle h
-- | 'readBlob' reads an entire blob.
--
-- Use 'readBlob' only for small blobs.
-- For large blobs, use 'readPartial' instead.
readBlob :: BlobId -> IO Blob
readBlob = fmap Blob . F.readAllFromHandle <=< F.getHandle
-- | Deletes the given blob.
--
-- Use 'deleteBlob' only when you are sure that the given blob
-- is not accessible by anyone. If the blob is shared, you should
-- use the GC interface instead.
deleteBlob :: BlobId -> IO ()
deleteBlob = F.deleteFile . getFullPath currDirName
|
TypeDB/bloc
|
src/Data/Blob.hs
|
bsd-3-clause
| 4,112 | 0 | 11 | 1,011 | 768 | 403 | 365 | -1 | -1 |
{-# LANGUAGE TypeFamilies #-}
-- | Unit tests for 3D CSG Operations
module CSG where
import Diagrams.Prelude hiding (nearly)
import Diagrams.ThreeD.Shapes
import Linear.Epsilon
import Test.Tasty
import Test.Tasty.HUnit
import Data.Maybe
tests :: TestTree
tests = testGroup "3D"
[ solids
, csg
]
solids :: TestTree
solids = testGroup "solids"
[ testGroup "sphere"
[ testGroup "Inside Query"
[ testCase "origin is inside" $ assertInside True sphere origin
, testCase "near surface inside" $
assertInside True sphere zOneMinus
, testCase "near surface outside" $
assertInside False sphere zOnePlus
]
, testGroup "Trace"
[ testCase "+x from origin" $ rayTraceV origin unitX sphere @?= Just unitX
, testCase "+y from origin" $ rayTraceV origin unitY sphere @?=Just unitY
, testCase "+z from origin" $ rayTraceV origin unitZ sphere @?=Just unitZ
]
, testGroup "Envelope"
[ testCase "+x envelope" $ envelopeV unitX sphere @?= unitX
, testCase "+y envelope" $ envelopeV unitY sphere @?= unitY
, testCase "+z envelope" $ envelopeV unitZ sphere @?= unitZ
]
]
, testGroup "cube"
[ testGroup "Inside Query"
[ testCase "near origin inside" $
assertInside True cube (mkP3 slight slight slight)
, testCase "near origin outside" $
assertInside False cube (mkP3 (-slight) slight slight)
, testCase "near opposite corner inside" $
assertInside True cube (mkP3 oneMinus oneMinus oneMinus)
, testCase "near opposite corner outside" $
assertInside False cube (mkP3 oneMinus onePlus oneMinus)
]
, testGroup "Trace"
-- If we trace from the origin, we find the intersection at the origin!
[ testCase "+x from near origin" $
rayTraceV (mkP3 slight 0 0) unitX cube @?=Just (oneMinus *^ unitX)
, testCase "+y from near origin" $
rayTraceV (mkP3 0 slight 0) unitY cube @?=Just (oneMinus *^ unitY)
, testCase "+z from near oprigin" $
rayTraceV aboveOrigin unitZ cube @?=Just (oneMinus *^ unitZ)
]
, testGroup "Envelope"
[ testCase "+x envelope" $ envelopeV unitX cube @?= unitX
, testCase "+y envelope" $ envelopeV unitY cube @?= unitY
, testCase "+z envelope" $ envelopeV unitZ cube @?= unitZ
]
]
, testGroup "cone"
[ testGroup "Inside Query"
[ testCase "slightly above origin" $
assertInside True cone aboveOrigin
, testCase "slightly below origin" $
assertInside False cone (mkP3 0 0 (-slight))
, testCase "near (1,0,0) inside" $
assertInside True cone (mkP3 oneMinus 0 (slight/2))
, testCase "near (1,0,0) outside" $
assertInside False cone (mkP3 onePlus 0 0)
, testCase "slightly below apex" $
assertInside True cone zOneMinus
, testCase "slightly above apex" $
assertInside False cone zOnePlus
]
, testGroup "Trace"
[ testCase "+x from near origin" $
fromJust (rayTraceV aboveOrigin unitX cone) `nearly` (oneMinus *^ unitX)
, testCase "+z from near origin" $
fromJust (rayTraceV aboveOrigin unitZ cone) `nearly` (oneMinus *^ unitZ)
, testCase "+x from near (1,0,0) inside" $
fromJust (rayTraceV (mkP3 (1-2*slight) 0 slight) unitX cone) `nearly` (slight *^ unitX)
, testCase "+x from near (1,0,0) outside" $
assertNothing $ rayTraceV (mkP3 1 0 slight) unitX cone
, testCase "+z from near apex inside" $
fromJust (rayTraceV zOneMinus unitZ cone) `nearly` (slight *^ unitZ)
, testCase "+Z from near apex outside" $
assertNothing $rayTraceV zOnePlus unitZ cone
]
, testGroup "Envelope"
[ testCase "+x from origin" $ envelopeV unitX cone @?= unitX
, testCase "+y from origin" $ envelopeV unitY cone @?= unitY
, testCase "+z from origin" $ envelopeV unitZ cone @?= unitZ
]
]
, testGroup "cylinder"
[ testGroup "Inside Query"
[ testCase "slightly above origin" $
assertInside True cylinder aboveOrigin
, testCase "slightly below top" $
assertInside True cylinder zOneMinus
, testCase "near (1,0,0) inside" $
assertInside True cylinder (mkP3 oneMinus 0 slight)
, testCase "near (1,0,0) outside" $
assertInside False cylinder (mkP3 onePlus 0 slight)
]
, testGroup "Trace"
[ testCase "+x from near origin" $
fromJust (rayTraceV aboveOrigin unitX cylinder) `nearly` unitX
, testCase "+x from near (1,0,0) inside" $
fromJust (rayTraceV (mkP3 oneMinus 0 slight) unitX cylinder) `nearly` (slight *^ unitX)
, testCase "+x from near (1,0,0) outside" $
assertNothing $ rayTraceV (mkP3 onePlus 0 slight) unitX cylinder
, testCase "+z from near origin" $
fromJust (rayTraceV aboveOrigin unitZ cylinder) `nearly` (oneMinus *^ unitZ)
, testCase "+z from near top inside" $
fromJust (rayTraceV zOneMinus unitZ cylinder) `nearly` (slight *^ unitZ)
, testCase "+z from near top outside" $
assertNothing $ rayTraceV zOnePlus unitZ cylinder
]
, testGroup "Envelope"
[ testCase "+x from origin" $ envelopeV unitX cylinder @?= unitX
, testCase "+y from origin" $ envelopeV unitY cylinder @?= unitY
, testCase "+z from origin" $ envelopeV unitZ cylinder @?= unitZ
]
]
]
csg :: TestTree
csg = testGroup "csg"
[ testGroup "union"
[ testGroup "Inside"
[ testCase "-x axis inside" $
assertInside True sphereUnion (mkP3 (-oneMinus) 0 0)
, testCase "-x axis outside" $
assertInside False sphereUnion (mkP3 (-onePlus) 0 0)
, testCase "+x axis inside" $
assertInside True sphereUnion (mkP3 (1.5 - slight) 0 0)
]
, testGroup "Trace"
[ testCase "+x from origin" $
fromJust (rayTraceV origin unitX sphereUnion) `nearly` (1.5 *^ unitX)
, testCase "-x from origin" $
fromJust (rayTraceV origin unit_X sphereUnion) `nearly` (-1 *^ unitX)
]
, testGroup "Envelope"
[ testCase "+x from origin" $ envelopeV unitX sphereUnion @?= (1.5 *^ unitX)
, testCase "-x from origin" $ envelopeV unit_X sphereUnion @?= (-1 *^ unitX)
]
]
, testGroup "intersection"
[ testGroup "Inside Query"
[ testCase "-x axis inside" $
assertInside True sphereIntersection (mkP3 (-0.5 + slight) 0 0)
, testCase "-x axis outside" $
assertInside False sphereIntersection (mkP3 (-0.5 - slight) 0 0)
, testCase "+x axis inside" $
assertInside True sphereIntersection (mkP3 oneMinus 0 0)
, testCase "+x axis outside" $
assertInside False sphereIntersection (mkP3 onePlus 0 0)
]
, testGroup "Trace"
[ testCase "+x from origin" $
fromJust (rayTraceV origin unitX sphereIntersection) `nearly` unitX
, testCase "-x from origin" $
fromJust (rayTraceV origin unit_X sphereIntersection) `nearly` (-0.5 *^ unitX)
]
]
, testGroup "difference"
[ testGroup "Inside Query"
[ testCase "-x axis inside" $
assertInside True sphereDifference (mkP3 (-oneMinus) 0 0)
, testCase "-x axis outside" $
assertInside False sphereDifference (mkP3 (-onePlus) 0 0)
, testCase "+x axis inside" $
assertInside True sphereDifference (mkP3 (0.5 - slight) 0 0)
, testCase "+x axis outside" $
assertInside False sphereDifference (mkP3 (0.5 + slight) 0 0)
]
, testGroup "Trace"
[ testCase "+x from origin" $
fromJust (rayTraceV origin unitX sphereDifference) `nearly` (0.5 *^ unitX)
, testCase "-x from origin" $
fromJust (rayTraceV origin unit_X sphereDifference) `nearly` unit_X
]
]
]
-- Conveniences to avoid repetition
sphereUnion :: CSG Double
sphereUnion = union sphere (translateX 0.5 sphere)
sphereIntersection :: CSG Double
sphereIntersection = intersection sphere (translateX 0.5 sphere)
sphereDifference :: CSG Double
sphereDifference = difference sphere (translateX 1.5 sphere)
-- | near enough for test success
slight :: Double
slight = 0.001
-- | slightly more than 1
onePlus :: Double
onePlus = 1 + slight
-- | slightly less than 1
oneMinus :: Double
oneMinus = 1 - slight
aboveOrigin :: Point V3 Double
aboveOrigin = mkP3 0 0 slight
zOnePlus :: Point V3 Double
zOnePlus = mkP3 0 0 onePlus
zOneMinus :: Point V3 Double
zOneMinus = mkP3 0 0 oneMinus
nearly :: Epsilon a => a -> a -> Assertion
nearly a b = assertBool "Expression was not near enough to zero" $
nearZero (a - b)
-- constrain to Double to reduce inline type signatures in this module
assertInside :: (Inside t, Vn t ~ V3 Double) => Bool -> t -> P3 Double -> Assertion
assertInside result t p = result @?= getAny (runQuery (inside t) p)
assertNothing :: Maybe a -> Assertion
assertNothing = assertBool "Expression was not Nothing" . isNothing
|
diagrams/diagrams-test
|
misc/CSG.hs
|
bsd-3-clause
| 9,472 | 0 | 20 | 2,840 | 2,478 | 1,245 | 1,233 | 181 | 1 |
data T = T {-# UNPACK #-} !X
{-# UNPACK #-} !X
|
itchyny/vim-haskell-indent
|
test/pragma/unpack.out.hs
|
mit
| 58 | 0 | 6 | 23 | 19 | 11 | 8 | 2 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ParallelListComp #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE RecordWildCards #-}
{-|
The @roi@ command prints internal rate of return and time-weighted rate of return for and investment.
-}
module Hledger.Cli.Commands.Roi (
roimode
, roi
) where
import Control.Monad
import System.Exit
import Data.Time.Calendar
import Text.Printf
import Data.Bifunctor (second)
import Data.Either (fromLeft, fromRight, isLeft)
import Data.Function (on)
import Data.List
import Numeric.RootFinding
import Data.Decimal
import qualified Data.Text as T
import qualified Data.Text.Lazy.IO as TL
import System.Console.CmdArgs.Explicit as CmdArgs
import Text.Tabular.AsciiWide as Tab
import Hledger
import Hledger.Cli.CliOptions
roimode = hledgerCommandMode
$(embedFileRelative "Hledger/Cli/Commands/Roi.txt")
[flagNone ["cashflow"] (setboolopt "cashflow") "show all amounts that were used to compute returns"
,flagReq ["investment"] (\s opts -> Right $ setopt "investment" s opts) "QUERY"
"query to select your investment transactions"
,flagReq ["profit-loss","pnl"] (\s opts -> Right $ setopt "pnl" s opts) "QUERY"
"query to select profit-and-loss or appreciation/valuation transactions"
]
[generalflagsgroup1]
hiddenflags
([], Just $ argsFlag "[QUERY]")
-- One reporting span,
data OneSpan = OneSpan
Day -- start date, inclusive
Day -- end date, exclusive
MixedAmount -- value of investment at the beginning of day on spanBegin_
MixedAmount -- value of investment at the end of day on spanEnd_
[(Day,MixedAmount)] -- all deposits and withdrawals (but not changes of value) in the DateSpan [spanBegin_,spanEnd_)
[(Day,MixedAmount)] -- all PnL changes of the value of investment in the DateSpan [spanBegin_,spanEnd_)
deriving (Show)
roi :: CliOpts -> Journal -> IO ()
roi CliOpts{rawopts_=rawopts, reportspec_=rspec@ReportSpec{_rsReportOpts=ReportOpts{..}}} j = do
-- We may be converting posting amounts to value, per hledger_options.m4.md "Effect of --value on reports".
let
today = _rsDay rspec
priceOracle = journalPriceOracle infer_prices_ j
styles = journalCommodityStyles j
mixedAmountValue periodlast date =
maybe id (mixedAmountApplyValuation priceOracle styles periodlast today date) value_
. maybe id (mixedAmountToCost styles) conversionop_
let
ropts = _rsReportOpts rspec
wd = whichDate ropts
showCashFlow = boolopt "cashflow" rawopts
prettyTables = pretty_
makeQuery flag = do
q <- either usageError (return . fst) . parseQuery today . T.pack $ stringopt flag rawopts
return . simplifyQuery $ And [queryFromFlags ropts{period_=PeriodAll}, q]
investmentsQuery <- makeQuery "investment"
pnlQuery <- makeQuery "pnl"
let
filteredj = filterJournalTransactions investmentsQuery j
trans = dbg3 "investments" $ jtxns filteredj
when (null trans) $ do
putStrLn "No relevant transactions found. Check your investments query"
exitFailure
let spans = snd $ reportSpan filteredj rspec
let priceDirectiveDates = dbg3 "priceDirectiveDates" $ map pddate $ jpricedirectives j
tableBody <- forM spans $ \span@(DateSpan (Just spanBegin) (Just spanEnd)) -> do
-- Spans are [spanBegin,spanEnd), and spanEnd is 1 day after then actual end date we are interested in
let
cashFlowApplyCostValue = map (\(d,amt) -> (d,mixedAmountValue spanEnd d amt))
valueBefore =
mixedAmountValue spanEnd spanBegin $
total trans (And [ investmentsQuery
, Date (DateSpan Nothing (Just spanBegin))])
valueAfter =
mixedAmountValue spanEnd spanEnd $
total trans (And [investmentsQuery
, Date (DateSpan Nothing (Just spanEnd))])
priceDates = dbg3 "priceDates" $ nub $ filter (spanContainsDate span) priceDirectiveDates
cashFlow =
((map (,nullmixedamt) priceDates)++) $
cashFlowApplyCostValue $
calculateCashFlow wd trans (And [ Not investmentsQuery
, Not pnlQuery
, Date span ] )
pnl =
cashFlowApplyCostValue $
calculateCashFlow wd trans (And [ Not investmentsQuery
, pnlQuery
, Date span ] )
thisSpan = dbg3 "processing span" $
OneSpan spanBegin spanEnd valueBefore valueAfter cashFlow pnl
irr <- internalRateOfReturn showCashFlow prettyTables thisSpan
twr <- timeWeightedReturn showCashFlow prettyTables investmentsQuery trans mixedAmountValue thisSpan
let cashFlowAmt = maNegate . maSum $ map snd cashFlow
let smallIsZero x = if abs x < 0.01 then 0.0 else x
return [ showDate spanBegin
, showDate (addDays (-1) spanEnd)
, T.pack $ showMixedAmount valueBefore
, T.pack $ showMixedAmount cashFlowAmt
, T.pack $ showMixedAmount valueAfter
, T.pack $ showMixedAmount (valueAfter `maMinus` (valueBefore `maPlus` cashFlowAmt))
, T.pack $ printf "%0.2f%%" $ smallIsZero irr
, T.pack $ printf "%0.2f%%" $ smallIsZero twr ]
let table = Table
(Tab.Group Tab.NoLine (map (Header . T.pack . show) (take (length tableBody) [1..])))
(Tab.Group Tab.DoubleLine
[ Tab.Group Tab.SingleLine [Header "Begin", Header "End"]
, Tab.Group Tab.SingleLine [Header "Value (begin)", Header "Cashflow", Header "Value (end)", Header "PnL"]
, Tab.Group Tab.SingleLine [Header "IRR", Header "TWR"]])
tableBody
TL.putStrLn $ Tab.render prettyTables id id id table
timeWeightedReturn showCashFlow prettyTables investmentsQuery trans mixedAmountValue (OneSpan spanBegin spanEnd valueBeforeAmt valueAfter cashFlow pnl) = do
let valueBefore = unMix valueBeforeAmt
let initialUnitPrice = 100 :: Decimal
let initialUnits = valueBefore / initialUnitPrice
let changes =
-- If cash flow and PnL changes happen on the same day, this
-- will sort PnL changes to come before cash flows (on any
-- given day), so that we will have better unit price computed
-- first for processing cash flow. This is why pnl changes are Left
-- and cashflows are Right.
-- However, if the very first date in the changes list has both
-- PnL and CashFlow, we would not be able to apply pnl change to 0 unit,
-- which would lead to an error. We make sure that we have at least one
-- cashflow entry at the front, and we know that there would be at most
-- one for the given date, by construction.
zeroUnitsNeedsCashflowAtTheFront
$ sort
$ datedCashflows ++ datedPnls
where
zeroUnitsNeedsCashflowAtTheFront changes =
if initialUnits > 0 then changes
else
let (leadingPnls, rest) = span (isLeft . snd) changes
(firstCashflow, rest') = splitAt 1 rest
in firstCashflow ++ leadingPnls ++ rest'
datedPnls = map (second Left) $ aggregateByDate pnl
datedCashflows = map (second Right) $ aggregateByDate cashFlow
aggregateByDate datedAmounts =
-- Aggregate all entries for a single day, assuming that intraday interest is negligible
sort
$ map (\date_cash -> let (dates, cash) = unzip date_cash in (head dates, maSum cash))
$ groupBy ((==) `on` fst)
$ sortOn fst
$ map (second maNegate)
$ datedAmounts
let units =
tail $
scanl
(\(_, _, unitPrice, unitBalance) (date, amt) ->
let valueOnDate = unMix $ mixedAmountValue spanEnd date $ total trans (And [investmentsQuery, Date (DateSpan Nothing (Just date))])
in
case amt of
Right amt ->
-- we are buying or selling
let unitsBoughtOrSold = unMix amt / unitPrice
in (valueOnDate, unitsBoughtOrSold, unitPrice, unitBalance + unitsBoughtOrSold)
Left pnl ->
-- PnL change
let valueAfterDate = valueOnDate + unMix pnl
unitPrice' = valueAfterDate/unitBalance
in (valueOnDate, 0, unitPrice', unitBalance))
(0, 0, initialUnitPrice, initialUnits)
$ dbg3 "changes" changes
let finalUnitBalance = if null units then initialUnits else let (_,_,_,u) = last units in u
finalUnitPrice = if finalUnitBalance == 0 then
if null units then initialUnitPrice
else let (_,_,lastUnitPrice,_) = last units in lastUnitPrice
else (unMix valueAfter) / finalUnitBalance
-- Technically, totalTWR should be (100*(finalUnitPrice - initialUnitPrice) / initialUnitPrice), but initalUnitPrice is 100, so 100/100 == 1
totalTWR = roundTo 2 $ (finalUnitPrice - initialUnitPrice)
years = fromIntegral (diffDays spanEnd spanBegin) / 365 :: Double
annualizedTWR = 100*((1+(realToFrac totalTWR/100))**(1/years)-1) :: Double
when showCashFlow $ do
printf "\nTWR cash flow for %s - %s\n" (showDate spanBegin) (showDate (addDays (-1) spanEnd))
let (dates', amounts) = unzip changes
cashflows' = map (fromRight nullmixedamt) amounts
pnls = map (fromLeft nullmixedamt) amounts
(valuesOnDate,unitsBoughtOrSold', unitPrices', unitBalances') = unzip4 units
add x lst = if valueBefore/=0 then x:lst else lst
dates = add spanBegin dates'
cashflows = add valueBeforeAmt cashflows'
unitsBoughtOrSold = add initialUnits unitsBoughtOrSold'
unitPrices = add initialUnitPrice unitPrices'
unitBalances = add initialUnits unitBalances'
TL.putStr $ Tab.render prettyTables id id T.pack
(Table
(Tab.Group NoLine (map (Header . showDate) dates))
(Tab.Group DoubleLine [ Tab.Group Tab.SingleLine [Tab.Header "Portfolio value", Tab.Header "Unit balance"]
, Tab.Group Tab.SingleLine [Tab.Header "Pnl", Tab.Header "Cashflow", Tab.Header "Unit price", Tab.Header "Units"]
, Tab.Group Tab.SingleLine [Tab.Header "New Unit Balance"]])
[ [value, oldBalance, pnl, cashflow, prc, udelta, balance]
| value <- map showDecimal valuesOnDate
| oldBalance <- map showDecimal (0:unitBalances)
| balance <- map showDecimal unitBalances
| pnl <- map showMixedAmount pnls
| cashflow <- map showMixedAmount cashflows
| prc <- map showDecimal unitPrices
| udelta <- map showDecimal unitsBoughtOrSold ])
printf "Final unit price: %s/%s units = %s\nTotal TWR: %s%%.\nPeriod: %.2f years.\nAnnualized TWR: %.2f%%\n\n"
(showMixedAmount valueAfter) (showDecimal finalUnitBalance) (showDecimal finalUnitPrice) (showDecimal totalTWR) years annualizedTWR
return annualizedTWR
internalRateOfReturn showCashFlow prettyTables (OneSpan spanBegin spanEnd valueBefore valueAfter cashFlow _pnl) = do
let prefix = (spanBegin, maNegate valueBefore)
postfix = (spanEnd, valueAfter)
totalCF = filter (maIsNonZero . snd) $ prefix : (sortOn fst cashFlow) ++ [postfix]
when showCashFlow $ do
printf "\nIRR cash flow for %s - %s\n" (showDate spanBegin) (showDate (addDays (-1) spanEnd))
let (dates, amounts) = unzip totalCF
TL.putStrLn $ Tab.render prettyTables id id id
(Table
(Tab.Group Tab.NoLine (map (Header . showDate) dates))
(Tab.Group Tab.SingleLine [Header "Amount"])
(map ((:[]) . T.pack . showMixedAmount) amounts))
-- 0% is always a solution, so require at least something here
case totalCF of
[] -> return 0
_ -> case ridders (RiddersParam 100 (AbsTol 0.00001))
(0.000000000001,10000)
(interestSum spanEnd totalCF) of
Root rate -> return ((rate-1)*100)
NotBracketed -> error' $ "Error (NotBracketed): No solution for Internal Rate of Return (IRR).\n"
++ " Possible causes: IRR is huge (>1000000%), balance of investment becomes negative at some point in time."
SearchFailed -> error' $ "Error (SearchFailed): Failed to find solution for Internal Rate of Return (IRR).\n"
++ " Either search does not converge to a solution, or converges too slowly."
type CashFlow = [(Day, MixedAmount)]
interestSum :: Day -> CashFlow -> Double -> Double
interestSum referenceDay cf rate = sum $ map go cf
where go (t,m) = realToFrac (unMix m) * rate ** (fromIntegral (referenceDay `diffDays` t) / 365)
calculateCashFlow :: WhichDate -> [Transaction] -> Query -> CashFlow
calculateCashFlow wd trans query =
[ (postingDateOrDate2 wd p, pamount p) | p <- filter (matchesPosting query) (concatMap realPostings trans), maIsNonZero (pamount p) ]
total :: [Transaction] -> Query -> MixedAmount
total trans query = sumPostings . filter (matchesPosting query) $ concatMap realPostings trans
unMix :: MixedAmount -> Quantity
unMix a =
case (unifyMixedAmount $ mixedAmountCost a) of
Just a -> aquantity a
Nothing -> error' $ "Amounts could not be converted to a single cost basis: " ++ show (map showAmount $ amounts a) ++
"\nConsider using --value to force all costs to be in a single commodity." ++
"\nFor example, \"--cost --value=end,<commodity> --infer-market-prices\", where commodity is the one that was used to pay for the investment."
-- Show Decimal rounded to two decimal places, unless it has less places already. This ensures that "2" won't be shown as "2.00"
showDecimal :: Decimal -> String
showDecimal d = if d == rounded then show d else show rounded
where
rounded = roundTo 2 d
|
simonmichael/hledger
|
hledger/Hledger/Cli/Commands/Roi.hs
|
gpl-3.0
| 13,971 | 39 | 29 | 3,590 | 3,405 | 1,762 | 1,643 | 229 | 7 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.Route53Domains.GetDomainDetail
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | This operation returns detailed information about the domain. The domain's
-- contact information is also returned as part of the output.
--
-- <http://docs.aws.amazon.com/Route53/latest/APIReference/api-GetDomainDetail.html>
module Network.AWS.Route53Domains.GetDomainDetail
(
-- * Request
GetDomainDetail
-- ** Request constructor
, getDomainDetail
-- ** Request lenses
, gddDomainName
-- * Response
, GetDomainDetailResponse
-- ** Response constructor
, getDomainDetailResponse
-- ** Response lenses
, gddrAbuseContactEmail
, gddrAbuseContactPhone
, gddrAdminContact
, gddrAdminPrivacy
, gddrAutoRenew
, gddrCreationDate
, gddrDnsSec
, gddrDomainName
, gddrExpirationDate
, gddrNameservers
, gddrRegistrantContact
, gddrRegistrantPrivacy
, gddrRegistrarName
, gddrRegistrarUrl
, gddrRegistryDomainId
, gddrReseller
, gddrStatusList
, gddrTechContact
, gddrTechPrivacy
, gddrUpdatedDate
, gddrWhoIsServer
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.Route53Domains.Types
import qualified GHC.Exts
newtype GetDomainDetail = GetDomainDetail
{ _gddDomainName :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'GetDomainDetail' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'gddDomainName' @::@ 'Text'
--
getDomainDetail :: Text -- ^ 'gddDomainName'
-> GetDomainDetail
getDomainDetail p1 = GetDomainDetail
{ _gddDomainName = p1
}
-- | The name of a domain.
--
-- Type: String
--
-- Default: None
--
-- Constraints: The domain name can contain only the letters a through z, the
-- numbers 0 through 9, and hyphen (-). Internationalized Domain Names are not
-- supported.
--
-- Required: Yes
gddDomainName :: Lens' GetDomainDetail Text
gddDomainName = lens _gddDomainName (\s a -> s { _gddDomainName = a })
data GetDomainDetailResponse = GetDomainDetailResponse
{ _gddrAbuseContactEmail :: Maybe Text
, _gddrAbuseContactPhone :: Maybe Text
, _gddrAdminContact :: ContactDetail
, _gddrAdminPrivacy :: Maybe Bool
, _gddrAutoRenew :: Maybe Bool
, _gddrCreationDate :: Maybe POSIX
, _gddrDnsSec :: Maybe Text
, _gddrDomainName :: Text
, _gddrExpirationDate :: Maybe POSIX
, _gddrNameservers :: List "Nameservers" Nameserver
, _gddrRegistrantContact :: ContactDetail
, _gddrRegistrantPrivacy :: Maybe Bool
, _gddrRegistrarName :: Maybe Text
, _gddrRegistrarUrl :: Maybe Text
, _gddrRegistryDomainId :: Maybe Text
, _gddrReseller :: Maybe Text
, _gddrStatusList :: List "StatusList" Text
, _gddrTechContact :: ContactDetail
, _gddrTechPrivacy :: Maybe Bool
, _gddrUpdatedDate :: Maybe POSIX
, _gddrWhoIsServer :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'GetDomainDetailResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'gddrAbuseContactEmail' @::@ 'Maybe' 'Text'
--
-- * 'gddrAbuseContactPhone' @::@ 'Maybe' 'Text'
--
-- * 'gddrAdminContact' @::@ 'ContactDetail'
--
-- * 'gddrAdminPrivacy' @::@ 'Maybe' 'Bool'
--
-- * 'gddrAutoRenew' @::@ 'Maybe' 'Bool'
--
-- * 'gddrCreationDate' @::@ 'Maybe' 'UTCTime'
--
-- * 'gddrDnsSec' @::@ 'Maybe' 'Text'
--
-- * 'gddrDomainName' @::@ 'Text'
--
-- * 'gddrExpirationDate' @::@ 'Maybe' 'UTCTime'
--
-- * 'gddrNameservers' @::@ ['Nameserver']
--
-- * 'gddrRegistrantContact' @::@ 'ContactDetail'
--
-- * 'gddrRegistrantPrivacy' @::@ 'Maybe' 'Bool'
--
-- * 'gddrRegistrarName' @::@ 'Maybe' 'Text'
--
-- * 'gddrRegistrarUrl' @::@ 'Maybe' 'Text'
--
-- * 'gddrRegistryDomainId' @::@ 'Maybe' 'Text'
--
-- * 'gddrReseller' @::@ 'Maybe' 'Text'
--
-- * 'gddrStatusList' @::@ ['Text']
--
-- * 'gddrTechContact' @::@ 'ContactDetail'
--
-- * 'gddrTechPrivacy' @::@ 'Maybe' 'Bool'
--
-- * 'gddrUpdatedDate' @::@ 'Maybe' 'UTCTime'
--
-- * 'gddrWhoIsServer' @::@ 'Maybe' 'Text'
--
getDomainDetailResponse :: Text -- ^ 'gddrDomainName'
-> ContactDetail -- ^ 'gddrAdminContact'
-> ContactDetail -- ^ 'gddrRegistrantContact'
-> ContactDetail -- ^ 'gddrTechContact'
-> GetDomainDetailResponse
getDomainDetailResponse p1 p2 p3 p4 = GetDomainDetailResponse
{ _gddrDomainName = p1
, _gddrAdminContact = p2
, _gddrRegistrantContact = p3
, _gddrTechContact = p4
, _gddrNameservers = mempty
, _gddrAutoRenew = Nothing
, _gddrAdminPrivacy = Nothing
, _gddrRegistrantPrivacy = Nothing
, _gddrTechPrivacy = Nothing
, _gddrRegistrarName = Nothing
, _gddrWhoIsServer = Nothing
, _gddrRegistrarUrl = Nothing
, _gddrAbuseContactEmail = Nothing
, _gddrAbuseContactPhone = Nothing
, _gddrRegistryDomainId = Nothing
, _gddrCreationDate = Nothing
, _gddrUpdatedDate = Nothing
, _gddrExpirationDate = Nothing
, _gddrReseller = Nothing
, _gddrDnsSec = Nothing
, _gddrStatusList = mempty
}
-- | Email address to contact to report incorrect contact information for a
-- domain, to report that the domain is being used to send spam, to report that
-- someone is cybersquatting on a domain name, or report some other type of
-- abuse.
--
-- Type: String
gddrAbuseContactEmail :: Lens' GetDomainDetailResponse (Maybe Text)
gddrAbuseContactEmail =
lens _gddrAbuseContactEmail (\s a -> s { _gddrAbuseContactEmail = a })
-- | Phone number for reporting abuse.
--
-- Type: String
gddrAbuseContactPhone :: Lens' GetDomainDetailResponse (Maybe Text)
gddrAbuseContactPhone =
lens _gddrAbuseContactPhone (\s a -> s { _gddrAbuseContactPhone = a })
-- | Provides details about the domain administrative contact.
--
-- Type: Complex
--
-- Children: 'FirstName', 'MiddleName', 'LastName', 'ContactType', 'OrganizationName', 'AddressLine1', 'AddressLine2', 'City', 'State', 'CountryCode', 'ZipCode', 'PhoneNumber', 'Email', 'Fax', 'ExtraParams'
gddrAdminContact :: Lens' GetDomainDetailResponse ContactDetail
gddrAdminContact = lens _gddrAdminContact (\s a -> s { _gddrAdminContact = a })
-- | Specifies whether contact information for the admin contact is concealed from
-- WHOIS queries. If the value is 'true', WHOIS ("who is") queries will return
-- contact information for our registrar partner, Gandi, instead of the contact
-- information that you enter.
--
-- Type: Boolean
gddrAdminPrivacy :: Lens' GetDomainDetailResponse (Maybe Bool)
gddrAdminPrivacy = lens _gddrAdminPrivacy (\s a -> s { _gddrAdminPrivacy = a })
-- | Specifies whether the domain registration is set to renew automatically.
--
-- Type: Boolean
gddrAutoRenew :: Lens' GetDomainDetailResponse (Maybe Bool)
gddrAutoRenew = lens _gddrAutoRenew (\s a -> s { _gddrAutoRenew = a })
-- | The date when the domain was created as found in the response to a WHOIS
-- query. The date format is Unix time.
gddrCreationDate :: Lens' GetDomainDetailResponse (Maybe UTCTime)
gddrCreationDate = lens _gddrCreationDate (\s a -> s { _gddrCreationDate = a }) . mapping _Time
-- | Reserved for future use.
gddrDnsSec :: Lens' GetDomainDetailResponse (Maybe Text)
gddrDnsSec = lens _gddrDnsSec (\s a -> s { _gddrDnsSec = a })
-- | The name of a domain.
--
-- Type: String
gddrDomainName :: Lens' GetDomainDetailResponse Text
gddrDomainName = lens _gddrDomainName (\s a -> s { _gddrDomainName = a })
-- | The date when the registration for the domain is set to expire. The date
-- format is Unix time.
gddrExpirationDate :: Lens' GetDomainDetailResponse (Maybe UTCTime)
gddrExpirationDate =
lens _gddrExpirationDate (\s a -> s { _gddrExpirationDate = a })
. mapping _Time
-- | The name of the domain.
--
-- Type: String
gddrNameservers :: Lens' GetDomainDetailResponse [Nameserver]
gddrNameservers = lens _gddrNameservers (\s a -> s { _gddrNameservers = a }) . _List
-- | Provides details about the domain registrant.
--
-- Type: Complex
--
-- Children: 'FirstName', 'MiddleName', 'LastName', 'ContactType', 'OrganizationName', 'AddressLine1', 'AddressLine2', 'City', 'State', 'CountryCode', 'ZipCode', 'PhoneNumber', 'Email', 'Fax', 'ExtraParams'
gddrRegistrantContact :: Lens' GetDomainDetailResponse ContactDetail
gddrRegistrantContact =
lens _gddrRegistrantContact (\s a -> s { _gddrRegistrantContact = a })
-- | Specifies whether contact information for the registrant contact is concealed
-- from WHOIS queries. If the value is 'true', WHOIS ("who is") queries will
-- return contact information for our registrar partner, Gandi, instead of the
-- contact information that you enter.
--
-- Type: Boolean
gddrRegistrantPrivacy :: Lens' GetDomainDetailResponse (Maybe Bool)
gddrRegistrantPrivacy =
lens _gddrRegistrantPrivacy (\s a -> s { _gddrRegistrantPrivacy = a })
-- | Name of the registrar of the domain as identified in the registry. Amazon
-- Route 53 domains are registered by registrar Gandi. The value is '"GANDI SAS"'.
--
-- Type: String
gddrRegistrarName :: Lens' GetDomainDetailResponse (Maybe Text)
gddrRegistrarName =
lens _gddrRegistrarName (\s a -> s { _gddrRegistrarName = a })
-- | Web address of the registrar.
--
-- Type: String
gddrRegistrarUrl :: Lens' GetDomainDetailResponse (Maybe Text)
gddrRegistrarUrl = lens _gddrRegistrarUrl (\s a -> s { _gddrRegistrarUrl = a })
-- | Reserved for future use.
gddrRegistryDomainId :: Lens' GetDomainDetailResponse (Maybe Text)
gddrRegistryDomainId =
lens _gddrRegistryDomainId (\s a -> s { _gddrRegistryDomainId = a })
-- | Reseller of the domain. Domains registered or transferred using Amazon Route
-- 53 domains will have '"Amazon"' as the reseller.
--
-- Type: String
gddrReseller :: Lens' GetDomainDetailResponse (Maybe Text)
gddrReseller = lens _gddrReseller (\s a -> s { _gddrReseller = a })
-- | An array of domain name status codes, also known as Extensible Provisioning
-- Protocol (EPP) status codes.
--
-- ICANN, the organization that maintains a central database of domain names,
-- has developed a set of domain name status codes that tell you the status of a
-- variety of operations on a domain name, for example, registering a domain
-- name, transferring a domain name to another registrar, renewing the
-- registration for a domain name, and so on. All registrars use this same set
-- of status codes.
--
-- For a current list of domain name status codes and an explanation of what
-- each code means, go to the <https://www.icann.org/ ICANN website> and search for 'epp status codes'.
-- (Search on the ICANN website; web searches sometimes return an old version of
-- the document.)
--
-- Type: Array of String
gddrStatusList :: Lens' GetDomainDetailResponse [Text]
gddrStatusList = lens _gddrStatusList (\s a -> s { _gddrStatusList = a }) . _List
-- | Provides details about the domain technical contact.
--
-- Type: Complex
--
-- Children: 'FirstName', 'MiddleName', 'LastName', 'ContactType', 'OrganizationName', 'AddressLine1', 'AddressLine2', 'City', 'State', 'CountryCode', 'ZipCode', 'PhoneNumber', 'Email', 'Fax', 'ExtraParams'
gddrTechContact :: Lens' GetDomainDetailResponse ContactDetail
gddrTechContact = lens _gddrTechContact (\s a -> s { _gddrTechContact = a })
-- | Specifies whether contact information for the tech contact is concealed from
-- WHOIS queries. If the value is 'true', WHOIS ("who is") queries will return
-- contact information for our registrar partner, Gandi, instead of the contact
-- information that you enter.
--
-- Type: Boolean
gddrTechPrivacy :: Lens' GetDomainDetailResponse (Maybe Bool)
gddrTechPrivacy = lens _gddrTechPrivacy (\s a -> s { _gddrTechPrivacy = a })
-- | The last updated date of the domain as found in the response to a WHOIS
-- query. The date format is Unix time.
gddrUpdatedDate :: Lens' GetDomainDetailResponse (Maybe UTCTime)
gddrUpdatedDate = lens _gddrUpdatedDate (\s a -> s { _gddrUpdatedDate = a }) . mapping _Time
-- | The fully qualified name of the WHOIS server that can answer the WHOIS query
-- for the domain.
--
-- Type: String
gddrWhoIsServer :: Lens' GetDomainDetailResponse (Maybe Text)
gddrWhoIsServer = lens _gddrWhoIsServer (\s a -> s { _gddrWhoIsServer = a })
instance ToPath GetDomainDetail where
toPath = const "/"
instance ToQuery GetDomainDetail where
toQuery = const mempty
instance ToHeaders GetDomainDetail
instance ToJSON GetDomainDetail where
toJSON GetDomainDetail{..} = object
[ "DomainName" .= _gddDomainName
]
instance AWSRequest GetDomainDetail where
type Sv GetDomainDetail = Route53Domains
type Rs GetDomainDetail = GetDomainDetailResponse
request = post "GetDomainDetail"
response = jsonResponse
instance FromJSON GetDomainDetailResponse where
parseJSON = withObject "GetDomainDetailResponse" $ \o -> GetDomainDetailResponse
<$> o .:? "AbuseContactEmail"
<*> o .:? "AbuseContactPhone"
<*> o .: "AdminContact"
<*> o .:? "AdminPrivacy"
<*> o .:? "AutoRenew"
<*> o .:? "CreationDate"
<*> o .:? "DnsSec"
<*> o .: "DomainName"
<*> o .:? "ExpirationDate"
<*> o .:? "Nameservers" .!= mempty
<*> o .: "RegistrantContact"
<*> o .:? "RegistrantPrivacy"
<*> o .:? "RegistrarName"
<*> o .:? "RegistrarUrl"
<*> o .:? "RegistryDomainId"
<*> o .:? "Reseller"
<*> o .:? "StatusList" .!= mempty
<*> o .: "TechContact"
<*> o .:? "TechPrivacy"
<*> o .:? "UpdatedDate"
<*> o .:? "WhoIsServer"
|
romanb/amazonka
|
amazonka-route53-domains/gen/Network/AWS/Route53Domains/GetDomainDetail.hs
|
mpl-2.0
| 14,842 | 0 | 51 | 3,055 | 2,019 | 1,210 | 809 | 188 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sq-AL">
<title>SOAP Scanner | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/soap/src/main/javahelp/org/zaproxy/zap/extension/soap/resources/help_sq_AL/helpset_sq_AL.hs
|
apache-2.0
| 974 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
module Test.Machine.Heap (tests) where
import Data.Text.Prettyprint.Doc
import Stg.Language.Prettyprint
import qualified Stg.Machine.Heap as Heap
import Stg.Machine.Types
import Test.Orphans ()
import Test.Tasty
import Test.Tasty.QuickCheck
tests :: TestTree
tests = testGroup "Heap"
[ testProperty "Lookup single inserted item"
(\closure heap ->
let (addr, heap') = Heap.alloc closure heap
in Heap.lookup addr heap' === Just closure )
, testProperty "Heap grows with allocated elements"
(\heap closures ->
let (_addrs, heap') = Heap.allocMany closures heap
in Heap.size heap' === Heap.size heap + length closures )
, testProperty "Update heap overwrites old values"
(\closure1 closure2 heap ->
let (addr1, heap1) = Heap.alloc closure1 heap
heap2 = Heap.update (Mapping addr1 closure2) heap1
in counterexample (show (prettyStgi heap2 :: Doc StgiAnn)
<> "\ndoes not contain "
<> show (prettyStgi closure2 :: Doc StgiAnn))
(Heap.lookup addr1 heap2 == Just closure2) )
, testProperty "Lookup many inserted items" (\closures heap ->
let (addrs, heap') = Heap.allocMany closures heap
in traverse (\addr -> Heap.lookup addr heap') addrs
==
Just closures
)
]
|
quchen/stg
|
test/Testsuite/Test/Machine/Heap.hs
|
bsd-3-clause
| 1,470 | 0 | 18 | 479 | 393 | 205 | 188 | 31 | 1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ru-RU">
<title>Расширенный сканер SQLInjection </title>
<maps>
<homeID>sqliplugin</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Содержание</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Индекс</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Поиск</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Избранное</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
kingthorin/zap-extensions
|
addOns/sqliplugin/src/main/javahelp/help_ru_RU/helpset_ru_RU.hs
|
apache-2.0
| 1,033 | 77 | 66 | 158 | 495 | 248 | 247 | -1 | -1 |
-- Simple example demonstrating the syntax - semantic interplay: search and print definitions
module Main where
import System.Environment ; import System.FilePath
import System.IO
import Control.Arrow ; import Control.Monad
import Control.Applicative
import Debug.Trace
import Data.Maybe
import Data.Map (Map) ; import qualified Data.Map as Map
import Data.Set (Set) ; import qualified Data.Set as Set
import Data.Generics
import Language.C -- simple API
import Language.C.Analysis -- analysis API
import Language.C.System.GCC -- preprocessor used
main :: IO ()
main = do
let usage = error "Example Usage: ./ShowDef '((struct|union|enum) tagname|typename|objectname)' -I/usr/include my_file.c"
args <- getArgs
when (length args < 2) usage
-- get cpp options and input file
let (searchterm:args') = args
let (opts,c_file) = (init &&& last) args'
-- parse
ast <- parseCFile (newGCC "gcc") Nothing opts c_file
>>= checkResult "[parsing]"
(globals,_warnings) <- (runTrav_ >>> checkResult "[analysis]") $ analyseAST ast
let defId = searchDef globals searchterm
-- traverse the AST and print decls which match
case defId of
Nothing -> print "Not found"
Just def_id -> printDecl def_id ast
where
checkResult :: (Show a) => String -> (Either a b) -> IO b
checkResult label = either (error . (label++) . show) return
printDecl def_id (CTranslUnit decls _) =
let decls' = filter (maybe False (posFile (posOfNode def_id) ==).fileOfNode) decls in
mapM_ (printIfMatch def_id) (zip decls' (map Just (tail decls') ++ [Nothing]))
printIfMatch def (decl,Just next_decl) | posOfNode def >= posOf decl &&
posOfNode def < posOf next_decl = (print . pretty) decl
| otherwise = return ()
printIfMatch def (decl, Nothing) | posOfNode def >= posOf decl = (print . pretty) decl
| otherwise = return ()
searchDef globs term =
case analyseSearchTerm term of
Left tag -> fmap nodeInfo (Map.lookup tag (gTags globs))
Right ident -> fmap nodeInfo (Map.lookup ident (gObjs globs))
<|> fmap nodeInfo (Map.lookup ident (gTypeDefs globs))
<|> fmap nodeInfo (Map.lookup (NamedRef ident) (gTags globs))
analyseSearchTerm term =
case words term of
[tag,name] | tag `elem` (words "struct union enum") -> Left $ NamedRef (internalIdent name)
[ident] -> Right (internalIdent ident)
_ -> error "bad search term"
|
llelf/language-c
|
examples/SearchDef.hs
|
bsd-3-clause
| 2,659 | 13 | 22 | 725 | 814 | 413 | 401 | 48 | 6 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
-- | Build the project.
module Stack.Build
(build
,withLoadPackage
,mkBaseConfigOpts
,queryBuildInfo)
where
import Control.Monad
import Control.Monad.Catch (MonadCatch, MonadMask)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (MonadReader, asks)
import Control.Monad.Trans.Resource
import Data.Aeson (Value (Object, Array), (.=), object)
import Data.Function
import qualified Data.HashMap.Strict as HM
import Data.IORef.RunOnce (runOnce)
import Data.List ((\\))
import Data.List.Extra (groupSort)
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as Map
import Data.Map.Strict (Map)
import Data.Monoid
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8)
import qualified Data.Text.IO as TIO
import Data.Text.Read (decimal)
import qualified Data.Vector as V
import qualified Data.Yaml as Yaml
import Network.HTTP.Client.Conduit (HasHttpManager)
import Path
import Prelude hiding (FilePath, writeFile)
import Stack.Build.ConstructPlan
import Stack.Build.Execute
import Stack.Build.Haddock
import Stack.Build.Installed
import Stack.Build.Source
import Stack.Build.Target
import Stack.Fetch as Fetch
import Stack.GhcPkg
import Stack.Package
import Stack.Types
import Stack.Types.Internal
import System.FileLock (FileLock, unlockFile)
#ifdef WINDOWS
import System.Win32.Console (setConsoleCP, setConsoleOutputCP, getConsoleCP, getConsoleOutputCP)
import qualified Control.Monad.Catch as Catch
#endif
type M env m = (MonadIO m,MonadReader env m,HasHttpManager env,HasBuildConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,MonadMask m,HasLogLevel env,HasEnvConfig env,HasTerminal env)
-- | Build.
--
-- If a buildLock is passed there is an important contract here. That lock must
-- protect the snapshot, and it must be safe to unlock it if there are no further
-- modifications to the snapshot to be performed by this build.
build :: M env m
=> (Set (Path Abs File) -> IO ()) -- ^ callback after discovering all local files
-> Maybe FileLock
-> BuildOpts
-> m ()
build setLocalFiles mbuildLk bopts = fixCodePage $ do
menv <- getMinimalEnvOverride
(_, mbp, locals, extraToBuild, sourceMap) <- loadSourceMap NeedTargets bopts
-- Set local files, necessary for file watching
stackYaml <- asks $ bcStackYaml . getBuildConfig
liftIO $ setLocalFiles
$ Set.insert stackYaml
$ Set.unions
$ map lpFiles locals
(installedMap, globalDumpPkgs, snapshotDumpPkgs, localDumpPkgs) <-
getInstalled menv
GetInstalledOpts
{ getInstalledProfiling = profiling
, getInstalledHaddock = shouldHaddockDeps bopts }
sourceMap
baseConfigOpts <- mkBaseConfigOpts bopts
plan <- withLoadPackage menv $ \loadPackage ->
constructPlan mbp baseConfigOpts locals extraToBuild localDumpPkgs loadPackage sourceMap installedMap
-- If our work to do is all local, let someone else have a turn with the snapshot.
-- They won't damage what's already in there.
case (mbuildLk, allLocal plan) of
-- NOTE: This policy is too conservative. In the future we should be able to
-- schedule unlocking as an Action that happens after all non-local actions are
-- complete.
(Just lk,True) -> do $logDebug "All installs are local; releasing snapshot lock early."
liftIO $ unlockFile lk
_ -> return ()
warnIfExecutablesWithSameNameCouldBeOverwritten locals plan
when (boptsPreFetch bopts) $
preFetch plan
if boptsDryrun bopts
then printPlan plan
else executePlan menv bopts baseConfigOpts locals
globalDumpPkgs
snapshotDumpPkgs
localDumpPkgs
installedMap
plan
where
profiling = boptsLibProfile bopts || boptsExeProfile bopts
-- | If all the tasks are local, they don't mutate anything outside of our local directory.
allLocal :: Plan -> Bool
allLocal =
all (== Local) .
map taskLocation .
Map.elems .
planTasks
-- | See https://github.com/commercialhaskell/stack/issues/1198.
warnIfExecutablesWithSameNameCouldBeOverwritten
:: MonadLogger m => [LocalPackage] -> Plan -> m ()
warnIfExecutablesWithSameNameCouldBeOverwritten locals plan =
forM_ (Map.toList warnings) $ \(exe,(toBuild,otherLocals)) -> do
let exe_s
| length toBuild > 1 = "several executables with the same name:"
| otherwise = "executable"
exesText pkgs =
T.intercalate
", "
["'" <> packageNameText p <> ":" <> exe <> "'" | p <- pkgs]
($logWarn . T.unlines . concat)
[ [ "Building " <> exe_s <> " " <> exesText toBuild <> "." ]
, [ "Only one of them will be available via 'stack exec' or locally installed."
| length toBuild > 1
]
, [ "Other executables with the same name might be overwritten: " <>
exesText otherLocals <> "."
| not (null otherLocals)
]
]
where
-- Cases of several local packages having executables with the same name.
-- The Map entries have the following form:
--
-- executable name: ( package names for executables that are being built
-- , package names for other local packages that have an
-- executable with the same name
-- )
warnings :: Map Text ([PackageName],[PackageName])
warnings =
Map.mapMaybe
(\(pkgsToBuild,localPkgs) ->
case (pkgsToBuild,NE.toList localPkgs \\ NE.toList pkgsToBuild) of
(_ :| [],[]) ->
-- We want to build the executable of single local package
-- and there are no other local packages with an executable of
-- the same name. Nothing to warn about, ignore.
Nothing
(_,otherLocals) ->
-- We could be here for two reasons (or their combination):
-- 1) We are building two or more executables with the same
-- name that will end up overwriting each other.
-- 2) In addition to the executable(s) that we want to build
-- there are other local packages with an executable of the
-- same name that might get overwritten.
-- Both cases warrant a warning.
Just (NE.toList pkgsToBuild,otherLocals))
(Map.intersectionWith (,) exesToBuild localExes)
exesToBuild :: Map Text (NonEmpty PackageName)
exesToBuild =
collect
[ (exe,pkgName)
| (pkgName,task) <- Map.toList (planTasks plan)
, isLocal task
, exe <- (Set.toList . exeComponents . lpComponents . taskLP) task
]
where
isLocal Task{taskType = (TTLocal _)} = True
isLocal _ = False
taskLP Task{taskType = (TTLocal lp)} = lp
taskLP _ = error "warnIfExecutablesWithSameNameCouldBeOverwritten/taskLP: task isn't local"
localExes :: Map Text (NonEmpty PackageName)
localExes =
collect
[ (exe,packageName pkg)
| pkg <- map lpPackage locals
, exe <- Set.toList (packageExes pkg)
]
collect :: Ord k => [(k,v)] -> Map k (NonEmpty v)
collect = Map.map NE.fromList . Map.fromDistinctAscList . groupSort
-- | Get the @BaseConfigOpts@ necessary for constructing configure options
mkBaseConfigOpts :: (MonadIO m, MonadReader env m, HasEnvConfig env, MonadThrow m)
=> BuildOpts -> m BaseConfigOpts
mkBaseConfigOpts bopts = do
snapDBPath <- packageDatabaseDeps
localDBPath <- packageDatabaseLocal
snapInstallRoot <- installationRootDeps
localInstallRoot <- installationRootLocal
packageExtraDBs <- packageDatabaseExtra
return BaseConfigOpts
{ bcoSnapDB = snapDBPath
, bcoLocalDB = localDBPath
, bcoSnapInstallRoot = snapInstallRoot
, bcoLocalInstallRoot = localInstallRoot
, bcoBuildOpts = bopts
, bcoExtraDBs = packageExtraDBs
}
-- | Provide a function for loading package information from the package index
withLoadPackage :: ( MonadIO m
, HasHttpManager env
, MonadReader env m
, MonadBaseControl IO m
, MonadCatch m
, MonadLogger m
, HasEnvConfig env)
=> EnvOverride
-> ((PackageName -> Version -> Map FlagName Bool -> IO Package) -> m a)
-> m a
withLoadPackage menv inner = do
econfig <- asks getEnvConfig
withCabalLoader' <- runOnce $ withCabalLoader menv $ \cabalLoader ->
inner $ \name version flags -> do
bs <- cabalLoader $ PackageIdentifier name version -- TODO automatically update index the first time this fails
-- Intentionally ignore warnings, as it's not really
-- appropriate to print a bunch of warnings out while
-- resolving the package index.
(_warnings,pkg) <- readPackageBS (depPackageConfig econfig flags) bs
return pkg
withCabalLoader'
where
-- | Package config to be used for dependencies
depPackageConfig :: EnvConfig -> Map FlagName Bool -> PackageConfig
depPackageConfig econfig flags = PackageConfig
{ packageConfigEnableTests = False
, packageConfigEnableBenchmarks = False
, packageConfigFlags = flags
, packageConfigCompilerVersion = envConfigCompilerVersion econfig
, packageConfigPlatform = configPlatform (getConfig econfig)
}
-- | Set the code page for this process as necessary. Only applies to Windows.
-- See: https://github.com/commercialhaskell/stack/issues/738
fixCodePage :: M env m => m a -> m a
#ifdef WINDOWS
fixCodePage inner = do
mcp <- asks $ configModifyCodePage . getConfig
ec <- asks getEnvConfig
if mcp && getGhcVersion (envConfigCompilerVersion ec) < $(mkVersion "7.10.3")
then fixCodePage'
-- GHC >=7.10.3 doesn't need this code page hack.
else inner
where
fixCodePage' = do
origCPI <- liftIO getConsoleCP
origCPO <- liftIO getConsoleOutputCP
let setInput = origCPI /= expected
setOutput = origCPO /= expected
fixInput
| setInput = Catch.bracket_
(liftIO $ do
setConsoleCP expected)
(liftIO $ setConsoleCP origCPI)
| otherwise = id
fixOutput
| setInput = Catch.bracket_
(liftIO $ do
setConsoleOutputCP expected)
(liftIO $ setConsoleOutputCP origCPO)
| otherwise = id
case (setInput, setOutput) of
(False, False) -> return ()
(True, True) -> warn ""
(True, False) -> warn " input"
(False, True) -> warn " output"
fixInput $ fixOutput inner
expected = 65001 -- UTF-8
warn typ = $logInfo $ T.concat
[ "Setting"
, typ
, " codepage to UTF-8 (65001) to ensure correct output from GHC"
]
#else
fixCodePage = id
#endif
-- | Query information about the build and print the result to stdout in YAML format.
queryBuildInfo :: M env m
=> [Text] -- ^ selectors
-> m ()
queryBuildInfo selectors0 =
rawBuildInfo
>>= select id selectors0
>>= liftIO . TIO.putStrLn . decodeUtf8 . Yaml.encode
where
select _ [] value = return value
select front (sel:sels) value =
case value of
Object o ->
case HM.lookup sel o of
Nothing -> err "Selector not found"
Just value' -> cont value'
Array v ->
case decimal sel of
Right (i, "")
| i >= 0 && i < V.length v -> cont $ v V.! i
| otherwise -> err "Index out of range"
_ -> err "Encountered array and needed numeric selector"
_ -> err $ "Cannot apply selector to " ++ show value
where
cont = select (front . (sel:)) sels
err msg = error $ msg ++ ": " ++ show (front [sel])
-- | Get the raw build information object
rawBuildInfo :: M env m => m Value
rawBuildInfo = do
(_, _mbp, locals, _extraToBuild, _sourceMap) <- loadSourceMap NeedTargets defaultBuildOpts
return $ object
[ "locals" .= Object (HM.fromList $ map localToPair locals)
]
where
localToPair lp =
(T.pack $ packageNameString $ packageName p, value)
where
p = lpPackage lp
value = object
[ "version" .= packageVersion p
, "path" .= toFilePath (lpDir lp)
]
|
harendra-kumar/stack
|
src/Stack/Build.hs
|
bsd-3-clause
| 14,033 | 7 | 20 | 4,539 | 2,840 | 1,520 | 1,320 | 224 | 6 |
module T13600b where
f ! (Just x) = f !! x
f ! y = head f
x = [1,2,3] ! Just 1
where
f ! (Just x) = f !! x
f ! y = head f
|
sdiehl/ghc
|
testsuite/tests/parser/should_compile/T13600b.hs
|
bsd-3-clause
| 134 | 0 | 9 | 50 | 97 | 48 | 49 | 6 | 2 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
module T12102 where
import Data.Kind
import GHC.TypeLits
type family IsTypeLit a where
IsTypeLit Nat = 'True
IsTypeLit Symbol = 'True
IsTypeLit a = 'False
data T :: forall a. (IsTypeLit a ~ 'True) => a -> Type where
MkNat :: T 42
MkSymbol :: T "Don't panic!"
|
sdiehl/ghc
|
testsuite/tests/typecheck/should_fail/T12102.hs
|
bsd-3-clause
| 402 | 0 | 9 | 88 | 103 | 59 | 44 | -1 | -1 |
{-# LANGUAGE Safe #-}
{-# LANGUAGE CPP #-}
#ifdef __GLASGOW_HASKELL__
{-# LANGUAGE ForeignFunctionInterface #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : System.Mem
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Memory-related system things.
--
-----------------------------------------------------------------------------
module System.Mem (
performGC -- :: IO ()
) where
import Prelude
#ifdef __HUGS__
import Hugs.IOExts
#endif
#ifdef __GLASGOW_HASKELL__
-- | Triggers an immediate garbage collection
foreign import ccall {-safe-} "performMajorGC" performGC :: IO ()
#endif
#ifdef __NHC__
import NHC.IOExtras (performGC)
#endif
|
beni55/haste-compiler
|
libraries/ghc-7.8/base/System/Mem.hs
|
bsd-3-clause
| 887 | 2 | 7 | 134 | 75 | 55 | 20 | 5 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.