code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
--
-- Code generation for profiling
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
module StgCmmProf (
initCostCentres, ccType, ccsType,
mkCCostCentre, mkCCostCentreStack,
-- Cost-centre Profiling
dynProfHdr, profDynAlloc, profAlloc, staticProfHdr, initUpdFrameProf,
enterCostCentreThunk, enterCostCentreFun,
costCentreFrom,
curCCS, storeCurCCS,
emitSetCCC,
saveCurrentCostCentre, restoreCurrentCostCentre,
-- Lag/drag/void stuff
ldvEnter, ldvEnterClosure, ldvRecordCreate
) where
#include "HsVersions.h"
import StgCmmClosure
import StgCmmUtils
import StgCmmMonad
import SMRep
import MkGraph
import Cmm
import CmmUtils
import CLabel
import qualified Module
import CostCentre
import DynFlags
import FastString
import Module
import Outputable
import Control.Monad
import Data.Char (ord)
-----------------------------------------------------------------------------
--
-- Cost-centre-stack Profiling
--
-----------------------------------------------------------------------------
-- Expression representing the current cost centre stack
ccsType :: DynFlags -> CmmType -- Type of a cost-centre stack
ccsType = bWord
ccType :: DynFlags -> CmmType -- Type of a cost centre
ccType = bWord
curCCS :: CmmExpr
curCCS = CmmReg (CmmGlobal CCCS)
storeCurCCS :: CmmExpr -> CmmAGraph
storeCurCCS e = mkAssign (CmmGlobal CCCS) e
mkCCostCentre :: CostCentre -> CmmLit
mkCCostCentre cc = CmmLabel (mkCCLabel cc)
mkCCostCentreStack :: CostCentreStack -> CmmLit
mkCCostCentreStack ccs = CmmLabel (mkCCSLabel ccs)
costCentreFrom :: DynFlags
-> CmmExpr -- A closure pointer
-> CmmExpr -- The cost centre from that closure
costCentreFrom dflags cl = CmmLoad (cmmOffsetB dflags cl (oFFSET_StgHeader_ccs dflags)) (ccsType dflags)
-- | The profiling header words in a static closure
staticProfHdr :: DynFlags -> CostCentreStack -> [CmmLit]
staticProfHdr dflags ccs
= ifProfilingL dflags [mkCCostCentreStack ccs, staticLdvInit dflags]
-- | Profiling header words in a dynamic closure
dynProfHdr :: DynFlags -> CmmExpr -> [CmmExpr]
dynProfHdr dflags ccs = ifProfilingL dflags [ccs, dynLdvInit dflags]
-- | Initialise the profiling field of an update frame
initUpdFrameProf :: CmmExpr -> FCode ()
initUpdFrameProf frame
= ifProfiling $ -- frame->header.prof.ccs = CCCS
do dflags <- getDynFlags
emitStore (cmmOffset dflags frame (oFFSET_StgHeader_ccs dflags)) curCCS
-- frame->header.prof.hp.rs = NULL (or frame-header.prof.hp.ldvw = 0)
-- is unnecessary because it is not used anyhow.
---------------------------------------------------------------------------
-- Saving and restoring the current cost centre
---------------------------------------------------------------------------
{- Note [Saving the current cost centre]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The current cost centre is like a global register. Like other
global registers, it's a caller-saves one. But consider
case (f x) of (p,q) -> rhs
Since 'f' may set the cost centre, we must restore it
before resuming rhs. So we want code like this:
local_cc = CCC -- save
r = f( x )
CCC = local_cc -- restore
That is, we explicitly "save" the current cost centre in
a LocalReg, local_cc; and restore it after the call. The
C-- infrastructure will arrange to save local_cc across the
call.
The same goes for join points;
let j x = join-stuff
in blah-blah
We want this kind of code:
local_cc = CCC -- save
blah-blah
J:
CCC = local_cc -- restore
-}
saveCurrentCostCentre :: FCode (Maybe LocalReg)
-- Returns Nothing if profiling is off
saveCurrentCostCentre
= do dflags <- getDynFlags
if not (gopt Opt_SccProfilingOn dflags)
then return Nothing
else do local_cc <- newTemp (ccType dflags)
emitAssign (CmmLocal local_cc) curCCS
return (Just local_cc)
restoreCurrentCostCentre :: Maybe LocalReg -> FCode ()
restoreCurrentCostCentre Nothing
= return ()
restoreCurrentCostCentre (Just local_cc)
= emit (storeCurCCS (CmmReg (CmmLocal local_cc)))
-------------------------------------------------------------------------------
-- Recording allocation in a cost centre
-------------------------------------------------------------------------------
-- | Record the allocation of a closure. The CmmExpr is the cost
-- centre stack to which to attribute the allocation.
profDynAlloc :: SMRep -> CmmExpr -> FCode ()
profDynAlloc rep ccs
= ifProfiling $
do dflags <- getDynFlags
profAlloc (mkIntExpr dflags (heapClosureSizeW dflags rep)) ccs
-- | Record the allocation of a closure (size is given by a CmmExpr)
-- The size must be in words, because the allocation counter in a CCS counts
-- in words.
profAlloc :: CmmExpr -> CmmExpr -> FCode ()
profAlloc words ccs
= ifProfiling $
do dflags <- getDynFlags
let alloc_rep = rEP_CostCentreStack_mem_alloc dflags
emit (addToMemE alloc_rep
(cmmOffsetB dflags ccs (oFFSET_CostCentreStack_mem_alloc dflags))
(CmmMachOp (MO_UU_Conv (wordWidth dflags) (typeWidth alloc_rep)) $
[CmmMachOp (mo_wordSub dflags) [words,
mkIntExpr dflags (profHdrSize dflags)]]))
-- subtract the "profiling overhead", which is the
-- profiling header in a closure.
-- -----------------------------------------------------------------------
-- Setting the current cost centre on entry to a closure
enterCostCentreThunk :: CmmExpr -> FCode ()
enterCostCentreThunk closure =
ifProfiling $ do
dflags <- getDynFlags
emit $ storeCurCCS (costCentreFrom dflags closure)
enterCostCentreFun :: CostCentreStack -> CmmExpr -> FCode ()
enterCostCentreFun ccs closure =
ifProfiling $ do
if isCurrentCCS ccs
then do dflags <- getDynFlags
emitRtsCall rtsPackageKey (fsLit "enterFunCCS")
[(CmmReg (CmmGlobal BaseReg), AddrHint),
(costCentreFrom dflags closure, AddrHint)] False
else return () -- top-level function, nothing to do
ifProfiling :: FCode () -> FCode ()
ifProfiling code
= do dflags <- getDynFlags
if gopt Opt_SccProfilingOn dflags
then code
else return ()
ifProfilingL :: DynFlags -> [a] -> [a]
ifProfilingL dflags xs
| gopt Opt_SccProfilingOn dflags = xs
| otherwise = []
---------------------------------------------------------------
-- Initialising Cost Centres & CCSs
---------------------------------------------------------------
initCostCentres :: CollectedCCs -> FCode ()
-- Emit the declarations
initCostCentres (local_CCs, ___extern_CCs, singleton_CCSs)
= do dflags <- getDynFlags
when (gopt Opt_SccProfilingOn dflags) $
do mapM_ emitCostCentreDecl local_CCs
mapM_ emitCostCentreStackDecl singleton_CCSs
emitCostCentreDecl :: CostCentre -> FCode ()
emitCostCentreDecl cc = do
{ dflags <- getDynFlags
; let is_caf | isCafCC cc = mkIntCLit dflags (ord 'c') -- 'c' == is a CAF
| otherwise = zero dflags
-- NB. bytesFS: we want the UTF-8 bytes here (#5559)
; label <- newByteStringCLit (bytesFS $ costCentreUserNameFS cc)
; modl <- newByteStringCLit (bytesFS $ Module.moduleNameFS
$ Module.moduleName
$ cc_mod cc)
; loc <- newByteStringCLit $ bytesFS $ mkFastString $
showPpr dflags (costCentreSrcSpan cc)
-- XXX going via FastString to get UTF-8 encoding is silly
; let
lits = [ zero dflags, -- StgInt ccID,
label, -- char *label,
modl, -- char *module,
loc, -- char *srcloc,
zero64, -- StgWord64 mem_alloc
zero64, -- StgDouble e_counter
zero dflags, -- StgWord time_ticks
is_caf, -- StgInt is_caf
zero dflags -- struct _CostCentre *link
]
; emitDataLits (mkCCLabel cc) lits
}
emitCostCentreStackDecl :: CostCentreStack -> FCode ()
emitCostCentreStackDecl ccs
= case maybeSingletonCCS ccs of
Just cc ->
do dflags <- getDynFlags
let mk_lits cc = zero dflags :
mkCCostCentre cc :
replicate (sizeof_ccs_words dflags - 2) (zero dflags)
-- Note: to avoid making any assumptions about how the
-- C compiler (that compiles the RTS, in particular) does
-- layouts of structs containing long-longs, simply
-- pad out the struct with zero words until we hit the
-- size of the overall struct (which we get via DerivedConstants.h)
emitDataLits (mkCCSLabel ccs) (mk_lits cc)
Nothing -> pprPanic "emitCostCentreStackDecl" (ppr ccs)
zero :: DynFlags -> CmmLit
zero dflags = mkIntCLit dflags 0
zero64 :: CmmLit
zero64 = CmmInt 0 W64
sizeof_ccs_words :: DynFlags -> Int
sizeof_ccs_words dflags
-- round up to the next word.
| ms == 0 = ws
| otherwise = ws + 1
where
(ws,ms) = sIZEOF_CostCentreStack dflags `divMod` wORD_SIZE dflags
-- ---------------------------------------------------------------------------
-- Set the current cost centre stack
emitSetCCC :: CostCentre -> Bool -> Bool -> FCode ()
emitSetCCC cc tick push
= do dflags <- getDynFlags
if not (gopt Opt_SccProfilingOn dflags)
then return ()
else do tmp <- newTemp (ccsType dflags) -- TODO FIXME NOW
pushCostCentre tmp curCCS cc
when tick $ emit (bumpSccCount dflags (CmmReg (CmmLocal tmp)))
when push $ emit (storeCurCCS (CmmReg (CmmLocal tmp)))
pushCostCentre :: LocalReg -> CmmExpr -> CostCentre -> FCode ()
pushCostCentre result ccs cc
= emitRtsCallWithResult result AddrHint
rtsPackageKey
(fsLit "pushCostCentre") [(ccs,AddrHint),
(CmmLit (mkCCostCentre cc), AddrHint)]
False
bumpSccCount :: DynFlags -> CmmExpr -> CmmAGraph
bumpSccCount dflags ccs
= addToMem (rEP_CostCentreStack_scc_count dflags)
(cmmOffsetB dflags ccs (oFFSET_CostCentreStack_scc_count dflags)) 1
-----------------------------------------------------------------------------
--
-- Lag/drag/void stuff
--
-----------------------------------------------------------------------------
--
-- Initial value for the LDV field in a static closure
--
staticLdvInit :: DynFlags -> CmmLit
staticLdvInit = zeroCLit
--
-- Initial value of the LDV field in a dynamic closure
--
dynLdvInit :: DynFlags -> CmmExpr
dynLdvInit dflags = -- (era << LDV_SHIFT) | LDV_STATE_CREATE
CmmMachOp (mo_wordOr dflags) [
CmmMachOp (mo_wordShl dflags) [loadEra dflags, mkIntExpr dflags (lDV_SHIFT dflags)],
CmmLit (mkWordCLit dflags (iLDV_STATE_CREATE dflags))
]
--
-- Initialise the LDV word of a new closure
--
ldvRecordCreate :: CmmExpr -> FCode ()
ldvRecordCreate closure = do dflags <- getDynFlags
emit $ mkStore (ldvWord dflags closure) (dynLdvInit dflags)
--
-- Called when a closure is entered, marks the closure as having been "used".
-- The closure is not an 'inherently used' one.
-- The closure is not IND or IND_OLDGEN because neither is considered for LDV
-- profiling.
--
ldvEnterClosure :: ClosureInfo -> CmmReg -> FCode ()
ldvEnterClosure closure_info node_reg = do
dflags <- getDynFlags
let tag = funTag dflags closure_info
-- don't forget to substract node's tag
ldvEnter (cmmOffsetB dflags (CmmReg node_reg) (-tag))
ldvEnter :: CmmExpr -> FCode ()
-- Argument is a closure pointer
ldvEnter cl_ptr = do
dflags <- getDynFlags
let -- don't forget to substract node's tag
ldv_wd = ldvWord dflags cl_ptr
new_ldv_wd = cmmOrWord dflags (cmmAndWord dflags (CmmLoad ldv_wd (bWord dflags))
(CmmLit (mkWordCLit dflags (iLDV_CREATE_MASK dflags))))
(cmmOrWord dflags (loadEra dflags) (CmmLit (mkWordCLit dflags (iLDV_STATE_USE dflags))))
ifProfiling $
-- if (era > 0) {
-- LDVW((c)) = (LDVW((c)) & LDV_CREATE_MASK) |
-- era | LDV_STATE_USE }
emit =<< mkCmmIfThenElse (CmmMachOp (mo_wordUGt dflags) [loadEra dflags, CmmLit (zeroCLit dflags)])
(mkStore ldv_wd new_ldv_wd)
mkNop
loadEra :: DynFlags -> CmmExpr
loadEra dflags = CmmMachOp (MO_UU_Conv (cIntWidth dflags) (wordWidth dflags))
[CmmLoad (mkLblExpr (mkCmmDataLabel rtsPackageKey (fsLit "era")))
(cInt dflags)]
ldvWord :: DynFlags -> CmmExpr -> CmmExpr
-- Takes the address of a closure, and returns
-- the address of the LDV word in the closure
ldvWord dflags closure_ptr
= cmmOffsetB dflags closure_ptr (oFFSET_StgHeader_ldvw dflags)
|
green-haskell/ghc
|
compiler/codeGen/StgCmmProf.hs
|
bsd-3-clause
| 13,435
| 0
| 18
| 3,380
| 2,518
| 1,302
| 1,216
| 206
| 2
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
{-
Copyright (C) 2004-2008 John Goerzen <jgoerzen@complete.org>
Copyright (C) 2015 David Farrell <shokku.ra@gmail.com>
-}
{-|
Module : Polar.ConfigFile
Copyright : Copyright (C) 2004-2008 John Goerzen, 2015 David Farrell
License : BSD3
Maintainer : David Farrell <shokku.ra@gmail.com>
Stability : unstable
Portability : non-portable (GHC extensions)
Configuration file parsing, generation, and manipulation
Copyright (C) 2004-2008 John Goerzen \<jgoerzen\@complete.org\>, 2015 David Farrell \<shokku.ra\@gmail.com\>.
This module contains extensive documentation. Please scroll down to the Introduction section to continue reading.
-}
module Polar.ConfigFile
(
-- * Introduction
-- $introduction
-- ** Features
-- $features
-- ** History
-- $history
-- * Configuration File Format
-- $format
-- ** White Space
-- $whitespace
-- ** Comments
-- $comments
-- ** Case Sensitivity
-- $casesens
-- ** Interpolation
-- $interpolation
-- * Usage Examples
-- $usage
-- ** Non-Monadic Usage
-- $usagenomonad
-- ** Error Monad Usage
-- $usageerrormonad
-- ** Combined Error\/IO Monad Usage
-- $usageerroriomonad
-- * Types
-- $types
SectionName, OptionName, ConfigParser(..),
ConfigErrorType(..), ConfigError,
-- * Initialization
-- $initialization
emptyCP,
-- * Building
-- $building
(|%|), (|$|), (|=|),
-- * Configuring the ConfigParser
-- $configuringcp
-- ** Access Functions
simpleAccess, interpolatingAccess,
-- * Reading
-- $reading
readFromFile, readFromHandle, readFromString,
-- * Accessing Data
OptionGetter(..),
sections, hasSection,
options, hasOption,
items,
-- * Modifying Data
set, setShow, removeOption,
addSection, removeSection,
merge,
-- * Output Data
toString
) where
import Polar.ConfigFile.Types
import Polar.ConfigFile.Parser
import Polar.ConfigFile.Utils
import qualified Data.Map as Map
import System.IO (Handle)
import Data.Char
import Control.Monad.Error
-- For interpolatingAccess
import Text.ParserCombinators.Parsec.Error (errorMessages, Message(..))
import Text.ParserCombinators.Parsec (parse)
----------------------------------------------------------------------
-- Basic types / default values
----------------------------------------------------------------------
{- | The default empty 'Polar.ConfigFile' object.
The content contains only an empty mandatory @DEFAULT@ section.
'optionNameTransform' is set to @map toLower@.
'useDefault' is set to @True@.
'accessFunction' is set to 'simpleAccess'.
-}
emptyCP :: ConfigParser
emptyCP = ConfigParser { content = fromAL [("DEFAULT", [])],
defaultHandler = defHandler,
optionNameTransform = map toLower,
useDefault = True,
accessFunction = simpleAccess}
class BuildConfig a where (|%|) :: a -> Section -> ConfigParser
instance BuildConfig ConfigParser where cp |%| (sect, opts) = cp { content = Map.insert sect opts (content cp) }
instance BuildConfig Section where sect1 |%| sect2 = emptyCP |%| sect1 |%| sect2
class BuildSection a where (|$|) :: a -> Option -> Section
instance BuildSection Section where (sect, opts) |$| (oName, oValue) = (sect, Map.insert oName oValue opts)
instance BuildSection SectionName where sect |$| (oName, oValue) = (sect, Map.singleton oName oValue)
(|=|) :: OptionName -> String -> Option
opt |=| val = (opt, val)
-- the list append function (++) has a precendence of 5
-- and should bind more tightly than these operators
infixl 2 |%|
infixl 3 |$|
infix 4 |=|
{- | Low-level tool to convert a parsed object into a 'Sections'
representation. Performs no option conversions or special handling
of @DEFAULT@. -}
fromAL :: ParseOutput -> Sections
fromAL origal =
let conv :: Sections -> (String, [(String, String)]) -> Sections
conv fm sect = Map.insert (fst sect) (Map.fromList $ snd sect) fm
in
foldl conv Map.empty origal
{- | Default (non-interpolating) access function -}
simpleAccess :: MonadError ConfigError m =>
ConfigParser -> SectionName -> OptionName -> m String
simpleAccess cp s o = defHandler cp s (optionNameTransform cp $ o)
{- | Interpolating access function. Please see the Interpolation section
above for a background on interpolation.
Although the format string looks similar to one used by "Text.Printf",
it is not the same. In particular, only the %(...)s format is supported.
No width specifiers are supported and no conversions other than s are supported.
To use this function, you must specify a maximum recursion depth for
interpolation. This is used to prevent a stack overflow in the event that
the configuration file contains an endless interpolation loop. Values of 10
or so are usually more than enough, though you could probably go into the
hundreds or thousands before you have actual problems.
A value less than one will cause an instant error every time you attempt
a lookup.
This access method can cause 'get' and friends to return a new 'ConfigError':
'InterpolationError'. This error would be returned when:
* The configuration file makes a reference to an option that does
not exist
* The maximum interpolation depth is exceeded
* There is a syntax error processing a %-directive in the configuration
file
An interpolation lookup name specifies an option only. There is no provision
to specify a section. Interpolation variables are looked up in the current
section, and, if 'useDefault' is True, in @DEFAULT@ according to the normal
logic.
To use a literal percent sign, you must place @%%@ in the configuration
file when interpolation is used.
Here is how you might enable interpolation:
>let cp2 = cp {accessFunction = interpolatingAccess 10}
The @cp2@ object will now support interpolation with a maximum depth of 10.
-}
interpolatingAccess :: MonadError ConfigError m =>
Int ->
ConfigParser -> SectionName -> OptionName
-> m String
interpolatingAccess maxdepth cp s o =
if maxdepth < 1
then interError "maximum interpolation depth exceeded"
else do x <- simpleAccess cp s o
case parse (interpMain $ lookupfunc) (s ++ "/" ++ o) x of
Left y -> case head (errorMessages y) of
Message z -> interError z
_ -> interError (show y)
Right y -> return y
where
lookupfunc = interpolatingAccess (maxdepth - 1) cp s
interError x = throwError (InterpolationError x, "interpolatingAccess")
-- internal function: default handler
defHandler :: MonadError ConfigError m =>
ConfigParser -> SectionName -> OptionName -> m String
defHandler cp sectn opt =
let fm = content cp
lookUp s o = do sect <- maybeToEither (NoSection s,
"get " ++ formatSO sectn opt) $
Map.lookup s fm
maybeToEither (NoOption o,
"get " ++ formatSO sectn opt) $
Map.lookup o sect
trydefault e = if (useDefault cp)
then
lookUp "DEFAULT" opt
-- Use original error if it's not in DEFAULT either
`catchError` (\_ -> throwError e)
else throwError e
in
lookUp sectn opt `catchError` trydefault
{- | Combines two 'ConfigParser's into one.
Any duplicate options are resolved to contain the value specified in
the second parser.
The 'ConfigParser' options in the resulting object will be set as they
are in the second one passed to this function. -}
merge :: ConfigParser -> ConfigParser -> ConfigParser
merge src dest =
let conv :: String -> String
conv = optionNameTransform dest
convFM :: Options -> Options
convFM = Map.fromList . map (\x -> (conv (fst x), snd x)) . Map.toList
mergesects a b = Map.union a b
in
dest { content = Map.unionWith mergesects
(content dest) (Map.map convFM (content src)) }
{- | Utility to do a special case merge. -}
readutil :: ConfigParser -> ParseOutput -> ConfigParser
readutil old new = merge old $ old { content = fromAL new }
{- | Loads data from the specified file. It is then combined with the
given 'ConfigParser' using the semantics documented under 'merge' with the
new data taking precedence over the old. However, unlike
'merge', all the options
as set in the old object are preserved since the on-disk representation
does not convey those options.
May return an error if there is a syntax error. May raise an exception if the file could not be accessed.
-}
--readFromFile :: ConfigParser -> FilePath ->IO (CPResult ConfigParser)
readFromFile :: MonadError ConfigError m => ConfigParser -> FilePath -> IO (m ConfigParser)
{-
readFromFile cp fp = do n <- parseFile fp
return $ do y <- n
return $ readutil cp y
-}
readFromFile cp fp = do n <- parseFile fp
return $ n >>= (return . readutil cp)
{- | Like 'readFromFile', but uses an already-open handle. You should
use 'readFromFile' instead of this if possible, since it will be able to
generate better error messages.
Errors would be returned on a syntax error.
-}
--readFromHandle :: ConfigParser -> Handle -> IO (CPResult ConfigParser)
readFromHandle :: MonadError ConfigError m => ConfigParser -> Handle -> IO (m ConfigParser)
readFromHandle cp h = do n <- parseHandle h
return $ n >>= (return . (readutil cp))
{- | Like 'readFromFile', but uses a string. You should use 'readFromFile'
instead of this if you are processing a file, since it can generate
better error messages.
Errors would be returned on a syntax error.
-}
readFromString :: MonadError ConfigError m =>
ConfigParser -> String -> m ConfigParser
readFromString cp s = do
n <- parseString s
return $ readutil cp n
{- | Returns a list of sections in your configuration file. Never includes
the always-present section @DEFAULT@. -}
sections :: ConfigParser -> [SectionName]
sections = filter (/= "DEFAULT") . Map.keys . content
{- | Indicates whether the given section exists.
No special @DEFAULT@ processing is done. -}
hasSection :: ConfigParser -> SectionName -> Bool
hasSection cp x = Map.member x (content cp)
{- | Adds the specified section name. Returns a
'SectionAlreadyExists' error if the
section was already present. Otherwise, returns the new
'ConfigParser' object.-}
addSection :: MonadError ConfigError m =>
ConfigParser -> SectionName -> m ConfigParser
addSection cp s =
if hasSection cp s
then throwError $ (SectionAlreadyExists s, "addSection")
else return $ cp {content = Map.insert s Map.empty (content cp)}
{- | Removes the specified section. Returns a 'NoSection' error if
the section does not exist; otherwise, returns the new 'ConfigParser'
object.
This call may not be used to remove the @DEFAULT@ section. Attempting to do
so will always cause a 'NoSection' error.
-}
removeSection :: MonadError ConfigError m =>
ConfigParser -> SectionName -> m ConfigParser
removeSection _ "DEFAULT" = throwError $ (NoSection "DEFAULT", "removeSection")
removeSection cp s =
if hasSection cp s
then return $ cp {content = Map.delete s (content cp)}
else throwError $ (NoSection s, "removeSection")
{- | Removes the specified option. Returns a 'NoSection' error if the
section does not exist and a 'NoOption' error if the option does not
exist. Otherwise, returns the new 'ConfigParser' object.
-}
removeOption :: MonadError ConfigError m =>
ConfigParser -> SectionName -> OptionName -> m ConfigParser
removeOption cp s passedo =
do sectmap <- maybeToEither (NoSection s,
"removeOption " ++ formatSO s passedo) $
Map.lookup s (content cp)
let o = (optionNameTransform cp) passedo
let newsect = Map.delete o sectmap
let newmap = Map.insert s newsect (content cp)
if Map.member o sectmap
then return $ cp {content = newmap}
else throwError $ (NoOption o,
"removeOption " ++ formatSO s passedo)
{- | Returns a list of the names of all the options present in the
given section.
Returns an error if the given section does not exist.
-}
options :: MonadError ConfigError m =>
ConfigParser -> SectionName -> m [OptionName]
options cp x = maybeToEither (NoSection x, "options") $
do
o <- Map.lookup x (content cp)
return $ Map.keys o
{- | Indicates whether the given option is present. Returns True
only if the given section is present AND the given option is present
in that section. No special @DEFAULT@ processing is done. No
exception could be raised or error returned.
-}
hasOption :: ConfigParser -> SectionName -> OptionName -> Bool
hasOption cp s o =
let c = content cp
v = do secthash <- Map.lookup s c
return $ Map.member (optionNameTransform cp $ o) secthash
in maybe False id v
{- | The class representing the data types that can be returned by "get".
-}
class OptionGetter a where
{- | Retrieves a string from the configuration file.
When used in a context where a String is expected, returns that string verbatim.
When used in a context where a Bool is expected, parses the string to
a Boolean value (see logic below).
When used in a context where anything that is an instance of Read is expected,
calls read to parse the item.
An error will be returned of no such option could be found or if it could
not be parsed as a boolean (when returning a Bool).
When parsing to a Bool, strings are case-insentively converted as follows:
The following will produce a True value:
* 1
* yes
* on
* enabled
* true
The following will produce a False value:
* 0
* no
* off
* disabled
* false -}
get :: MonadError ConfigError m => ConfigParser -> SectionName -> OptionName -> m a
instance {-# OVERLAPPABLE #-} Read t => OptionGetter t where
get = genericget
instance OptionGetter String where
get cp s o = eitherToMonadError $ (accessFunction cp) cp s o
instance OptionGetter Bool where
get = getbool
-- Based on code from Neil Mitchell's safe-0.3.3 package.
readMaybe :: Read a => String -> Maybe a
readMaybe s = case [x | (x, t) <- reads s, ("","") <- lex t] of
[x] -> Just x
_ -> Nothing
genericget :: (Read b, MonadError ConfigError m) => ConfigParser -> SectionName -> OptionName -> m b
genericget cp s o = do
val <- get cp s o
let errMsg = "couldn't parse value " ++ val ++ " from " ++ formatSO s o
maybe (throwError (ParseError errMsg, "genericget"))
return
$ readMaybe val
getbool :: MonadError ConfigError m =>
ConfigParser -> SectionName -> OptionName -> m Bool
getbool cp s o =
do val <- get cp s o
case map toLower . strip $ val of
"1" -> return True
"yes" -> return True
"on" -> return True
"enabled" -> return True
"true" -> return True
"0" -> return False
"no" -> return False
"off" -> return False
"disabled" -> return False
"false" -> return False
_ -> throwError (ParseError $ "couldn't parse bool " ++
val ++ " from " ++ formatSO s o, "getbool")
formatSO :: [Char] -> [Char] -> [Char]
formatSO s o =
"(" ++ s ++ "/" ++ o ++ ")"
{- | Returns a list of @(optionname, value)@ pairs representing the content
of the given section. Returns an error the section is invalid. -}
items :: MonadError ConfigError m =>
ConfigParser -> SectionName -> m [(OptionName, String)]
items cp s = do fm <- maybeToEither (NoSection s, "items") $
Map.lookup s (content cp)
return $ Map.toList fm
{- | Sets the option to a new value, replacing an existing one if it exists.
Returns an error if the section does not exist. -}
set :: MonadError ConfigError m =>
ConfigParser -> SectionName -> OptionName -> String -> m ConfigParser
set cp s passedo val =
do sectmap <- maybeToEither (NoSection s, "set " ++ formatSO s passedo) $
Map.lookup s (content cp)
let o = (optionNameTransform cp) passedo
let newsect = Map.insert o val sectmap
let newmap = Map.insert s newsect (content cp)
return $ cp { content = newmap}
{- | Sets the option to a new value, replacing an existing one if it exists.
It requires only a showable value as its parameter.
This can be used with bool values, as well as numeric ones.
Returns an error if the section does not exist. -}
setShow :: (Show a, MonadError ConfigError m) =>
ConfigParser -> SectionName -> OptionName -> a -> m ConfigParser
setShow cp s o val = set cp s o (show val)
{- | Converts the 'ConfigParser' to a string representation that could be
later re-parsed by this module or modified by a human.
Note that this does not necessarily re-create a file that was originally
loaded. Things may occur in a different order, comments will be removed,
etc. The conversion makes an effort to make the result human-editable,
but it does not make an effort to make the result identical to the original
input.
The result is, however, guaranteed to parse the same as the original input.
-}
toString :: ConfigParser -> String
toString cp =
let gen_option (key, value) =
key ++ ": " ++ (replace "\n" "\n " value) ++ "\n"
gen_section (sect, valfm) = -- gen a section, but omit DEFAULT if empty
if (sect /= "DEFAULT") || (Map.size valfm > 0)
then "[" ++ sect ++ "]\n" ++
(concat $ map gen_option (Map.toList valfm)) ++ "\n"
else ""
in
concat $ map gen_section (Map.toList (content cp))
----------------------------------------------------------------------
-- Docs
----------------------------------------------------------------------
{- $introduction
Many programs need configuration files. These configuration files are
typically used to configure certain runtime behaviours that need to be
saved across sessions. Various different configuration file formats
exist.
The ConfigParser module attempts to define a standard format that is
easy for the user to edit, easy for the programmer to work with, yet
powerful and flexible.
-}
{- $features
For the programmer, this module provides:
* Simple calls to both read /and write/ configuration files
* Call that can generate a string version of a file that is
re-parsable by this module (useful for, for instance, sending the
file down a network)
* Segmented configuration files that let you separate configuration
into distinct sections, each with its own namespace. This can be
used to configure multiple modules in one file, to configure
multiple instances of a single object, etc.
* On-the-fly parsing of integer, boolean, float, multi-line string values,
and anything else Haskell's read can deal with
* It is possible to make a configuration file parsable by this
module, the Unix shell, and\/or Unix make, though some features are,
of course, not compatible with these other tools.
* Syntax checking with error reporting including line numbers
* Implemented in pure Haskell. No dependencies on modules outside
the standard library distributed with Haskell compilers or interpreters.
All calls except those that read directly from a handle are pure calls
and can be used outside the IO monad.
* Comprehensive documentation
* Extensible API
For the user, this module provides:
* Easily human-editable configuration files with a clear, concise,
and consistent format
* Configuration file format consistent with other familiar formats
(\/etc\/passwd is a valid ConfigParser file)
* No need to understand semantics of markup languages like XML
-}
{- $history
This module is based on Python's ConfigParser module at
<http://www.python.org/doc/current/lib/module-ConfigParser.html>. I had
earlier developed an OCaml implementation as part of my MissingLib library
at <gopher://gopher.quux.org/devel/missinglib>.
While the API of these three modules is similar, and the aim is to preserve all
useful features of the original Python module, there are some differences
in the implementation details. This module is a complete, clean re-implementation
in Haskell, not a Haskell translation of a Python program. As such, the feature
set is slightly different.
/\-John Goerzen/
-}
{- $format
The basic configuration file format resembles that of an old-style
Windows .INI file. Here are two samples:
>debug = yes
>inputfile = /etc/passwd
>names = Peter, Paul, Mary, George, Abrahaham, John, Bill, Gerald, Richard,
> Franklin, Woodrow
>color = red
This defines a file without any explicit section, so all items will
occur within the default section @DEFAULT@. The @debug@ option can be read
as a boolean or a string. The remaining items can be read as a string
only. The @names@ entry spans two lines -- any line starting with
whitespace, and containing something other than whitespace or
comments, is taken as a continuation of the previous line.
Here's another example:
># Default options
>[DEFAULT]
>hostname: localhost
># Options for the first file
>[file1]
>location: /usr/local
>user: Fred
>uid: 1000
>optionaltext: Hello, this entire string is included
>[file2]
>location: /opt
>user: Fred
>uid: 1001
This file defines three sections. The @DEFAULT@ section specifies an
entry @hostname@. If you attempt to read the hostname option in any
section, and that section doesn't define @hostname@, you will get the
value from @DEFAULT@ instead. This is a nice time-saver. You can also
note that you can use colons instead of the = character to separate
option names from option entries.
-}
{- $whitespace
Whitespace (spaces, tabs, etc) is automatically stripped from the
beginning and end of all strings. Thus, users can insert whitespace
before\/after the colon or equal sign if they like, and it will be
automatically stripped.
Blank lines or lines consisting solely of whitespace are ignored.
A line giving an option or a section name may not begin with white space.
This requirement is necessary so there is no ambiguity between such lines
and continuation lines for multi-line options.
-}
{- $comments
Comments are introduced with the pound sign @#@ or the semicolon @;@. They
cause the parser to ignore everything from that character to the end
of the line.
Comments /may not/ occur within the definitions of options; that is, you
may not place a comment in the middle of a line such as @user: Fred@.
That is because the parser considers the comment characters part
of the string; otherwise, you'd be unable to use those characters in
your strings. You can, however, \"comment out\" options by putting the
comment character at the start of the line.
-}
{- $casesens
By default, section names are case-sensitive but option names are
not. The latter can be adjusted by adjusting 'optionNameTransform'. -}
{- $interpolation
Interpolation is an optional feature, disabled by default. If you replace
the default 'accessFunction' ('simpleAccess') with 'interpolatingAccess',
then you get interpolation support with 'get' and the other 'get'-based functions.
As an example, consider the following file:
>arch = i386
>project = test
>filename = test_%(arch)s.c
>dir = /usr/src/%(filename)s
>percent = 5%%
With interpolation, you would get these results:
>get cp "DEFAULT" "filename" -> "test_i386.c"
>get cp "DEFAULT" "dir" -> "/usr/src/test_i386.c"
>get cp "DEFAULT" "percent" -> "5%"
For more details on interpolation, please see the documentation for the
'interpolatingAccess' function.
-}
{- $usage
The basic theory of working with ConfigParser is this:
1. Parse or build a 'ConfigParser' object
2. Work with it in one of several ways
3. To make changes, you discard the original object and use a new one.
Changes can be "chained" through one of several monads.
The default 'ConfigParser' object that you always start with is 'emptyCP'.
From here, you load data into it (merging data into the empty object),
set up structures yourself, or adjust options.
Let's take a look at some basic use cases.
-}
{- $usagenomonad
You'll notice that many functions in this module return a
@MonadError 'ConfigError'@ over some
type. Although its definition is not this simple, you can consider this to be
the same as returning @Either ConfigError a@.
That is, these functions will return @Left error@ if there's a problem
or @Right result@ if things are fine. The documentation for individual
functions describes the specific circumstances in which an error may occur in
more detail.
Some people find it annoying to have to deal with errors manually.
You can transform errors into exceptions in your code by using
'Data.Either.Utils.forceEither'. Here's an example of this style of programming:
> import Data.Either.Utils
> do
> val <- readFromFile emptyCP "/etc/foo.cfg"
> let cp = forceEither val
> putStrLn "Your setting is:"
> putStrLn $ forceEither $ get cp "sect1" "opt1"
In short, you can just put @forceEither $@ in front of every call that returns
something that is a MonadError.
This is still a pure functional call, so it can be used outside
of the IO monads. The exception, however, can only be caught in the IO
monad.
If you don't want to bother with 'forceEither', you can use the error monad. It's simple and better... read on.
-}
{- $usageerrormonad
The return type is actually defined in terms of the Error monad, which is
itself based on the Either data type.
Here's a neat example of chaining together calls to build up a 'ConfigParser'
object:
>do let cp = emptyCP
> cp <- addSection cp "sect1"
> cp <- set cp "sect1" "opt1" "foo"
> cp <- set cp "sect1" "opt2" "bar"
> options cp "sect1"
The return value of this little snippet is @Right [\"opt1\", \"opt2\"]@.
(Note to beginners: unlike the IO monad, you /can/ escape from the Error
monad.)
Although it's not obvious, there actually was error checking there. If
any of those calls would have generated an error, processing would have
stopped immediately and a @Left@ value would have been returned. Consider
this example:
>do let cp = emptyCP
> cp <- addSection cp "sect1"
> cp <- set cp "sect1" "opt1" "foo"
> cp <- set cp "sect2" "opt2" "bar"
> options cp "sect1"
The return value from this is @Left ('NoSection' \"sect2\", \"set\")@. The
second call to 'set' failed, so the final call was skipped, and the result
of the entire computation was considered to be an error.
You can combine this with the non-monadic style to get a final, pure value
out of it:
>forceEither $ do let cp = emptyCP
> cp <- addSection cp "sect1"
> cp <- set cp "sect1" "opt1" "foo"
> cp <- set cp "sect1" "opt2" "bar"
> options cp "sect1"
This returns @[\"opt1\", \"opt2\"]@. A quite normal value.
-}
{- $usageerroriomonad
You've seen a nice way to use this module in the Error monad and get an Either
value out. But that's the Error monad, so IO is not permitted.
Using Haskell's monad transformers, you can run it in the combined
Error\/IO monad. That is, you will get an IO result back. Here is a full
standalone example of doing that:
>import Polar.ConfigFile
>import Control.Monad.Error
>
>main = do
> rv <- runErrorT $
> do
> cp <- join $ liftIO $ readFromFile emptyCP "/etc/passwd"
> let x = cp
> liftIO $ putStrLn "In the test"
> nb <- get x "DEFAULT" "nobody"
> liftIO $ putStrLn nb
> foo <- get x "DEFAULT" "foo"
> liftIO $ putStrLn foo
> return "done"
> print rv
On my system, this prints:
>In the test
>x:65534:65534:nobody:/nonexistent:/bin/sh
>Left (NoOption "foo","get")
That is, my @\/etc\/passwd@ file contains a @nobody@ user but not a @foo@ user.
Let's look at how that works.
First, @main@ always runs in the IO monad only, so we take the result from
the later calls and put it in @rv@. Note that the combined block
is started with @runErrorT $ do@ instead of just @do@.
To get something out of the call to 'readFromFile', we use
@join $ liftIO $ readFromFile@. This will bring the result out of the IO monad
into the combined monad and process it like usual. From here on,
everything looks normal, except for IO calls. They are all executed under
@liftIO@ so that the result value is properly brought into the combined
monad. This finally returns @\"done\"@. Since we are in the Error monad, that means that the literal value is @Right \"done\"@. Since we are also in the IO
monad, this is wrapped in IO. So the final return type after applying
@runErrorT@ is @IO (Either ConfigError String)@.
In this case, there was an error, and processing stopped at that point just
like the example of the pure Error monad. We print out the return value,
so you see the error displayed as a @Left@ value.
It all works quite easily.
-}
{- $configuringcp
You may notice that the 'ConfigParser' object has some configurable parameters,
such as 'useDefault'. In case you're not familiar with the Haskell syntax
for working with these, you can use syntax like this to set these options:
>let cp2 = cp { useDefault = False }
This will create a new 'ConfigParser' that is the same as @cp@ except for
the 'useDefault' field, which is now always False. The new object will be
called @cp2@ in this example.
-}
{- $reading
You can use these functions to read data from a file.
A common idiom for loading a new object from stratch is:
@cp <- 'readFromFile' 'emptyCP' \"\/etc\/foo.cfg\"@
Note the use of 'emptyCP'; this will essentially cause the file's data
to be merged with the empty 'ConfigParser'.
-}
{- $types
The code used to say this:
>type CPResult a = MonadError ConfigError m => m a
>simpleAccess :: ConfigParser -> SectionName -> OptionName -> CPResult String
But Hugs did not support that type declaration. Therefore, types are now
given like this:
>simpleAccess :: MonadError ConfigError m =>
> ConfigParser -> SectionName -> OptionName -> m String
Although it looks more confusing than before, it still means the same.
The return value can still be treated as @Either ConfigError String@ if you so
desire.
-}
|
polar-engine/polar-configfile
|
src/Polar/ConfigFile.hs
|
bsd-3-clause
| 31,365
| 0
| 17
| 7,440
| 3,255
| 1,700
| 1,555
| 214
| 11
|
{-
Joel Svensson
2010
-}
module DotProd where
import Obsidian
import Prelude hiding (foldr,zipWith)
import PureAPI
import Data.Foldable
import Data.Bits
--------------------------------------------------------------------------------
-- DotProducts
--------------------------------------------------------------------------------
zipWith f = pure (fmap f . zipp)
mult :: Num a => (Arr a, Arr a) :-> Arr a
mult = zipWith $ uncurry (*)
reduce :: Flatten a => Int -> (a -> a -> a) -> Arr a :-> Arr a
reduce 0 f = pure id
reduce n f = pure op ->- sync ->- reduce (n-1) f
where
op = fmap (uncurry f) . pair
reduce' :: Flatten a => Int -> (a -> a -> a) -> Arr a :-> Arr a
reduce' 0 f = pure id
reduce' n f = pure halve ->- zipWith (uncurry f) ->- sync ->- reduce' (n-1) f
dotProd :: Int -> (Arr FloatE, Arr FloatE) :-> Arr FloatE
dotProd n = mult ->- sync ->- reduce n (+)
dotProd2 :: Int -> (Arr FloatE, Arr FloatE) :-> Arr FloatE
dotProd2 n = mult ->- reduce n (+)
dotProd3 :: Int -> (Arr FloatE, Arr FloatE) :-> Arr FloatE
dotProd3 n = mult ->- add_once ->- reduce (n-1) (+)
where add_once = pure (fmap (uncurry (+)) . pair)
--------------------------------------------------------------------------------
-- wrapper
--------------------------------------------------------------------------------
wrapper prg = pure halve ->- prg
|
svenssonjoel/ArrowObsidian
|
Obsidian/ArrowObsidian/Examples/DotProd.hs
|
bsd-3-clause
| 1,393
| 0
| 12
| 279
| 511
| 263
| 248
| -1
| -1
|
module Chat where
import Chat.Bot.Ping
import Chat.Bot.Run.Guess
import Chat.Bot.Run.Cipher
import Chat.Bot.Run.Calculator
import Chat.Bot.Run.Hangman
import Chat.Bot.Run.TicTacToe
import Chat.Bot.Run.Vote
import Chat.Data
import Chat.Web
start :: IO ()
start = do
bots <- sequence [
guessBot
, return (toBot calculatorBot)
, return cipherBot
, ticTacToeBot
, return (toBot pingBot)
, voteBot
, hangmanBot
]
startChat bots
|
charleso/haskell-in-haste
|
src/Chat.hs
|
bsd-3-clause
| 554
| 0
| 12
| 184
| 135
| 80
| 55
| 21
| 1
|
module Data.Folds.Internal where
data Pair a b = Pair !a !b
|
Shimuuar/data-folds
|
Data/Folds/Internal.hs
|
bsd-3-clause
| 61
| 0
| 7
| 12
| 22
| 13
| 9
| 6
| 0
|
{-# OPTIONS_HADDOCK not-home #-}
-- | An interface with references that can be used internally while generating instances
-- for 'MMorph' and tuple lens classes.
--
-- Only the public parts of "Control.Reference.Representation" are exported.
--
-- For creating a new interface with different generated elements, use this internal interface.
--
module Control.Reference.InternalInterface
( bireference, reference, referenceWithClose
, module Control.Reference.Types
, module Control.Reference.Operators
, module Control.Reference.Combinators
, module Control.Reference.Predefined
, module Control.Reference.Generators
, module Control.Reference.Predefined.Containers
) where
import Control.Reference.Representation
import Control.Reference.Types
import Control.Reference.Operators
import Control.Reference.Combinators
import Control.Reference.Predefined
import Control.Reference.Generators
import Control.Reference.Predefined.Containers
|
nboldi/references
|
Control/Reference/InternalInterface.hs
|
bsd-3-clause
| 1,020
| 0
| 5
| 175
| 112
| 80
| 32
| 16
| 0
|
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE FlexibleContexts #-}
module Main where
import Diagrams.Prelude as D
import Diagrams.Backend.Reflex as DR
import Reflex as R
import Reflex.Dom as R
import Control.Concurrent
import GHCJS.DOM
import GHCJS.DOM.Document
import GHCJS.DOM.HTMLDocument
import GHCJS.DOM.HTMLElement
main :: IO ()
main = appMain app
app :: MonadWidget t m => m ()
app = mdo
-- svgDyn :: Dynamic t (m (DiaEv Any))
svgDyn <- mapDyn (reflexDia $ def & sizeSpec .~ dims2D 500 1000) diaDyn
-- pos :: Event (V2 Double)
pos <- switchPromptly never <$> fmap diaMousemovePos =<< dyn svgDyn
-- diaDyn :: Dynamic (Diagram B)
diaDyn <- holdDyn mempty (mkDia <$> pos)
return ()
-- TODO generalize and move into diagrams-lib
constrain :: (InSpace V2 Double a, Enveloped a) =>
a -> P2 Double -> P2 Double
constrain a p = maybe p c $ getCorners box where
c (l,h) = max l (min h p)
box = boundingBox a
mkDia :: P2 Double -> Diagram B
mkDia p = c <> bg where
c = moveTo (constrain bg p) (D.text "Hello") # fc green
bg = vcat [ square 1000 # fc cyan, square 1000 # fc yellow ]
------------------------------------------------------------------------------
waitUntilJust :: IO (Maybe a) -> IO a
waitUntilJust a = do
mx <- a
case mx of
Just x -> return x
Nothing -> do
threadDelay 10000
waitUntilJust a
------------------------------------------------------------------------------
-- | Launch a Reflex app when the page loads
appMain reflexApp = runWebGUI $ \webView -> do
doc <- waitUntilJust $ fmap (fmap castToHTMLDocument) $
webViewGetDomDocument webView
body <- waitUntilJust $ fmap (fmap castToHTMLElement) $ getBody doc
attachWidget body webView reflexApp
|
bergey/gooey
|
diagrams-reflex-follow/src/Main.hs
|
bsd-3-clause
| 1,808
| 0
| 14
| 416
| 540
| 271
| 269
| 42
| 2
|
module Hive.Console.Player
( player
, completion
) where
import Mitchell.Prelude
import Hive
import Prelude (String, read)
import System.Console.ANSI
import System.Console.Haskeline
import Text.Megaparsec
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Vector as Vector
player :: String -> Game -> Hive (InputT IO) ()
player name game0 = do
io $ do
putStrLn (pack ("To place a piece: " ++ colored White "place ant 0 1"))
putStrLn (pack ("To move a piece: " ++ colored White "move 2 3, 2 4, 3 4"))
loop game0
where
loop :: Game -> Hive (InputT IO) ()
loop game = do
io $ do
putStrLn ""
printBoard board
let prompt = colored (player2color player) (name ++ "> ")
lift (getInputLine prompt) >>= \case
Nothing -> do
putStrLn (pack (colored Red "Parse error."))
loop game
Just line ->
case runParser actionParser "" line of
Left _ -> do
putStrLn (pack (colored Red "Parse error."))
loop game
Right action -> do
result <- hiveAction action
case result of
Left err -> do
putStrLn (pack (colored Red (unpack (displayHiveError err))))
loop game
Right (GameOver winner) -> io (print winner)
Right (GameActive game') -> loop game'
where
board = gameBoard game
player = gamePlayer game
completion :: Monad m => CompletionFunc m
completion =
completeWord Nothing [' ']
(go [ ("ant", ["ant"])
, ("beetle", ["beetle"])
, ("grasshopper", ["grasshopper"])
, ("ladybug", ["ladybug"])
, ("mosquito", ["mosquito","move"])
, ("move", ["mosquito","move"])
, ("place", ["place"])
, ("queen", ["queen"])
, ("spider", ["spider"])
])
where
go [] _ = pure []
go ((w,w'):ws) s
| s `isPrefixOf` w = pure (map simpleCompletion w')
| otherwise = go ws s
actionParser :: Parsec Dec String Action
actionParser = placeParser <|> moveParser
where
placeParser :: Parsec Dec String Action
placeParser = do
_ <- string' "place"
space
bug <- bugParser
space
idx <- idxParser
pure (Place bug idx)
moveParser :: Parsec Dec String Action
moveParser = do
_ <- string' "move"
space
(x:xs) <- sepBy1 idxParser (space *> char ',' <* space)
pure (Move x (NonEmpty.fromList xs))
bugParser :: Parsec Dec String Bug
bugParser =
Ant <$ string' "ant"
<|> Beetle <$ string' "beetle"
<|> Grasshopper <$ string' "grasshopper"
<|> Ladybug <$ string' "ladybug"
<|> Mosquito <$ string' "mosquito"
<|> Spider <$ string' "spider"
<|> Queen <$ string' "queen"
idxParser :: Parsec Dec String BoardIndex
idxParser = do
row <- num
space
col <- num
pure (row, col)
where
num = read <$> some digitChar
printBoard :: Board -> IO ()
printBoard board = do
putStrLn (pack (colored White column_nums))
putStrLn (" " ++ pack (replicate (3 * (boardWidth board) - 2) '-'))
Vector.imapM_
printTwoRows
(Vector.map (split . Vector.toList . Vector.map cellToString) (boardTiles board))
where
column_nums :: String
column_nums =
" " ++ concatMap (printf "%-2d ")
(take (boardWidth board) [(0::Int)..])
printTwoRows :: Int -> ([String], [String]) -> IO ()
printTwoRows row (es, os)
| boardParity board == Even = do
unless (null os) $
putStrLn (pack (row_num ++ spaceFirst os))
unless (null es) $
putStrLn (pack (row_num ++ spaceSecond es))
| otherwise = do
unless (null es) $
putStrLn (pack (row_num ++ spaceSecond es))
unless (null os) $
putStrLn (pack (row_num ++ spaceFirst os))
where
row_num = colored White (printf "%2d|" row)
cellToString :: Cell -> String
cellToString [] = "·"
cellToString (Tile p bug : _) = colored (player2color p) [bug2char bug]
bug2char :: Bug -> Char
bug2char Ant = 'A'
bug2char Beetle = 'B'
bug2char Grasshopper = 'G'
bug2char Ladybug = 'L'
bug2char Mosquito = 'M'
bug2char Queen = 'Q'
bug2char Spider = 'S'
player2color :: Player -> Color
player2color P1 = Magenta
player2color P2 = Cyan
colored :: Color -> String -> String
colored c s = setSGRCode [SetColor Foreground Vivid c] ++ s ++ setSGRCode [Reset]
spaceFirst :: [String] -> String
spaceFirst [] = ""
spaceFirst (s:ss) = " " ++ s ++ spaceFirst' ss
spaceFirst' :: [String] -> String
spaceFirst' [] = ""
spaceFirst' (s:ss) = " " ++ s ++ spaceFirst' ss
spaceSecond :: [String] -> String
spaceSecond [] = ""
spaceSecond (s:ss) = s ++ " " ++ spaceSecond ss
split :: [a] -> ([a], [a])
split = go True ([], [])
where
go :: Bool -> ([a], [a]) -> [a] -> ([a], [a])
go _ (es, os) [] = (reverse es, reverse os)
go True (es, os) (x:xs) = go False (x:es, os) xs
go False (es, os) (x:xs) = go True (es, x:os) xs
|
mitchellwrosen/hive
|
hive-console/src/Hive/Console/Player.hs
|
bsd-3-clause
| 5,096
| 0
| 31
| 1,492
| 1,980
| 1,004
| 976
| -1
| -1
|
{-# LANGUAGE ExistentialQuantification #-}
module MonadPoint.Rendering where
import Control.Monad.State
import Control.Monad.Writer hiding (All)
import Data.IORef
import Data.List
import Data.Maybe
import Graphics.Rendering.OpenGL.Raw
import Graphics.Rendering.FTGL hiding (AlignLeft, AlignCenter, AlignRight)
import Graphics.UI.GLUT as GLUT hiding (Font)
import Codec.Image.STB as STB
import Data.Bitmap.IO
import qualified MonadPoint.Config as Config
--
defaultWindowSize = Size 800 600
fontSize = 128 :: Int
type Rendering a = StateT RenderState IO a
data RenderState =
RenderState
{
datDir :: String,
aspect :: Double, -- アスペクト比
font :: Font, -- フォント
fixFont :: Font, -- 等幅フォント
imgs :: [(String, TextureObject)], -- 画像
kmStat :: IORef KeyMouseState, -- キー・マウス情報
tick :: Double, -- ページ切り替え率
curPage :: Rendering (), -- PageData, -- 現在のページ
nextPage :: Maybe (Rendering ()), -- Maybe PageData, -- 遷移先ページ
direction :: Bool, -- 遷移方向
plugins :: [Rendering ()] -- プラグイン
}
data KeyMouseState =
KeyMouseState
{ prevKeys :: [Key]
, curKeys :: [Key]
}
kmProc stat key keyState mod pos = do
case keyState of
Down -> do
modifyIORef stat $ \s -> s { curKeys = curKeys s \\ [key] }
Up -> do
modifyIORef stat $ \s -> s { curKeys = nub $ key : curKeys s }
kmsIsKeyPress :: Key -> KeyMouseState -> Bool
kmsIsKeyPress k stat =
not (k`elem`prevKeys stat) && (k`elem`curKeys stat)
isKeyPress :: Key -> Rendering Bool
isKeyPress key = do
kmsr <- gets kmStat
kms <- liftIO $ readIORef kmsr
return $ kmsIsKeyPress key kms
initRenderState dir (Size w h) font ffont kmsr startPage =
RenderState
{ datDir = dir
, aspect = 600/800
, font = font
, fixFont = ffont
, imgs = []
, kmStat = kmsr
, tick = 0
, curPage = startPage
, nextPage = Nothing
, direction = False
, plugins = []
}
initRenderer :: Config.Config -> Rendering a -> IO RenderState
initRenderer cfg m = do
blend $= Enabled
-- blendEquation $= FuncAdd
blendFunc $= (SrcAlpha, OneMinusSrcAlpha)
textureFunction $= Replace
texture Texture2D $= Enabled
-- multisample $= Enabled
-- polygonSmooth $= Enabled
-- hint PolygonSmooth $= Nicest
let datdir = Config.datDir cfg ++ "/"
let pfont = Config.pFont cfg
let ffont = Config.fFont cfg
font <- createPolygonFont (datdir ++ pfont)
setFontFaceSize font fontSize fontSize
setFontDepth font 1.0
ffont <- createPolygonFont (datdir ++ ffont)
setFontFaceSize ffont fontSize fontSize
setFontDepth ffont 1.0
kmsr <- newIORef $ KeyMouseState [] []
return $ initRenderState datdir defaultWindowSize font ffont kmsr (m >> return ())
bg :: Double -> Rendering()
bg alpha = do
liftIO $ renderPrimitive Polygon $ do
color $ Color4 0.4 0.4 (0.6 :: GLdouble) (realToFrac alpha)
vertex $ Vertex2 ( 0) ( 0::GLdouble)
vertex $ Vertex2 ( 1) ( 0::GLdouble)
color $ Color4 0.1 0.1 (0.1 :: GLdouble) (realToFrac alpha)
vertex $ Vertex2 ( 1) ( 1::GLdouble)
vertex $ Vertex2 ( 0) ( 1::GLdouble)
renderPage :: Rendering ()
renderPage = do
liftIO $ clearColor $= Color4 0 0 0 0
liftIO $ clear [ColorBuffer]
Size ww hh <- liftIO $ GLUT.get windowSize
modify $ \s -> s { aspect = fromIntegral hh / fromIntegral ww }
liftIO $ loadIdentity
liftIO $ do
translate $ Vector3 (-1) (-1) (0 :: GLdouble)
scale 2.0 2.0 (1 :: GLdouble)
bg 1
cp <- gets curPage
np <- gets nextPage
d <- gets direction
case np of
Nothing -> do
cp
return ()
Just np -> do
tc <- gets tick
if d
then do
preserving $ do
transl (-tc*1) 0
cp
bg $ min 1 (tc*2)
preserving $ do
transl (1-tc*1) 0
np
bg $ min 1 (2-tc*2)
else do
preserving $ do
transl (-(1-tc)*1) 0
np
bg $ min 1 ((1-tc)*2)
preserving $ do
transl (1-(1-tc)*1) 0
cp
bg $ min 1 (2-(1-tc)*2)
if (tc+1/20>1)
then do
modify $ \s -> s { tick = 0, curPage = np, nextPage = Nothing }
else do
modify $ \s -> s { tick = tc+1/20 }
pins <- gets plugins
sequence_ pins
kmsr <- gets kmStat
kms <- liftIO $ readIORef kmsr
liftIO $ writeIORef kmsr $ kms { prevKeys = curKeys kms }
liftIO $ swapBuffers
class Page a where
render :: a -> Rendering ()
data PageData = forall a. (Page a) => PageData a
instance Page PageData where
render (PageData p) = render p
preserving :: Rendering a -> Rendering a
preserving m = do
a <- gets aspect
liftIO glPushMatrix
ret <- m
liftIO glPopMatrix
modify $ \s -> s { aspect = a }
return ret
scale2 :: Double -> Double -> Rendering ()
scale2 w h = do
liftIO $ scale (realToFrac w) (realToFrac h) (1 :: GLdouble)
modify $ \s -> s { aspect = aspect s * h / w }
transl :: Double -> Double -> Rendering ()
transl w h = do
liftIO $ translate $ Vector3 (realToFrac w) (realToFrac h) (0 :: GLdouble)
square :: IO a -> Rendering a
square m = do
a <- gets (realToFrac . aspect)
liftIO $ preservingMatrix $ do
scale a 1 (1 :: GLdouble)
m
getImage :: String -> Rendering TextureObject
getImage fname = do
is <- gets imgs
case lookup fname is of
Just tex -> return tex
Nothing -> do
datdir <- gets datDir
tex <- liftIO $ loadTexture (datdir ++ fname)
modify $ \s -> s { imgs = is ++ [(fname, tex)] }
return tex
loadTexture :: String -> IO TextureObject
loadTexture fname = do
rs <- loadImage fname
case rs of
Left err -> error err
Right img -> do
withBitmap img $ \(w, h) comp padding ptr -> do
-- print (w, h, comp)
[tex] <- genObjectNames 1
textureBinding Texture2D $= Just tex
textureWrapMode Texture2D S $= (Repeated, Repeat)
textureWrapMode Texture2D T $= (Repeated, Repeat)
textureFilter Texture2D $= ((Linear', Nothing), Linear')
texImage2D Nothing NoProxy 0 RGBA' (TextureSize2D (fromIntegral w) (fromIntegral h)) 0 $
PixelData (if comp==4 then RGBA else RGB) UnsignedByte ptr
return tex
changePage :: Rendering a -> Rendering ()
changePage p = do
np <- gets nextPage
when (isNothing np) $ do
modify $ \s -> s
{ tick = 0
, nextPage = Just $ p >> return ()
, direction = True
}
backwordPage :: Rendering a -> Rendering ()
backwordPage p = do
np <- gets nextPage
when (isNothing np) $ do
modify $ \s -> s
{ tick = 0
, nextPage = Just $ p >> return ()
, direction = False
}
installPlugin :: Rendering () -> Rendering ()
installPlugin p = do
modify $ \s -> s { plugins = p : plugins s }
|
tanakh/MonadPoint
|
src/MonadPoint/Rendering.hs
|
bsd-3-clause
| 7,158
| 0
| 24
| 2,152
| 2,631
| 1,330
| 1,301
| 206
| 4
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
module CategoryTheory where
import Prelude hiding (id, (.), (*))
id' :: a -> a
id' a = a
(*) :: (b -> c) -> (a -> b) -> (a -> c)
f * g = \x -> f (g x)
class Category cat where
id :: cat a a
(.) :: cat b c -> cat a b -> cat a c
instance Category (->) where
id :: (->) a a
id a = a
(.) :: (->) b c -> (->) a b -> (->) a c
f . g = \x -> f (g x)
newtype Kleisli m a b = Kleisli { runKleisli :: a -> m b }
instance Monad m => Category (Kleisli m) where
id :: (Kleisli m) a a
id = Kleisli pure
(.) :: (Kleisli m) b c -> (Kleisli m) a b -> (Kleisli m) a c
f . g = Kleisli (\x -> runKleisli g x >>= runKleisli f)
data Lens a b = Lens (a -> b) (a -> b -> a)
instance Category Lens where
id :: Lens a a
id = Lens id' (const id')
(.) :: Lens b c -> Lens a b -> Lens a c
Lens g1 s1 . Lens g2 s2 = Lens (g1 * g2) s3
where
s3 a c = s2 a (s1 (g2 a) c)
class (Category c, Category d) => Functor' c d f where
fmap' :: c a b -> d (f a) (f b)
instance Functor' (->) (->) Maybe where
fmap' _ Nothing = Nothing
fmap' f (Just a) = Just (f a)
newtype f :~> g = NT { unNT :: forall x. f x -> g x }
{--
instance Category (:~>) where
id :: a :~> a
id = NT id'
(.) :: (b :~> c) -> (a :~> b) -> (a :~> c)
NT f . NT g = NT (f * g)
--}
data (f :+: g) e = InL (f e) | InR (g e)
data Const a b = Const a
newtype Identity a = Identity { runIdentity :: a }
toMaybe :: (Const () :+: Identity) :~> Maybe
toMaybe = undefined
fromMaybe :: Maybe :~> (Const () :+: Identity)
fromMaybe = undefined
newtype Yoneda f a = Yoneda { runYoneda :: forall b. (a -> b) -> f b }
instance Functor (Yoneda f) where
fmap f m = Yoneda (\k -> runYoneda m (k . f))
liftYoneda :: Functor f => f a -> Yoneda f a
liftYoneda = undefined
lowerYoneda :: Yoneda f a -> f a
lowerYoneda = undefined
data CoYoneda f a where
CoYoneda :: (z -> a) -> f z -> CoYoneda f a
instance Functor (CoYoneda f) where
fmap f (CoYoneda g v) = CoYoneda (f * g) v
liftCoYoneda :: f a -> CoYoneda f a
liftCoYoneda = undefined
lowerCoYoneda :: Functor f => CoYoneda f a -> f a
lowerCoYoneda = undefined
-- covariant Yoneda
-- f a == forall b. (a -> b) -> f b
-- contravariant Yoneda
-- f a == exists b. (b -> a, f b)
-- covariant Coyoneda
-- f a == forall b. (b -> a) -> f b
-- contravariant Coyoneda
-- f a == exists b. (a -> b, f b)
class (Functor f, Functor u) => Adjunction f u where
unit :: a -> u (f a)
counit :: f (u a) -> a
leftAdjunct :: (f a -> b) -> a -> u b
rightAdjunct :: (a -> u b) -> f a -> b
unit = leftAdjunct id'
counit = rightAdjunct id'
leftAdjunct f = fmap f * unit
rightAdjunct f = counit * fmap f
-- Hom (AxB, C) == Hom (A, C^B)
instance Adjunction ((,) b) ((->) b) where
leftAdjunct :: ((b, a) -> c) -> a -> b -> c
leftAdjunct f a b = f (b, a)
rightAdjunct :: (a -> b -> c) -> (b, a) -> c
rightAdjunct f (b, a) = f a b
class (Functor' c d f, Functor' d c u) => Adjunction' c d f u where
leftAdjunct' :: d (f a) b -> c a (u b)
rightAdjunct' :: c a (u b) -> d (f a) b
instance Monad m => Functor' (->) (Kleisli m) Identity where
fmap' :: (a -> b) -> Kleisli m (Identity a) (Identity b)
fmap' f = Kleisli $ fmap Identity . (pure . f . runIdentity)
instance Monad m => Functor' (Kleisli m) (->) m where
fmap' :: Kleisli m a b -> m a -> m b
fmap' k = (=<<) (runKleisli k)
instance Monad m => Adjunction' (->) (Kleisli m) Identity m where
leftAdjunct' :: Kleisli m (Identity a) b -> a -> m b
leftAdjunct' k a = runKleisli k (Identity a)
rightAdjunct' :: (a -> m b) -> Kleisli m (Identity a) b
rightAdjunct' f = Kleisli $ f . runIdentity
newtype Ran g h a = Ran { runRan :: forall b. (a -> g b) -> h b }
yonedaToRan :: Yoneda f a -> Ran Identity f a
yonedaToRan = undefined
ranToYoneda :: Ran Identity f a -> Yoneda f a
ranToYoneda = undefined
data Lan g h a where
Lan :: (g b -> a) -> h b -> Lan g h a
{--
class Applicative m => Monad' m where
join :: m (m a) -> m a
join x = x `bind` id
bind :: m a -> (a -> m b) -> m b
m `bind` f = join (fmap f m)
return :: a -> m a
return = pure
--}
class Adjunction f u => Monad' f u where
return' :: a -> u (f a)
join' :: u (f (u (f a))) -> u (f a)
instance Monad' ((,) s) ((->) s) where
return' :: a -> (s -> (s, a))
return' a s = (s, a)
join' :: (s -> (s, (s -> (s, a)))) -> (s -> (s, a))
join' f s = f' s' where (s', f') = f s
class Functor w => Comonad w where
extract :: w a -> a
duplicate :: w a -> w (w a)
duplicate = extend id'
extend :: (w a -> b) -> w a -> w b
extend f = fmap f * duplicate
class Adjunction f u => Comonad' f u where
extract' :: f (u a) -> a
duplicate' :: f (u a) -> f (u (f (u a)))
instance Comonad' ((,) s) ((->) s) where
extract' :: (s, s -> a) -> a
extract' (s, f) = f s
duplicate' :: (s, s -> a) -> (s, s -> (s, s -> a))
duplicate' (s, f) = (s, \s -> (s, f))
|
cutsea110/aop
|
src/CategoryTheory.hs
|
bsd-3-clause
| 5,086
| 18
| 14
| 1,392
| 2,447
| 1,273
| 1,174
| 118
| 1
|
{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, TypeFamilies #-}
module HNN.Data (
load_mnist
, load_mnist_lazy
, makeleveldb
, leveldb_random_loader
, lazy_image_loader
, randomize
, map_pixels
, batch_images
, batch_to_gpu
, runEvery
, serializeTo
, random_crop
, timePipe
) where
import Foreign.C
import System.IO
import System.FilePath
import Vision.Image as Friday hiding (read)
import Vision.Primitive hiding (Shape)
import Vision.Image.Storage.DevIL
import Pipes hiding (Proxy)
import System.Directory
import Data.Maybe
import Control.Monad
import Control.Monad.ST
import Control.Monad.Random
import Foreign.Storable
import qualified Data.Vector.Storable as V
import qualified Data.Vector.Storable.Mutable as MV
import qualified Data.Vector as NSV
import qualified Data.Vector.Mutable as NSVM
import qualified Data.ByteString as B
import qualified Data.ByteString.Internal as BI
import Data.Serialize
import Data.Proxy
import qualified Data.Time as Time
import Data.IORef
import Control.DeepSeq
import Foreign.ForeignPtr
import qualified Database.LevelDB as LDB
import Control.Monad.Trans.Resource
import Control.Applicative
import HNN.Tensor as T
-- MonadRandom instance for ResourceT
instance MonadRandom m => MonadRandom (ResourceT m) where
getRandom = lift $ getRandom
getRandoms = lift $ getRandoms
getRandomR r = lift $ getRandomR r
getRandomRs r = lift $ getRandomRs r
vecToBstring :: forall a . (Storable a) => V.Vector a -> B.ByteString
vecToBstring vec =
let (afptr, o, l) = V.unsafeToForeignPtr vec
asize = sizeOf (undefined :: a)
bo = o * asize
bl = l * asize
in BI.fromForeignPtr (castForeignPtr afptr) bo bl
bstringToVec :: forall a . (Storable a) => B.ByteString -> Maybe (V.Vector a)
bstringToVec bstr =
let (bfptr, bo, bl) = BI.toForeignPtr bstr
asize = sizeOf (undefined :: a)
o = if bo `rem` asize == 0 then Just (bo `div` asize) else Nothing
l = if bl `rem` asize == 0 then Just (bl `div` asize) else Nothing
in pure (V.unsafeFromForeignPtr (castForeignPtr bfptr)) <*> o <*> l
-- Serializing for Friday image.
instance (Storable i)
=> Serialize (Manifest i) where
put (Manifest (Z:.w:.h) vec) = do
put w
put h
put $ vecToBstring vec
get = do
w <- get
h <- get
bstr <- get
case bstringToVec bstr of
Nothing -> error "Could not convert back to an image to data alignment issues."
Just vec -> return (Manifest (Z:.w:.h) vec)
load_mnist :: (Convertible StorageImage i)
=> FilePath -> IO [(i, Int)]
load_mnist directory = do
dirs <- getDirectoryContents directory >>= filterM (\d -> doesDirectoryExist $ directory </> d)
imgs <- forM dirs $ \classname -> do
imgfpaths <- getDirectoryContents (directory </> classname)
imgs' <- forM imgfpaths $ \imgfpath -> do
eimg <-load Autodetect $ directory </> classname </> imgfpath
case eimg of
Left err -> return Nothing
Right img -> return $ Just (img, read classname)
return imgs'
return $ fmap fromJust $ filter (\mi -> case mi of
Nothing -> False
_ -> True) $ Prelude.concat $ imgs
load_mnist_lazy :: (MonadIO m, Convertible StorageImage i)
=> FilePath -> Producer (i, Int) m ()
load_mnist_lazy directory = do
dirs <- liftIO $ getDirectoryContents directory >>= filterM (\d -> doesDirectoryExist $ directory </> d)
forM_ dirs $ \classname -> do
imgfpaths <- liftIO $ getDirectoryContents (directory </> classname)
forM_ imgfpaths $ \imgfpath -> do
eimg <- liftIO $ load Autodetect $ directory </> classname </> imgfpath
case eimg of
Left err -> do
liftIO $ do
putStrLn $ "Couldn't load image " ++ imgfpath
putStrLn $ "\t" ++ show err
return ()
Right img -> yield (img, read classname)
while :: (Monad m) => (m Bool) -> m b -> m [b]
while pred action = do
continue <- pred
if continue then do
x <- action
xs <- while pred action
return (x:xs)
else return []
makeleveldb :: forall k v m . (Serialize k, Serialize v, LDB.MonadResource m)
=> FilePath
-> Maybe (LDB.Options) -- optional options
-> Consumer (k,v) m ()
makeleveldb dbpath mopt = do
dbExists <- liftIO $ doesFileExist dbpath
if not dbExists then do
let opt = fromMaybe LDB.defaultOptions mopt
wopt = LDB.defaultWriteOptions
db <- lift $ LDB.open dbpath opt
forever $ do
(k,v) <- await
let vbstring = encode v
kbstring = encode k
lift $ LDB.put db wopt kbstring vbstring
else return ()
-- Loads data from a LevelDB, randomizing the order.
-- The output datatype is whatever you can decode with cereal.
-- Internally, uses a snapshot of the database.
leveldb_random_loader :: forall k v m
. (Serialize k, Serialize v, MonadRandom m, MonadResource m,
MonadBaseControl IO m)
=> LDB.DB
-> [k]
-> Producer v m ()
leveldb_random_loader db keys = do
liftIO $ putStrLn "creating DB snapshot..."
snapshot <- lift $ LDB.createSnapshot db
forever $ do
let rop = LDB.defaultReadOptions { LDB.useSnapshot = Just snapshot }
-- randomize the keys
liftIO $ putStrLn "Shuffling them..."
rkeys <- lift $ shuffle $ fmap encode keys
-- then read the values one after the other.
liftIO $ putStrLn "Decoding and yielding all values..."
forM_ rkeys $ \k -> do
mv <- lift $ LDB.get db rop k
case mv of
Nothing -> liftIO $ do
putStrLn $ "Couldn't find value at key " ++ show k ++ ", skipping."
Just sample -> case decode sample of
Left err -> liftIO $ do
putStrLn $ "Couldn't decode sample " ++ show k ++ ", skipping."
putStrLn $ "\t" ++ show err
Right v -> yield v
lazy_image_loader :: forall i m . (Image i, Convertible StorageImage i, Storable (ImagePixel i), MonadIO m)
=> Proxy i -> FilePath -> Pipe (FilePath, [Int]) (Manifest (ImagePixel i), [Int]) m ()
lazy_image_loader _ directory = forever $ do
(fpath, labels) <- await
eimg <- liftIO $
(load Autodetect $ directory </> fpath
:: IO (Either StorageError i))
case eimg of
Left err -> liftIO $ do
putStrLn $ "Unable to load image " ++ fpath
putStrLn $ show err
Right img -> do
let Z:. h :. w = Friday.shape img
if h == 1 || w == 1
then liftIO $ putStrLn $ "Image loaded as 1 by 1, skipping: " ++ fpath
else do
imgRes <- computeP img
yield (imgRes, labels)
return ()
shuffle :: MonadRandom m => [a] -> m [a]
shuffle xs = do
let l = length xs
rands_ <- getRandomRs (0, l-1)
let
rands = take l rands_
ar = runST $ do
ar <- NSV.unsafeThaw $ NSV.fromList xs
forM_ (zip [0..(l-1)] rands) $ \(i, j) -> do
vi <- NSVM.read ar i
vj <- NSVM.read ar j
NSVM.write ar j vi
NSVM.write ar i vj
NSV.unsafeFreeze ar
return $ NSV.toList ar
randomize :: (MonadIO m, MonadRandom m) => [a] -> (a -> m b) -> Producer b m ()
randomize xs f = do
sxs <- lift $ shuffle xs
forM_ sxs $ \x -> do
fx <- lift $ f x
yield fx
-- converts an image to a (nb_channels, height, width) shaped row-major
-- vector.
-- img_to_chw :: (Storable a, Image i, Pixel (ImagePixel i))
-- => (PixelChannel (ImagePixel i) -> a) -> i -> V.Vector a
-- img_to_chw conv img = V.fromList [conv $ pixIndex (index img (ix2 i j)) k
-- | k <- [0..c-1],
-- i <- [0..h-1],
-- j <- [0..w-1]]
-- where Z :. h :. w = Friday.shape img
-- c = nChannels img
-- img_to_chw :: (Storable a, Image i, Pixel (ImagePixel i))
-- => (PixelChannel (ImagePixel i) -> a) -> i -> V.Vector a
-- img_to_chw conv img = runST $ do
-- let Z :. h :. w = Friday.shape img
-- c = nChannels img
-- imgVector = vector img
-- out <- MV.new $ c * h * w
-- forM_ [0..h-1] $ \i -> do
-- forM_ [0..w-1] $ \j -> do
-- forM_ [0..c-1] $ \k -> do
-- MV.unsafeWrite out (j + w * (i + h * k)) $ conv $ pixIndex (V.unsafeIndex imgVector (j + w * i)) k
-- V.unsafeFreeze out
-- Converts an image to a storable-based vector by casting and sharing the inner
-- data foreign pointer.
img_to_vec :: (Image i, Pixel (ImagePixel i), Storable (PixelChannel (ImagePixel i)))
=> i -> V.Vector (PixelChannel (ImagePixel i))
img_to_vec img =
let Manifest (Z :. h :. w) pixVec = compute img
c = nChannels img
(pixFptr, o, l) = V.unsafeToForeignPtr pixVec
in V.unsafeFromForeignPtr (castForeignPtr pixFptr) (c*o) (c*l)
-- applies a pixel-wise operation to all images.
map_pixels :: (FunctorImage src dst, Monad m)
=> (ImagePixel src -> ImagePixel dst) -> Pipe src dst m ()
map_pixels f = forever $ await >>= yield . Friday.map f
samesize_concat :: (Storable a) => [V.Vector a] -> V.Vector a
samesize_concat vectors = runST $ do
let size = V.length $ head vectors
nbVectors = length vectors
totalSize = nbVectors * size
mres <- MV.new totalSize
forM_ (zip [0..] vectors) $ \(i,v) -> do
let mresslice = MV.unsafeSlice (i * size) size mres
mv <- V.unsafeThaw v
MV.unsafeCopy mresslice mv
V.unsafeFreeze mres
batch_images :: (Image i, Storable (PixelChannel (ImagePixel i)),
Pixel (ImagePixel i), Monad m, TensorDataType a)
=> Int
-> Int
-> Pipe (i, [Int]) (V.Vector (PixelChannel (ImagePixel i)), V.Vector a) m ()
batch_images nb_labels batch_size = forever $ do
imgAndLabels <- replicateM batch_size await
let (images, labels) = unzip imgAndLabels
Z :. h :. w = Friday.shape $ head images
c = nChannels $ head images
oneHot ls = V.fromList [if i `elem` ls then 1 else 0 | i <- [0..nb_labels - 1]]
imgVecs = fmap img_to_vec $ images
batch = samesize_concat imgVecs
lmatrix = V.concat $ fmap oneHot labels
yield (batch, lmatrix)
batch_to_gpu :: (MonadIO m, TensorDataType a, Shape s1, Shape s2)
=> Proxy [s1,s2]
-> Pipe (V.Vector a, V.Vector a) (Tensor s1 a, Tensor s2 a) m ()
batch_to_gpu _ = forever $ do
(batch, labels) <- await
yield (fromVector batch, fromVector labels)
-- serializes inputs
runEvery :: (Monad m) => Int -> (a -> m ()) -> Pipe a a m c
runEvery n action = forever $ do
replicateM (n - 1) $ await >>= yield
x <- await
lift $ action x
yield x
serializeTo :: (MonadIO m, Serialize a) => FilePath -> a -> m ()
serializeTo fpath toSerialize = do
liftIO $ B.writeFile fpath $ encode toSerialize
-- Dataset transformations
random_crop :: forall i l m . (Image i, Storable (ImagePixel i), MonadRandom m)
=> Proxy i -> Int -> Int -> Pipe (Manifest (ImagePixel i), l) (Manifest (ImagePixel i), l) m ()
random_crop _ width height = forever $ do
(img,l) <- await
let Z :. imgHeight :. imgWidth = Friday.shape img
if (imgWidth < width || imgHeight < height)
then error $ "Image too small for cropping:\nimage size: " ++ show (imgHeight,imgWidth) ++ "\ncrop size: " ++ show (height,width)
else do
ix <- lift $ getRandomR (0,imgWidth-width)
iy <- lift $ getRandomR (0,imgHeight-height)
let croppedImg = crop (Rect ix iy width height) img :: Manifest (ImagePixel i)
cropRes <- computeP croppedImg
yield (cropRes, l)
timePipe :: (NFData a, NFData b, MonadIO m, MonadIO m')
=> String -> Pipe a b m c -> m' (Pipe a b m c)
timePipe name pab = liftIO $ do
startRef <- Time.getCurrentTime >>= newIORef
let setStartPipe = forever $ do
a <- await
deepseq a $ liftIO $ Time.getCurrentTime >>= writeIORef startRef
yield a
printTimePipe = forever $ do
b <- await
deepseq b $ liftIO $ do
end_time <- Time.getCurrentTime
start_time <- readIORef startRef
putStrLn $ name ++ " ran in " ++ show (Time.diffUTCTime end_time start_time)
yield b
return $ setStartPipe >-> pab >-> printTimePipe
|
alexisVallet/hnn
|
src/HNN/Data.hs
|
bsd-3-clause
| 12,254
| 0
| 25
| 3,310
| 4,084
| 2,062
| 2,022
| -1
| -1
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP
, NoImplicitPrelude
, MagicHash
, UnboxedTuples
#-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.TopHandler
-- Copyright : (c) The University of Glasgow, 2001-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : cvs-ghc@haskell.org
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- Support for catching exceptions raised during top-level computations
-- (e.g. @Main.main@, 'Control.Concurrent.forkIO', and foreign exports)
--
-----------------------------------------------------------------------------
module GHC.TopHandler (
runMainIO, runIO, runIOFastExit, runNonIO,
topHandler, topHandlerFastExit,
reportStackOverflow, reportError,
flushStdHandles
) where
#include "HsBaseConfig.h"
import Control.Exception
import Data.Maybe
import Foreign
import Foreign.C
import GHC.Base
import GHC.Conc hiding (throwTo)
import GHC.Real
import GHC.IO
import GHC.IO.Handle.FD
import GHC.IO.Handle
import GHC.IO.Exception
import GHC.Weak
#if defined(mingw32_HOST_OS)
import GHC.ConsoleHandler
#else
import Data.Dynamic (toDyn)
#endif
-- | 'runMainIO' is wrapped around 'Main.main' (or whatever main is
-- called in the program). It catches otherwise uncaught exceptions,
-- and also flushes stdout\/stderr before exiting.
runMainIO :: IO a -> IO a
runMainIO main =
do
main_thread_id <- myThreadId
weak_tid <- mkWeakThreadId main_thread_id
install_interrupt_handler $ do
m <- deRefWeak weak_tid
case m of
Nothing -> return ()
Just tid -> throwTo tid (toException UserInterrupt)
main -- hs_exit() will flush
`catch`
topHandler
install_interrupt_handler :: IO () -> IO ()
#if defined(ghcjs_HOST_OS)
install_interrupt_handler _ = return ()
#elif defined(mingw32_HOST_OS)
install_interrupt_handler handler = do
_ <- GHC.ConsoleHandler.installHandler $
Catch $ \event ->
case event of
ControlC -> handler
Break -> handler
Close -> handler
_ -> return ()
return ()
#else
#include "rts/Signals.h"
-- specialised version of System.Posix.Signals.installHandler, which
-- isn't available here.
install_interrupt_handler handler = do
let sig = CONST_SIGINT :: CInt
_ <- setHandler sig (Just (const handler, toDyn handler))
_ <- stg_sig_install sig STG_SIG_RST nullPtr
-- STG_SIG_RST: the second ^C kills us for real, just in case the
-- RTS or program is unresponsive.
return ()
foreign import ccall unsafe
stg_sig_install
:: CInt -- sig no.
-> CInt -- action code (STG_SIG_HAN etc.)
-> Ptr () -- (in, out) blocked
-> IO CInt -- (ret) old action code
#endif
-- | 'runIO' is wrapped around every @foreign export@ and @foreign
-- import \"wrapper\"@ to mop up any uncaught exceptions. Thus, the
-- result of running 'System.Exit.exitWith' in a foreign-exported
-- function is the same as in the main thread: it terminates the
-- program.
--
runIO :: IO a -> IO a
runIO main = catch main topHandler
-- | Like 'runIO', but in the event of an exception that causes an exit,
-- we don't shut down the system cleanly, we just exit. This is
-- useful in some cases, because the safe exit version will give other
-- threads a chance to clean up first, which might shut down the
-- system in a different way. For example, try
--
-- main = forkIO (runIO (exitWith (ExitFailure 1))) >> threadDelay 10000
--
-- This will sometimes exit with "interrupted" and code 0, because the
-- main thread is given a chance to shut down when the child thread calls
-- safeExit. There is a race to shut down between the main and child threads.
--
runIOFastExit :: IO a -> IO a
runIOFastExit main = catch main topHandlerFastExit
-- NB. this is used by the testsuite driver
-- | The same as 'runIO', but for non-IO computations. Used for
-- wrapping @foreign export@ and @foreign import \"wrapper\"@ when these
-- are used to export Haskell functions with non-IO types.
--
runNonIO :: a -> IO a
runNonIO a = catch (a `seq` return a) topHandler
topHandler :: SomeException -> IO a
topHandler err = catch (real_handler safeExit err) topHandler
topHandlerFastExit :: SomeException -> IO a
topHandlerFastExit err =
catchException (real_handler fastExit err) topHandlerFastExit
-- Make sure we handle errors while reporting the error!
-- (e.g. evaluating the string passed to 'error' might generate
-- another error, etc.)
--
real_handler :: (Int -> IO a) -> SomeException -> IO a
real_handler exit se = do
flushStdHandles -- before any error output
case fromException se of
Just StackOverflow -> do
reportStackOverflow
exit 2
Just UserInterrupt -> exitInterrupted
_ -> case fromException se of
-- only the main thread gets ExitException exceptions
Just ExitSuccess -> exit 0
Just (ExitFailure n) -> exit n
-- EPIPE errors received for stdout are ignored (#2699)
_ -> case fromException se of
Just IOError{ ioe_type = ResourceVanished,
ioe_errno = Just ioe,
ioe_handle = Just hdl }
| Errno ioe == ePIPE, hdl == stdout -> exit 0
_ -> do reportError se
exit 1
-- try to flush stdout/stderr, but don't worry if we fail
-- (these handles might have errors, and we don't want to go into
-- an infinite loop).
flushStdHandles :: IO ()
flushStdHandles = do
hFlush stdout `catchAny` \_ -> return ()
hFlush stderr `catchAny` \_ -> return ()
safeExit, fastExit :: Int -> IO a
safeExit = exitHelper useSafeExit
fastExit = exitHelper useFastExit
unreachable :: IO a
unreachable = fail "If you can read this, shutdownHaskellAndExit did not exit."
exitHelper :: CInt -> Int -> IO a
#if defined(mingw32_HOST_OS) || defined(ghcjs_HOST_OS)
exitHelper exitKind r =
shutdownHaskellAndExit (fromIntegral r) exitKind >> unreachable
#else
-- On Unix we use an encoding for the ExitCode:
-- 0 -- 255 normal exit code
-- -127 -- -1 exit by signal
-- For any invalid encoding we just use a replacement (0xff).
exitHelper exitKind r
| r >= 0 && r <= 255
= shutdownHaskellAndExit (fromIntegral r) exitKind >> unreachable
| r >= -127 && r <= -1
= shutdownHaskellAndSignal (fromIntegral (-r)) exitKind >> unreachable
| otherwise
= shutdownHaskellAndExit 0xff exitKind >> unreachable
foreign import ccall "shutdownHaskellAndSignal"
shutdownHaskellAndSignal :: CInt -> CInt -> IO ()
#endif
exitInterrupted :: IO a
exitInterrupted =
#if defined(mingw32_HOST_OS) || defined(ghcjs_HOST_OS)
safeExit 252
#else
-- we must exit via the default action for SIGINT, so that the
-- parent of this process can take appropriate action (see #2301)
safeExit (-CONST_SIGINT)
#endif
-- NOTE: shutdownHaskellAndExit must be called "safe", because it *can*
-- re-enter Haskell land through finalizers.
foreign import ccall "Rts.h shutdownHaskellAndExit"
shutdownHaskellAndExit :: CInt -> CInt -> IO ()
useFastExit, useSafeExit :: CInt
useFastExit = 1
useSafeExit = 0
|
forked-upstream-packages-for-ghcjs/ghc
|
libraries/base/GHC/TopHandler.hs
|
bsd-3-clause
| 7,471
| 0
| 20
| 1,760
| 886
| 478
| 408
| 105
| 6
|
{-# OPTIONS -cpp #-}
module API where
import AltData.Typeable
data Interface = Interface {
equals :: forall t. Eq t => t -> t -> Bool
}
--
-- see how it hides the internal type.. but to compile GHC still checks
-- the type.
--
instance Typeable Interface where
#if __GLASGOW_HASKELL__ >= 603
typeOf i = mkTyConApp (mkTyCon "API.Interface") []
#else
typeOf i = mkAppTy (mkTyCon "API.Interface") []
#endif
plugin :: Interface
plugin = Interface { equals = (==) }
|
abuiles/turbinado-blog
|
tmp/dependencies/hs-plugins-1.3.1/testsuite/dynload/poly/api/API.hs
|
bsd-3-clause
| 490
| 0
| 12
| 110
| 101
| 60
| 41
| -1
| -1
|
{-# OPTIONS_GHC -fffi -fbang-patterns #-}
module MemBench (memBench) where
import Foreign
import Foreign.C
import Control.Exception
import System.CPUTime
import Numeric
memBench :: Int -> IO ()
memBench mb = do
let bytes = mb * 2^20
allocaBytes bytes $ \ptr -> do
let bench label test = do
seconds <- time $ test (castPtr ptr) (fromIntegral bytes)
let throughput = fromIntegral mb / seconds
putStrLn $ show mb ++ "MB of " ++ label
++ " in " ++ showFFloat (Just 3) seconds "s, at: "
++ showFFloat (Just 1) throughput "MB/s"
bench "setup " c_wordwrite
putStrLn ""
putStrLn "C memory throughput benchmarks:"
bench "bytes written" c_bytewrite
bench "bytes read " c_byteread
bench "words written" c_wordwrite
bench "words read " c_wordread
putStrLn ""
putStrLn "Haskell memory throughput benchmarks:"
bench "bytes written" hs_bytewrite
bench "bytes read " hs_byteread
bench "words written" hs_wordwrite
bench "words read " hs_wordread
hs_bytewrite :: Ptr CUChar -> Int -> IO ()
hs_bytewrite !ptr bytes = loop 0 0
where iterations = bytes
loop :: Int -> CUChar -> IO ()
loop !i !n | i == iterations = return ()
| otherwise = do pokeByteOff ptr i n
loop (i+1) (n+1)
hs_byteread :: Ptr CUChar -> Int -> IO CUChar
hs_byteread !ptr bytes = loop 0 0
where iterations = bytes
loop :: Int -> CUChar -> IO CUChar
loop !i !n | i == iterations = return n
| otherwise = do x <- peekByteOff ptr i
loop (i+1) (n+x)
hs_wordwrite :: Ptr CULong -> Int -> IO ()
hs_wordwrite !ptr bytes = loop 0 0
where iterations = bytes `div` sizeOf (undefined :: CULong)
loop :: Int -> CULong -> IO ()
loop !i !n | i == iterations = return ()
| otherwise = do pokeByteOff ptr i n
loop (i+1) (n+1)
hs_wordread :: Ptr CULong -> Int -> IO CULong
hs_wordread !ptr bytes = loop 0 0
where iterations = bytes `div` sizeOf (undefined :: CULong)
loop :: Int -> CULong -> IO CULong
loop !i !n | i == iterations = return n
| otherwise = do x <- peekByteOff ptr i
loop (i+1) (n+x)
foreign import ccall unsafe "CBenchmark.h byteread"
c_byteread :: Ptr CUChar -> CInt -> IO ()
foreign import ccall unsafe "CBenchmark.h bytewrite"
c_bytewrite :: Ptr CUChar -> CInt -> IO ()
foreign import ccall unsafe "CBenchmark.h wordread"
c_wordread :: Ptr CUInt -> CInt -> IO ()
foreign import ccall unsafe "CBenchmark.h wordwrite"
c_wordwrite :: Ptr CUInt -> CInt -> IO ()
time :: IO a -> IO Double
time action = do
start <- getCPUTime
action
end <- getCPUTime
return $! (fromIntegral (end - start)) / (10^12)
|
fpco/serial-bench
|
binary-0.4.3.1/tests/MemBench.hs
|
bsd-3-clause
| 2,922
| 0
| 22
| 914
| 1,028
| 481
| 547
| -1
| -1
|
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
[lq| prop0 :: x:_ -> y:{_ | y == x} -> TT |]
prop0 x y = (a == b)
where
a = get x emp
b = get y emp
[lq| prop1 :: x:_ -> y:{_ | y /= x} -> TT |]
prop1 x y = (z == 10)
where
m1 = put x 10 emp
m2 = put y 20 m1
z = get x m2
[lq| prop2 :: x:_ -> y:{_ | y == x} -> TT |]
prop2 x y = (z == 20)
where
m1 = put x 10 emp
m2 = put y 20 m1
z = get x m2
-----------------------------------------------------------------------
data Map k v = M
[lq| embed Map as Map_t |]
[lq| measure Map_select :: Map k v -> k -> v |]
[lq| measure Map_store :: Map k v -> k -> v -> Map k v |]
emp :: Map Int Int
emp = undefined
[lq| get :: k:k -> m:Map k v -> {v:v | v = Map_select m k} |]
get :: k -> Map k v -> v
get = undefined
[lq| put :: k:k -> v:v -> m:Map k v -> {n:Map k v | n = Map_store m k v} |]
put :: k -> v -> Map k v -> Map k v
put = undefined
|
spinda/liquidhaskell
|
tests/gsoc15/unknown/pos/maps.hs
|
bsd-3-clause
| 977
| 0
| 8
| 326
| 286
| 160
| 126
| 28
| 1
|
module VForth.LocationSpec where
import Data.List (isInfixOf)
import Data.Char (isSpace)
import Test.Hspec
import Test.QuickCheck
import VForth
newtype TestableLocation = TestableLocation Location
instance Arbitrary TestableLocation where
arbitrary = TestableLocation <$> (
newLocation <$> arbitrary <*> arbitrary
)
instance Show TestableLocation where
show (TestableLocation l) = "Location { title=\"" ++ title l ++ "\", description=\"" ++ description l ++ "\" }"
newLocation :: String -> String -> Location
newLocation titleText descText = Location {
title = titleText
, description = descText
}
spec :: Spec
spec = do
describe "Location Display" $ do
it "Show puts title before dashes before a description" $ do
show (newLocation "My Title" "The complete description.") `shouldBe` "My Title\n--------\nThe complete description."
it "Title should be included in showable output" $ property $
\(TestableLocation l) -> title l `isInfixOf` show l
it "Description should be included in showable output" $ property $
\(TestableLocation l) -> description l `isInfixOf` show l
it "Showable output is never blank" $ property $
\(TestableLocation l) ->
(not . null . title $ l) && (not . null . description $ l)
==> any (not . isSpace) (show l)
|
budgefeeney/ventureforth
|
chap3/test/VForth/LocationSpec.hs
|
bsd-3-clause
| 1,324
| 0
| 17
| 271
| 361
| 187
| 174
| 29
| 1
|
{-# LANGUAGE ScopedTypeVariables, StandaloneDeriving, DeriveGeneric,
TupleSections, RecordWildCards, InstanceSigs #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
-- |
-- Running TH splices
--
module GHCi.TH (startTH, finishTH, runTH, GHCiQException(..)) where
import GHCi.Message
import GHCi.RemoteTypes
import GHC.Serialized
import Control.Exception
import qualified Control.Monad.Fail as Fail
import Data.Binary
import Data.Binary.Put
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as LB
import Data.Data
import Data.Dynamic
import Data.IORef
import Data.Map (Map)
import qualified Data.Map as M
import Data.Maybe
import GHC.Desugar
import qualified Language.Haskell.TH as TH
import qualified Language.Haskell.TH.Syntax as TH
import Unsafe.Coerce
initQState :: Pipe -> QState
initQState p = QState M.empty [] Nothing p
runModFinalizers :: GHCiQ ()
runModFinalizers = go =<< getState
where
go s | (f:ff) <- qsFinalizers s = do
putState (s { qsFinalizers = ff}) >> TH.runQ f >> getState >>= go
go _ = return ()
newtype GHCiQ a = GHCiQ { runGHCiQ :: QState -> IO (a, QState) }
data GHCiQException = GHCiQException QState String
deriving Show
instance Exception GHCiQException
instance Functor GHCiQ where
fmap f (GHCiQ s) = GHCiQ $ fmap (\(x,s') -> (f x,s')) . s
instance Applicative GHCiQ where
f <*> a = GHCiQ $ \s ->
do (f',s') <- runGHCiQ f s
(a',s'') <- runGHCiQ a s'
return (f' a', s'')
pure x = GHCiQ (\s -> return (x,s))
instance Monad GHCiQ where
m >>= f = GHCiQ $ \s ->
do (m', s') <- runGHCiQ m s
(a, s'') <- runGHCiQ (f m') s'
return (a, s'')
fail = Fail.fail
instance Fail.MonadFail GHCiQ where
fail err = GHCiQ $ \s -> throwIO (GHCiQException s err)
getState :: GHCiQ QState
getState = GHCiQ $ \s -> return (s,s)
putState :: QState -> GHCiQ ()
putState s = GHCiQ $ \_ -> return ((),s)
noLoc :: TH.Loc
noLoc = TH.Loc "<no file>" "<no package>" "<no module>" (0,0) (0,0)
ghcCmd :: Binary a => Message (THResult a) -> GHCiQ a
ghcCmd m = GHCiQ $ \s -> do
r <- remoteCall (qsPipe s) m
case r of
THException str -> throwIO (GHCiQException s str)
THComplete res -> return (res, s)
instance TH.Quasi GHCiQ where
qNewName str = ghcCmd (NewName str)
qReport isError msg = ghcCmd (Report isError msg)
-- See Note [TH recover with -fexternal-interpreter] in TcSplice
qRecover (GHCiQ h) (GHCiQ a) = GHCiQ $ \s -> (do
remoteCall (qsPipe s) StartRecover
(r, s') <- a s
remoteCall (qsPipe s) (EndRecover False)
return (r,s'))
`catch`
\GHCiQException{} -> remoteCall (qsPipe s) (EndRecover True) >> h s
qLookupName isType occ = ghcCmd (LookupName isType occ)
qReify name = ghcCmd (Reify name)
qReifyFixity name = ghcCmd (ReifyFixity name)
qReifyInstances name tys = ghcCmd (ReifyInstances name tys)
qReifyRoles name = ghcCmd (ReifyRoles name)
-- To reify annotations, we send GHC the AnnLookup and also the
-- TypeRep of the thing we're looking for, to avoid needing to
-- serialize irrelevant annotations.
qReifyAnnotations :: forall a . Data a => TH.AnnLookup -> GHCiQ [a]
qReifyAnnotations lookup =
map (deserializeWithData . B.unpack) <$>
ghcCmd (ReifyAnnotations lookup typerep)
where typerep = typeOf (undefined :: a)
qReifyModule m = ghcCmd (ReifyModule m)
qReifyConStrictness name = ghcCmd (ReifyConStrictness name)
qLocation = fromMaybe noLoc . qsLocation <$> getState
qRunIO m = GHCiQ $ \s -> fmap (,s) m
qAddDependentFile file = ghcCmd (AddDependentFile file)
qAddTopDecls decls = ghcCmd (AddTopDecls decls)
qAddModFinalizer fin = GHCiQ $ \s ->
return ((), s { qsFinalizers = fin : qsFinalizers s })
qGetQ = GHCiQ $ \s ->
let lookup :: forall a. Typeable a => Map TypeRep Dynamic -> Maybe a
lookup m = fromDynamic =<< M.lookup (typeOf (undefined::a)) m
in return (lookup (qsMap s), s)
qPutQ k = GHCiQ $ \s ->
return ((), s { qsMap = M.insert (typeOf k) (toDyn k) (qsMap s) })
qIsExtEnabled x = ghcCmd (IsExtEnabled x)
qExtsEnabled = ghcCmd ExtsEnabled
startTH :: IO (RemoteRef (IORef QState))
startTH = do
r <- newIORef (initQState (error "startTH: no pipe"))
mkRemoteRef r
finishTH :: Pipe -> RemoteRef (IORef QState) -> IO ()
finishTH pipe rstate = do
qstateref <- localRef rstate
qstate <- readIORef qstateref
_ <- runGHCiQ runModFinalizers qstate { qsPipe = pipe }
return ()
runTH
:: Pipe -> RemoteRef (IORef QState) -> HValueRef
-> THResultType
-> Maybe TH.Loc
-> IO ByteString
runTH pipe rstate rhv ty mb_loc = do
hv <- localRef rhv
case ty of
THExp -> runTHQ pipe rstate mb_loc (unsafeCoerce hv :: TH.Q TH.Exp)
THPat -> runTHQ pipe rstate mb_loc (unsafeCoerce hv :: TH.Q TH.Pat)
THType -> runTHQ pipe rstate mb_loc (unsafeCoerce hv :: TH.Q TH.Type)
THDec -> runTHQ pipe rstate mb_loc (unsafeCoerce hv :: TH.Q [TH.Dec])
THAnnWrapper -> do
hv <- unsafeCoerce <$> localRef rhv
case hv :: AnnotationWrapper of
AnnotationWrapper thing -> return $!
LB.toStrict (runPut (put (toSerialized serializeWithData thing)))
runTHQ
:: Binary a => Pipe -> RemoteRef (IORef QState) -> Maybe TH.Loc -> TH.Q a
-> IO ByteString
runTHQ pipe@Pipe{..} rstate mb_loc ghciq = do
qstateref <- localRef rstate
qstate <- readIORef qstateref
let st = qstate { qsLocation = mb_loc, qsPipe = pipe }
(r,new_state) <- runGHCiQ (TH.runQ ghciq) st
writeIORef qstateref new_state
return $! LB.toStrict (runPut (put r))
|
vikraman/ghc
|
libraries/ghci/GHCi/TH.hs
|
bsd-3-clause
| 5,586
| 0
| 22
| 1,168
| 2,128
| 1,087
| 1,041
| 136
| 5
|
module Sound.Sarasvati
( module Sound.Sarasvati.Base
, module Sound.Sarasvati.Types
, Error
) where
import Sound.Sarasvati.Base
import Sound.Sarasvati.Types
import Sound.PortAudio
|
tokiwoousaka/Sarasvati
|
src/Sound/Sarasvati.hs
|
bsd-3-clause
| 189
| 0
| 5
| 27
| 42
| 28
| 14
| 7
| 0
|
module Main (main) where
import Test.QuickCheck
import Test.Hspec
import TNGraph
import qualified Data.Map as M
import TNTypes
import TNPrimitiveFunctions
import Data.Maybe (fromMaybe)
import Test.QuickCheck
import Data.List
import GibbsSampler
import System.Random
instance Arbitrary TNGraphType where
arbitrary = elements [TNDGraph, TNUGraph]
main :: IO ()
main = hspec $ describe "Testing" $ do
describe "TNGraph.buildTNGraphFromInfo" $
it "Edges = [(1,2)] -> Vertices = [1,2]" $ do
let edges = [(1,2)]
let vertexValues = M.fromList [(1,3),(2,4)]
let graphInfo = (edges, vertexValues)
let graph = buildTNGraphFromInfo TNDGraph graphInfo
let vs = vertices graph
vs `shouldBe` [1,2]
describe "TNGraph.buildTNGraphFromInfo" $
it "Basic graph properties" $ do
let edges = [(1,2)]
let vertexValues = M.fromList [(1,3),(2,4)]
let graphInfo = (edges, vertexValues)
let (TNGraph {table = t, graphType = gt, vertexValues = values})
= buildTNGraphFromInfo TNDGraph graphInfo
gt `shouldBe` TNDGraph
values `shouldBe` M.fromList [(1,3),(2,4)]
describe "TNGraph.convertGraph: directed -> undirected" $
it "must double the number of edges" $ property prop_convertGraphDoublesEdges
describe "GibbsSampler.divideGraphValuesBy" $
it "new values must equal old values times denominator" $ property prop_divideGraphValuesBy
describe "GibbsSampler.addGraphValues" $
it "new values must equal sum of previous values plus sum of added values" $ property prop_addGraphValues
describe "GibbsSampler.randomInitializer" $
it "must not change graph dimensions" $ property prop_randomInitializer
describe "GibbsSampler.zerosInitializer" $
it "must not change graph dimensions" $ property prop_zerosInitializerDoesNotChangeDimensions
describe "GibbsSampler.zerosInitializer" $
it "all vertex values must add up to zero" $ property prop_zerosInitializerHasZeros
describe "TNGraph.getGraphType" $
it "must return graph type with which graph was built" $ property prop_getGraphType
describe "TNGraph.convertGraph" $
it "must update graph type to new type" $ property prop_convertGraphToUndirectedUpdatesType
-- | Converting a directed graph into an undirected graph should
-- double the number of edges in the graph.
prop_convertGraphDoublesEdges:: ([TNEdge], [(Int, Float)]) -> Bool
prop_convertGraphDoublesEdges graphInfo = do
let (ed, vertexVals) = graphInfo
let directedGraph = buildTNGraphFromInfo TNDGraph (ed, M.fromList vertexVals)
let undirectedGraph = convertGraph directedGraph TNUGraph
let newEdges = edges undirectedGraph
length (newEdges) == 2 * length (ed)
prop_convertGraphToUndirectedUpdatesType:: ([TNEdge], [(Int, Float)]) -> Bool
prop_convertGraphToUndirectedUpdatesType graphInfo = do
let (ed, vertexVals) = graphInfo
let directedGraph = buildTNGraphFromInfo TNDGraph (ed, M.fromList vertexVals)
let undirectedGraph = convertGraph directedGraph TNUGraph
getGraphType undirectedGraph == TNUGraph
prop_divideGraphValuesBy:: ([TNEdge], [(Int, Float)]) -> Float -> Bool
prop_divideGraphValuesBy graphInfo denominator = do
let (ed, vertexVals) = graphInfo
let graph = buildGraph graphInfo
let TNGraph {table = t, graphType = gt, vertexValues = newVals} = divideGraphValuesBy graph denominator
let add = M.foldl (+) 0
(add $ M.fromList vertexVals) - (add newVals) * denominator <= 0.1
prop_addGraphValues:: ([TNEdge], [(Int, Float)]) -> [(Int, Float)] -> Bool
prop_addGraphValues graphInfo valuesToAdd = do
let (ed, vertexVals) = graphInfo
let graph = buildGraph graphInfo
let TNGraph {table = t, graphType = gt, vertexValues = newVals} = addValuesToGraph graph (M.fromList valuesToAdd)
let add = M.foldl (+) 0
(add $ M.fromList vertexVals) + (add $ (M.fromList valuesToAdd)) - add newVals <= 0.2
prop_getGraphType:: ([TNEdge], [(Int, Float)]) -> TNGraphType -> Bool
prop_getGraphType graphInfo graphType = do
let (ed, vertexVals) = graphInfo
let graph = buildTNGraphFromInfo graphType (ed, M.fromList vertexVals)
getGraphType graph == graphType
prop_randomInitializer::([TNEdge], [(Int, Float)]) -> Bool
prop_randomInitializer graphInfo = do
length (vertices $ randomInitializer (buildGraph graphInfo) (mkStdGen 1)) == length (vertices (buildGraph graphInfo))
prop_zerosInitializerDoesNotChangeDimensions::([TNEdge], [(Int, Float)]) -> Bool
prop_zerosInitializerDoesNotChangeDimensions graphInfo = do
length (vertices $ zerosInitializer (buildGraph graphInfo)) == length (vertices (buildGraph graphInfo))
prop_zerosInitializerHasZeros::([TNEdge], [(Int, Float)]) -> Bool
prop_zerosInitializerHasZeros graphInfo = do
let TNGraph {table = t, graphType = gt, vertexValues = newVals} = zerosInitializer (buildGraph graphInfo)
let add = M.foldl (+) 0
add newVals == 0
buildGraph::([TNEdge], [(Int, Float)]) -> TNGraph
buildGraph graphInfo = buildTNGraphFromInfo TNUGraph (ed, M.fromList vertexVals)
where
(ed, vertexVals) = graphInfo
|
astarostap/cs240h_final_project
|
test/Spec.hs
|
bsd-3-clause
| 5,098
| 7
| 21
| 872
| 1,536
| 798
| 738
| 95
| 1
|
module Graphics.UI.SDL.Audio (
-- * Audio Device Management, Playing and Recording
audioInit,
audioQuit,
buildAudioCVT,
closeAudio,
closeAudioDevice,
convertAudio,
freeWAV,
getAudioDeviceName,
getAudioDeviceStatus,
getAudioDriver,
getAudioStatus,
getCurrentAudioDriver,
getNumAudioDevices,
getNumAudioDrivers,
loadWAV,
loadWAV_RW,
lockAudio,
lockAudioDevice,
mixAudio,
mixAudioFormat,
openAudio,
openAudioDevice,
pauseAudio,
pauseAudioDevice,
unlockAudio,
unlockAudioDevice
) where
import Control.Monad.IO.Class
import Data.Word
import Foreign.C.String
import Foreign.C.Types
import Foreign.Ptr
import Graphics.UI.SDL.Enum
import Graphics.UI.SDL.Filesystem
import Graphics.UI.SDL.Types
foreign import ccall "SDL.h SDL_AudioInit" audioInit' :: CString -> IO CInt
foreign import ccall "SDL.h SDL_AudioQuit" audioQuit' :: IO ()
foreign import ccall "SDL.h SDL_BuildAudioCVT" buildAudioCVT' :: Ptr AudioCVT -> AudioFormat -> Word8 -> CInt -> AudioFormat -> Word8 -> CInt -> IO CInt
foreign import ccall "SDL.h SDL_CloseAudio" closeAudio' :: IO ()
foreign import ccall "SDL.h SDL_CloseAudioDevice" closeAudioDevice' :: AudioDeviceID -> IO ()
foreign import ccall "SDL.h SDL_ConvertAudio" convertAudio' :: Ptr AudioCVT -> IO CInt
foreign import ccall "SDL.h SDL_FreeWAV" freeWAV' :: Ptr Word8 -> IO ()
foreign import ccall "SDL.h SDL_GetAudioDeviceName" getAudioDeviceName' :: CInt -> CInt -> IO CString
foreign import ccall "SDL.h SDL_GetAudioDeviceStatus" getAudioDeviceStatus' :: AudioDeviceID -> IO AudioStatus
foreign import ccall "SDL.h SDL_GetAudioDriver" getAudioDriver' :: CInt -> IO CString
foreign import ccall "SDL.h SDL_GetAudioStatus" getAudioStatus' :: IO AudioStatus
foreign import ccall "SDL.h SDL_GetCurrentAudioDriver" getCurrentAudioDriver' :: IO CString
foreign import ccall "SDL.h SDL_GetNumAudioDevices" getNumAudioDevices' :: CInt -> IO CInt
foreign import ccall "SDL.h SDL_GetNumAudioDrivers" getNumAudioDrivers' :: IO CInt
foreign import ccall "SDL.h SDL_LoadWAV_RW" loadWAV_RW' :: Ptr RWops -> CInt -> Ptr AudioSpec -> Ptr (Ptr Word8) -> Ptr Word32 -> IO (Ptr AudioSpec)
foreign import ccall "SDL.h SDL_LockAudio" lockAudio' :: IO ()
foreign import ccall "SDL.h SDL_LockAudioDevice" lockAudioDevice' :: AudioDeviceID -> IO ()
foreign import ccall "SDL.h SDL_MixAudio" mixAudio' :: Ptr Word8 -> Ptr Word8 -> Word32 -> CInt -> IO ()
foreign import ccall "SDL.h SDL_MixAudioFormat" mixAudioFormat' :: Ptr Word8 -> Ptr Word8 -> AudioFormat -> Word32 -> CInt -> IO ()
foreign import ccall "SDL.h SDL_OpenAudio" openAudio' :: Ptr AudioSpec -> Ptr AudioSpec -> IO CInt
foreign import ccall "SDL.h SDL_OpenAudioDevice" openAudioDevice' :: CString -> CInt -> Ptr AudioSpec -> Ptr AudioSpec -> CInt -> IO AudioDeviceID
foreign import ccall "SDL.h SDL_PauseAudio" pauseAudio' :: CInt -> IO ()
foreign import ccall "SDL.h SDL_PauseAudioDevice" pauseAudioDevice' :: AudioDeviceID -> CInt -> IO ()
foreign import ccall "SDL.h SDL_UnlockAudio" unlockAudio' :: IO ()
foreign import ccall "SDL.h SDL_UnlockAudioDevice" unlockAudioDevice' :: AudioDeviceID -> IO ()
audioInit :: MonadIO m => CString -> m CInt
audioInit v1 = liftIO $ audioInit' v1
{-# INLINE audioInit #-}
audioQuit :: MonadIO m => m ()
audioQuit = liftIO audioQuit'
{-# INLINE audioQuit #-}
buildAudioCVT :: MonadIO m => Ptr AudioCVT -> AudioFormat -> Word8 -> CInt -> AudioFormat -> Word8 -> CInt -> m CInt
buildAudioCVT v1 v2 v3 v4 v5 v6 v7 = liftIO $ buildAudioCVT' v1 v2 v3 v4 v5 v6 v7
{-# INLINE buildAudioCVT #-}
closeAudio :: MonadIO m => m ()
closeAudio = liftIO closeAudio'
{-# INLINE closeAudio #-}
closeAudioDevice :: MonadIO m => AudioDeviceID -> m ()
closeAudioDevice v1 = liftIO $ closeAudioDevice' v1
{-# INLINE closeAudioDevice #-}
convertAudio :: MonadIO m => Ptr AudioCVT -> m CInt
convertAudio v1 = liftIO $ convertAudio' v1
{-# INLINE convertAudio #-}
freeWAV :: MonadIO m => Ptr Word8 -> m ()
freeWAV v1 = liftIO $ freeWAV' v1
{-# INLINE freeWAV #-}
getAudioDeviceName :: MonadIO m => CInt -> CInt -> m CString
getAudioDeviceName v1 v2 = liftIO $ getAudioDeviceName' v1 v2
{-# INLINE getAudioDeviceName #-}
getAudioDeviceStatus :: MonadIO m => AudioDeviceID -> m AudioStatus
getAudioDeviceStatus v1 = liftIO $ getAudioDeviceStatus' v1
{-# INLINE getAudioDeviceStatus #-}
getAudioDriver :: MonadIO m => CInt -> m CString
getAudioDriver v1 = liftIO $ getAudioDriver' v1
{-# INLINE getAudioDriver #-}
getAudioStatus :: MonadIO m => m AudioStatus
getAudioStatus = liftIO getAudioStatus'
{-# INLINE getAudioStatus #-}
getCurrentAudioDriver :: MonadIO m => m CString
getCurrentAudioDriver = liftIO getCurrentAudioDriver'
{-# INLINE getCurrentAudioDriver #-}
getNumAudioDevices :: MonadIO m => CInt -> m CInt
getNumAudioDevices v1 = liftIO $ getNumAudioDevices' v1
{-# INLINE getNumAudioDevices #-}
getNumAudioDrivers :: MonadIO m => m CInt
getNumAudioDrivers = liftIO getNumAudioDrivers'
{-# INLINE getNumAudioDrivers #-}
loadWAV :: MonadIO m => CString -> Ptr AudioSpec -> Ptr (Ptr Word8) -> Ptr Word32 -> m (Ptr AudioSpec)
loadWAV file spec audio_buf audio_len = liftIO $ do
rw <- withCString "rb" $ rwFromFile file
loadWAV_RW rw 1 spec audio_buf audio_len
{-# INLINE loadWAV #-}
loadWAV_RW :: MonadIO m => Ptr RWops -> CInt -> Ptr AudioSpec -> Ptr (Ptr Word8) -> Ptr Word32 -> m (Ptr AudioSpec)
loadWAV_RW v1 v2 v3 v4 v5 = liftIO $ loadWAV_RW' v1 v2 v3 v4 v5
{-# INLINE loadWAV_RW #-}
lockAudio :: MonadIO m => m ()
lockAudio = liftIO lockAudio'
{-# INLINE lockAudio #-}
lockAudioDevice :: MonadIO m => AudioDeviceID -> m ()
lockAudioDevice v1 = liftIO $ lockAudioDevice' v1
{-# INLINE lockAudioDevice #-}
mixAudio :: MonadIO m => Ptr Word8 -> Ptr Word8 -> Word32 -> CInt -> m ()
mixAudio v1 v2 v3 v4 = liftIO $ mixAudio' v1 v2 v3 v4
{-# INLINE mixAudio #-}
mixAudioFormat :: MonadIO m => Ptr Word8 -> Ptr Word8 -> AudioFormat -> Word32 -> CInt -> m ()
mixAudioFormat v1 v2 v3 v4 v5 = liftIO $ mixAudioFormat' v1 v2 v3 v4 v5
{-# INLINE mixAudioFormat #-}
openAudio :: MonadIO m => Ptr AudioSpec -> Ptr AudioSpec -> m CInt
openAudio v1 v2 = liftIO $ openAudio' v1 v2
{-# INLINE openAudio #-}
openAudioDevice :: MonadIO m => CString -> CInt -> Ptr AudioSpec -> Ptr AudioSpec -> CInt -> m AudioDeviceID
openAudioDevice v1 v2 v3 v4 v5 = liftIO $ openAudioDevice' v1 v2 v3 v4 v5
{-# INLINE openAudioDevice #-}
pauseAudio :: MonadIO m => CInt -> m ()
pauseAudio v1 = liftIO $ pauseAudio' v1
{-# INLINE pauseAudio #-}
pauseAudioDevice :: MonadIO m => AudioDeviceID -> CInt -> m ()
pauseAudioDevice v1 v2 = liftIO $ pauseAudioDevice' v1 v2
{-# INLINE pauseAudioDevice #-}
unlockAudio :: MonadIO m => m ()
unlockAudio = liftIO unlockAudio'
{-# INLINE unlockAudio #-}
unlockAudioDevice :: MonadIO m => AudioDeviceID -> m ()
unlockAudioDevice v1 = liftIO $ unlockAudioDevice' v1
{-# INLINE unlockAudioDevice #-}
|
polarina/sdl2
|
Graphics/UI/SDL/Audio.hs
|
bsd-3-clause
| 6,875
| 0
| 13
| 1,091
| 1,936
| 977
| 959
| 140
| 1
|
module Test.Reschedule(main) where
import Development.Shake
import Test.Type
main = testBuild test $ do
file <- newResource "log.txt" 1
let log x = withResource file 1 $ liftIO $ appendFile "log.txt" x
"*.p0" %> \out -> do
log "0"
writeFile' out ""
"*.p1" %> \out -> do
reschedule 1
log "1"
writeFile' out ""
"*.p2" %> \out -> do
reschedule 2
log "2"
writeFile' out ""
test build = do
build ["clean"]
build ["foo.p1","bar.p1","baz.p0","qux.p2"]
assertContents "log.txt" "0211"
|
ndmitchell/shake
|
src/Test/Reschedule.hs
|
bsd-3-clause
| 579
| 0
| 13
| 178
| 208
| 95
| 113
| 21
| 1
|
import Data.Digest.Pure.MD5
-- import Benchmark.Crypto
import Criterion.Main
main = defaultMain [benchmarkHash (undefined :: MD5Digest) "pureMD5"]
|
TomMD/pureMD5
|
Test/Bench.hs
|
bsd-3-clause
| 148
| 0
| 8
| 16
| 36
| 21
| 15
| 3
| 1
|
-----------------------------------------------------------------------------
--
-- Object-file symbols (called CLabel for histerical raisins).
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
{-# LANGUAGE CPP #-}
module CLabel (
CLabel, -- abstract type
ForeignLabelSource(..),
pprDebugCLabel,
mkClosureLabel,
mkSRTLabel,
mkTopSRTLabel,
mkInfoTableLabel,
mkEntryLabel,
mkSlowEntryLabel,
mkConEntryLabel,
mkStaticConEntryLabel,
mkRednCountsLabel,
mkConInfoTableLabel,
mkStaticInfoTableLabel,
mkLargeSRTLabel,
mkApEntryLabel,
mkApInfoTableLabel,
mkClosureTableLabel,
mkLocalClosureLabel,
mkLocalInfoTableLabel,
mkLocalEntryLabel,
mkLocalConEntryLabel,
mkLocalStaticConEntryLabel,
mkLocalConInfoTableLabel,
mkLocalStaticInfoTableLabel,
mkLocalClosureTableLabel,
mkReturnPtLabel,
mkReturnInfoLabel,
mkAltLabel,
mkDefaultLabel,
mkBitmapLabel,
mkStringLitLabel,
mkAsmTempLabel,
mkAsmTempDerivedLabel,
mkAsmTempEndLabel,
mkAsmTempDieLabel,
mkPlainModuleInitLabel,
mkSplitMarkerLabel,
mkDirty_MUT_VAR_Label,
mkUpdInfoLabel,
mkBHUpdInfoLabel,
mkIndStaticInfoLabel,
mkMainCapabilityLabel,
mkMAP_FROZEN_infoLabel,
mkMAP_FROZEN0_infoLabel,
mkMAP_DIRTY_infoLabel,
mkSMAP_FROZEN_infoLabel,
mkSMAP_FROZEN0_infoLabel,
mkSMAP_DIRTY_infoLabel,
mkEMPTY_MVAR_infoLabel,
mkArrWords_infoLabel,
mkRUBBISH_ENTRY_infoLabel,
mkTopTickyCtrLabel,
mkCAFBlackHoleInfoTableLabel,
mkCAFBlackHoleEntryLabel,
mkRtsPrimOpLabel,
mkRtsSlowFastTickyCtrLabel,
mkSelectorInfoLabel,
mkSelectorEntryLabel,
mkCmmInfoLabel,
mkCmmEntryLabel,
mkCmmRetInfoLabel,
mkCmmRetLabel,
mkCmmCodeLabel,
mkCmmDataLabel,
mkCmmClosureLabel,
mkRtsApFastLabel,
mkPrimCallLabel,
mkForeignLabel,
addLabelSize,
foreignLabelStdcallInfo,
isForeignLabel,
mkCCLabel, mkCCSLabel,
DynamicLinkerLabelInfo(..),
mkDynamicLinkerLabel,
dynamicLinkerLabelInfo,
mkPicBaseLabel,
mkDeadStripPreventer,
mkHpcTicksLabel,
hasCAF,
needsCDecl, maybeAsmTemp, externallyVisibleCLabel,
isMathFun,
isCFunctionLabel, isGcPtrLabel, labelDynamic,
-- * Conversions
toClosureLbl, toSlowEntryLbl, toEntryLbl, toInfoLbl, toRednCountsLbl, hasHaskellName,
pprCLabel
) where
#include "HsVersions.h"
import IdInfo
import BasicTypes
import Packages
import Module
import Name
import Unique
import PrimOp
import Config
import CostCentre
import Outputable
import FastString
import DynFlags
import Platform
import UniqSet
import Util
import PprCore ( {- instances -} )
-- -----------------------------------------------------------------------------
-- The CLabel type
{-
| CLabel is an abstract type that supports the following operations:
- Pretty printing
- In a C file, does it need to be declared before use? (i.e. is it
guaranteed to be already in scope in the places we need to refer to it?)
- If it needs to be declared, what type (code or data) should it be
declared to have?
- Is it visible outside this object file or not?
- Is it "dynamic" (see details below)
- Eq and Ord, so that we can make sets of CLabels (currently only
used in outputting C as far as I can tell, to avoid generating
more than one declaration for any given label).
- Converting an info table label into an entry label.
-}
data CLabel
= -- | A label related to the definition of a particular Id or Con in a .hs file.
IdLabel
Name
CafInfo
IdLabelInfo -- encodes the suffix of the label
-- | A label from a .cmm file that is not associated with a .hs level Id.
| CmmLabel
UnitId -- what package the label belongs to.
FastString -- identifier giving the prefix of the label
CmmLabelInfo -- encodes the suffix of the label
-- | A label with a baked-in \/ algorithmically generated name that definitely
-- comes from the RTS. The code for it must compile into libHSrts.a \/ libHSrts.so
-- If it doesn't have an algorithmically generated name then use a CmmLabel
-- instead and give it an appropriate UnitId argument.
| RtsLabel
RtsLabelInfo
-- | A 'C' (or otherwise foreign) label.
--
| ForeignLabel
FastString -- name of the imported label.
(Maybe Int) -- possible '@n' suffix for stdcall functions
-- When generating C, the '@n' suffix is omitted, but when
-- generating assembler we must add it to the label.
ForeignLabelSource -- what package the foreign label is in.
FunctionOrData
-- | A family of labels related to a particular case expression.
| CaseLabel
{-# UNPACK #-} !Unique -- Unique says which case expression
CaseLabelInfo
| AsmTempLabel
{-# UNPACK #-} !Unique
| AsmTempDerivedLabel
CLabel
FastString -- suffix
| StringLitLabel
{-# UNPACK #-} !Unique
| PlainModuleInitLabel -- without the version & way info
Module
| CC_Label CostCentre
| CCS_Label CostCentreStack
-- | These labels are generated and used inside the NCG only.
-- They are special variants of a label used for dynamic linking
-- see module PositionIndependentCode for details.
| DynamicLinkerLabel DynamicLinkerLabelInfo CLabel
-- | This label is generated and used inside the NCG only.
-- It is used as a base for PIC calculations on some platforms.
-- It takes the form of a local numeric assembler label '1'; and
-- is pretty-printed as 1b, referring to the previous definition
-- of 1: in the assembler source file.
| PicBaseLabel
-- | A label before an info table to prevent excessive dead-stripping on darwin
| DeadStripPreventer CLabel
-- | Per-module table of tick locations
| HpcTicksLabel Module
-- | Static reference table
| SRTLabel !Unique
-- | Label of an StgLargeSRT
| LargeSRTLabel
{-# UNPACK #-} !Unique
-- | A bitmap (function or case return)
| LargeBitmapLabel
{-# UNPACK #-} !Unique
deriving Eq
-- This is laborious, but necessary. We can't derive Ord because
-- Unique doesn't have an Ord instance. Note nonDetCmpUnique in the
-- implementation. See Note [No Ord for Unique]
-- This is non-deterministic but we do not currently support deterministic
-- code-generation. See Note [Unique Determinism and code generation]
instance Ord CLabel where
compare (IdLabel a1 b1 c1) (IdLabel a2 b2 c2) =
compare a1 a2 `thenCmp`
compare b1 b2 `thenCmp`
compare c1 c2
compare (CmmLabel a1 b1 c1) (CmmLabel a2 b2 c2) =
compare a1 a2 `thenCmp`
compare b1 b2 `thenCmp`
compare c1 c2
compare (RtsLabel a1) (RtsLabel a2) = compare a1 a2
compare (ForeignLabel a1 b1 c1 d1) (ForeignLabel a2 b2 c2 d2) =
compare a1 a2 `thenCmp`
compare b1 b2 `thenCmp`
compare c1 c2 `thenCmp`
compare d1 d2
compare (CaseLabel u1 a1) (CaseLabel u2 a2) =
nonDetCmpUnique u1 u2 `thenCmp`
compare a1 a2
compare (AsmTempLabel u1) (AsmTempLabel u2) = nonDetCmpUnique u1 u2
compare (AsmTempDerivedLabel a1 b1) (AsmTempDerivedLabel a2 b2) =
compare a1 a2 `thenCmp`
compare b1 b2
compare (StringLitLabel u1) (StringLitLabel u2) =
nonDetCmpUnique u1 u2
compare (PlainModuleInitLabel a1) (PlainModuleInitLabel a2) =
compare a1 a2
compare (CC_Label a1) (CC_Label a2) =
compare a1 a2
compare (CCS_Label a1) (CCS_Label a2) =
compare a1 a2
compare (DynamicLinkerLabel a1 b1) (DynamicLinkerLabel a2 b2) =
compare a1 a2 `thenCmp`
compare b1 b2
compare PicBaseLabel PicBaseLabel = EQ
compare (DeadStripPreventer a1) (DeadStripPreventer a2) =
compare a1 a2
compare (HpcTicksLabel a1) (HpcTicksLabel a2) =
compare a1 a2
compare (SRTLabel u1) (SRTLabel u2) =
nonDetCmpUnique u1 u2
compare (LargeSRTLabel u1) (LargeSRTLabel u2) =
nonDetCmpUnique u1 u2
compare (LargeBitmapLabel u1) (LargeBitmapLabel u2) =
nonDetCmpUnique u1 u2
compare IdLabel{} _ = LT
compare _ IdLabel{} = GT
compare CmmLabel{} _ = LT
compare _ CmmLabel{} = GT
compare RtsLabel{} _ = LT
compare _ RtsLabel{} = GT
compare ForeignLabel{} _ = LT
compare _ ForeignLabel{} = GT
compare CaseLabel{} _ = LT
compare _ CaseLabel{} = GT
compare AsmTempLabel{} _ = LT
compare _ AsmTempLabel{} = GT
compare AsmTempDerivedLabel{} _ = LT
compare _ AsmTempDerivedLabel{} = GT
compare StringLitLabel{} _ = LT
compare _ StringLitLabel{} = GT
compare PlainModuleInitLabel{} _ = LT
compare _ PlainModuleInitLabel{} = GT
compare CC_Label{} _ = LT
compare _ CC_Label{} = GT
compare CCS_Label{} _ = LT
compare _ CCS_Label{} = GT
compare DynamicLinkerLabel{} _ = LT
compare _ DynamicLinkerLabel{} = GT
compare PicBaseLabel{} _ = LT
compare _ PicBaseLabel{} = GT
compare DeadStripPreventer{} _ = LT
compare _ DeadStripPreventer{} = GT
compare HpcTicksLabel{} _ = LT
compare _ HpcTicksLabel{} = GT
compare SRTLabel{} _ = LT
compare _ SRTLabel{} = GT
compare LargeSRTLabel{} _ = LT
compare _ LargeSRTLabel{} = GT
-- | Record where a foreign label is stored.
data ForeignLabelSource
-- | Label is in a named package
= ForeignLabelInPackage UnitId
-- | Label is in some external, system package that doesn't also
-- contain compiled Haskell code, and is not associated with any .hi files.
-- We don't have to worry about Haskell code being inlined from
-- external packages. It is safe to treat the RTS package as "external".
| ForeignLabelInExternalPackage
-- | Label is in the package currenly being compiled.
-- This is only used for creating hacky tmp labels during code generation.
-- Don't use it in any code that might be inlined across a package boundary
-- (ie, core code) else the information will be wrong relative to the
-- destination module.
| ForeignLabelInThisPackage
deriving (Eq, Ord)
-- | For debugging problems with the CLabel representation.
-- We can't make a Show instance for CLabel because lots of its components don't have instances.
-- The regular Outputable instance only shows the label name, and not its other info.
--
pprDebugCLabel :: CLabel -> SDoc
pprDebugCLabel lbl
= case lbl of
IdLabel{} -> ppr lbl <> (parens $ text "IdLabel")
CmmLabel pkg _name _info
-> ppr lbl <> (parens $ text "CmmLabel" <+> ppr pkg)
RtsLabel{} -> ppr lbl <> (parens $ text "RtsLabel")
ForeignLabel _name mSuffix src funOrData
-> ppr lbl <> (parens $ text "ForeignLabel"
<+> ppr mSuffix
<+> ppr src
<+> ppr funOrData)
_ -> ppr lbl <> (parens $ text "other CLabel)")
data IdLabelInfo
= Closure -- ^ Label for closure
| SRT -- ^ Static reference table (TODO: could be removed
-- with the old code generator, but might be needed
-- when we implement the New SRT Plan)
| InfoTable -- ^ Info tables for closures; always read-only
| Entry -- ^ Entry point
| Slow -- ^ Slow entry point
| LocalInfoTable -- ^ Like InfoTable but not externally visible
| LocalEntry -- ^ Like Entry but not externally visible
| RednCounts -- ^ Label of place to keep Ticky-ticky info for this Id
| ConEntry -- ^ Constructor entry point
| ConInfoTable -- ^ Corresponding info table
| StaticConEntry -- ^ Static constructor entry point
| StaticInfoTable -- ^ Corresponding info table
| ClosureTable -- ^ Table of closures for Enum tycons
deriving (Eq, Ord)
data CaseLabelInfo
= CaseReturnPt
| CaseReturnInfo
| CaseAlt ConTag
| CaseDefault
deriving (Eq, Ord)
data RtsLabelInfo
= RtsSelectorInfoTable Bool{-updatable-} Int{-offset-} -- ^ Selector thunks
| RtsSelectorEntry Bool{-updatable-} Int{-offset-}
| RtsApInfoTable Bool{-updatable-} Int{-arity-} -- ^ AP thunks
| RtsApEntry Bool{-updatable-} Int{-arity-}
| RtsPrimOp PrimOp
| RtsApFast FastString -- ^ _fast versions of generic apply
| RtsSlowFastTickyCtr String
deriving (Eq, Ord)
-- NOTE: Eq on LitString compares the pointer only, so this isn't
-- a real equality.
-- | What type of Cmm label we're dealing with.
-- Determines the suffix appended to the name when a CLabel.CmmLabel
-- is pretty printed.
data CmmLabelInfo
= CmmInfo -- ^ misc rts info tabless, suffix _info
| CmmEntry -- ^ misc rts entry points, suffix _entry
| CmmRetInfo -- ^ misc rts ret info tables, suffix _info
| CmmRet -- ^ misc rts return points, suffix _ret
| CmmData -- ^ misc rts data bits, eg CHARLIKE_closure
| CmmCode -- ^ misc rts code
| CmmClosure -- ^ closures eg CHARLIKE_closure
| CmmPrimCall -- ^ a prim call to some hand written Cmm code
deriving (Eq, Ord)
data DynamicLinkerLabelInfo
= CodeStub -- MachO: Lfoo$stub, ELF: foo@plt
| SymbolPtr -- MachO: Lfoo$non_lazy_ptr, Windows: __imp_foo
| GotSymbolPtr -- ELF: foo@got
| GotSymbolOffset -- ELF: foo@gotoff
deriving (Eq, Ord)
-- -----------------------------------------------------------------------------
-- Constructing CLabels
-- -----------------------------------------------------------------------------
-- Constructing IdLabels
-- These are always local:
mkSlowEntryLabel :: Name -> CafInfo -> CLabel
mkSlowEntryLabel name c = IdLabel name c Slow
mkTopSRTLabel :: Unique -> CLabel
mkTopSRTLabel u = SRTLabel u
mkSRTLabel :: Name -> CafInfo -> CLabel
mkRednCountsLabel :: Name -> CLabel
mkSRTLabel name c = IdLabel name c SRT
mkRednCountsLabel name =
IdLabel name NoCafRefs RednCounts -- Note [ticky for LNE]
-- These have local & (possibly) external variants:
mkLocalClosureLabel :: Name -> CafInfo -> CLabel
mkLocalInfoTableLabel :: Name -> CafInfo -> CLabel
mkLocalEntryLabel :: Name -> CafInfo -> CLabel
mkLocalClosureTableLabel :: Name -> CafInfo -> CLabel
mkLocalClosureLabel name c = IdLabel name c Closure
mkLocalInfoTableLabel name c = IdLabel name c LocalInfoTable
mkLocalEntryLabel name c = IdLabel name c LocalEntry
mkLocalClosureTableLabel name c = IdLabel name c ClosureTable
mkClosureLabel :: Name -> CafInfo -> CLabel
mkInfoTableLabel :: Name -> CafInfo -> CLabel
mkEntryLabel :: Name -> CafInfo -> CLabel
mkClosureTableLabel :: Name -> CafInfo -> CLabel
mkLocalConInfoTableLabel :: CafInfo -> Name -> CLabel
mkLocalConEntryLabel :: CafInfo -> Name -> CLabel
mkLocalStaticInfoTableLabel :: CafInfo -> Name -> CLabel
mkLocalStaticConEntryLabel :: CafInfo -> Name -> CLabel
mkConInfoTableLabel :: Name -> CafInfo -> CLabel
mkStaticInfoTableLabel :: Name -> CafInfo -> CLabel
mkClosureLabel name c = IdLabel name c Closure
mkInfoTableLabel name c = IdLabel name c InfoTable
mkEntryLabel name c = IdLabel name c Entry
mkClosureTableLabel name c = IdLabel name c ClosureTable
mkLocalConInfoTableLabel c con = IdLabel con c ConInfoTable
mkLocalConEntryLabel c con = IdLabel con c ConEntry
mkLocalStaticInfoTableLabel c con = IdLabel con c StaticInfoTable
mkLocalStaticConEntryLabel c con = IdLabel con c StaticConEntry
mkConInfoTableLabel name c = IdLabel name c ConInfoTable
mkStaticInfoTableLabel name c = IdLabel name c StaticInfoTable
mkConEntryLabel :: Name -> CafInfo -> CLabel
mkStaticConEntryLabel :: Name -> CafInfo -> CLabel
mkConEntryLabel name c = IdLabel name c ConEntry
mkStaticConEntryLabel name c = IdLabel name c StaticConEntry
-- Constructing Cmm Labels
mkDirty_MUT_VAR_Label, mkSplitMarkerLabel, mkUpdInfoLabel,
mkBHUpdInfoLabel, mkIndStaticInfoLabel, mkMainCapabilityLabel,
mkMAP_FROZEN_infoLabel, mkMAP_FROZEN0_infoLabel, mkMAP_DIRTY_infoLabel,
mkEMPTY_MVAR_infoLabel, mkTopTickyCtrLabel,
mkCAFBlackHoleInfoTableLabel, mkCAFBlackHoleEntryLabel,
mkArrWords_infoLabel, mkSMAP_FROZEN_infoLabel, mkSMAP_FROZEN0_infoLabel,
mkSMAP_DIRTY_infoLabel, mkRUBBISH_ENTRY_infoLabel :: CLabel
mkDirty_MUT_VAR_Label = mkForeignLabel (fsLit "dirty_MUT_VAR") Nothing ForeignLabelInExternalPackage IsFunction
mkSplitMarkerLabel = CmmLabel rtsUnitId (fsLit "__stg_split_marker") CmmCode
mkUpdInfoLabel = CmmLabel rtsUnitId (fsLit "stg_upd_frame") CmmInfo
mkBHUpdInfoLabel = CmmLabel rtsUnitId (fsLit "stg_bh_upd_frame" ) CmmInfo
mkIndStaticInfoLabel = CmmLabel rtsUnitId (fsLit "stg_IND_STATIC") CmmInfo
mkMainCapabilityLabel = CmmLabel rtsUnitId (fsLit "MainCapability") CmmData
mkMAP_FROZEN_infoLabel = CmmLabel rtsUnitId (fsLit "stg_MUT_ARR_PTRS_FROZEN") CmmInfo
mkMAP_FROZEN0_infoLabel = CmmLabel rtsUnitId (fsLit "stg_MUT_ARR_PTRS_FROZEN0") CmmInfo
mkMAP_DIRTY_infoLabel = CmmLabel rtsUnitId (fsLit "stg_MUT_ARR_PTRS_DIRTY") CmmInfo
mkEMPTY_MVAR_infoLabel = CmmLabel rtsUnitId (fsLit "stg_EMPTY_MVAR") CmmInfo
mkTopTickyCtrLabel = CmmLabel rtsUnitId (fsLit "top_ct") CmmData
mkCAFBlackHoleInfoTableLabel = CmmLabel rtsUnitId (fsLit "stg_CAF_BLACKHOLE") CmmInfo
mkCAFBlackHoleEntryLabel = CmmLabel rtsUnitId (fsLit "stg_CAF_BLACKHOLE") CmmEntry
mkArrWords_infoLabel = CmmLabel rtsUnitId (fsLit "stg_ARR_WORDS") CmmInfo
mkSMAP_FROZEN_infoLabel = CmmLabel rtsUnitId (fsLit "stg_SMALL_MUT_ARR_PTRS_FROZEN") CmmInfo
mkSMAP_FROZEN0_infoLabel = CmmLabel rtsUnitId (fsLit "stg_SMALL_MUT_ARR_PTRS_FROZEN0") CmmInfo
mkSMAP_DIRTY_infoLabel = CmmLabel rtsUnitId (fsLit "stg_SMALL_MUT_ARR_PTRS_DIRTY") CmmInfo
mkRUBBISH_ENTRY_infoLabel = CmmLabel rtsUnitId (fsLit "stg_RUBBISH_ENTRY") CmmInfo
-----
mkCmmInfoLabel, mkCmmEntryLabel, mkCmmRetInfoLabel, mkCmmRetLabel,
mkCmmCodeLabel, mkCmmDataLabel, mkCmmClosureLabel
:: UnitId -> FastString -> CLabel
mkCmmInfoLabel pkg str = CmmLabel pkg str CmmInfo
mkCmmEntryLabel pkg str = CmmLabel pkg str CmmEntry
mkCmmRetInfoLabel pkg str = CmmLabel pkg str CmmRetInfo
mkCmmRetLabel pkg str = CmmLabel pkg str CmmRet
mkCmmCodeLabel pkg str = CmmLabel pkg str CmmCode
mkCmmDataLabel pkg str = CmmLabel pkg str CmmData
mkCmmClosureLabel pkg str = CmmLabel pkg str CmmClosure
-- Constructing RtsLabels
mkRtsPrimOpLabel :: PrimOp -> CLabel
mkRtsPrimOpLabel primop = RtsLabel (RtsPrimOp primop)
mkSelectorInfoLabel :: Bool -> Int -> CLabel
mkSelectorEntryLabel :: Bool -> Int -> CLabel
mkSelectorInfoLabel upd off = RtsLabel (RtsSelectorInfoTable upd off)
mkSelectorEntryLabel upd off = RtsLabel (RtsSelectorEntry upd off)
mkApInfoTableLabel :: Bool -> Int -> CLabel
mkApEntryLabel :: Bool -> Int -> CLabel
mkApInfoTableLabel upd off = RtsLabel (RtsApInfoTable upd off)
mkApEntryLabel upd off = RtsLabel (RtsApEntry upd off)
-- A call to some primitive hand written Cmm code
mkPrimCallLabel :: PrimCall -> CLabel
mkPrimCallLabel (PrimCall str pkg)
= CmmLabel pkg str CmmPrimCall
-- Constructing ForeignLabels
-- | Make a foreign label
mkForeignLabel
:: FastString -- name
-> Maybe Int -- size prefix
-> ForeignLabelSource -- what package it's in
-> FunctionOrData
-> CLabel
mkForeignLabel str mb_sz src fod
= ForeignLabel str mb_sz src fod
-- | Update the label size field in a ForeignLabel
addLabelSize :: CLabel -> Int -> CLabel
addLabelSize (ForeignLabel str _ src fod) sz
= ForeignLabel str (Just sz) src fod
addLabelSize label _
= label
-- | Whether label is a non-haskell label (defined in C code)
isForeignLabel :: CLabel -> Bool
isForeignLabel (ForeignLabel _ _ _ _) = True
isForeignLabel _lbl = False
-- | Get the label size field from a ForeignLabel
foreignLabelStdcallInfo :: CLabel -> Maybe Int
foreignLabelStdcallInfo (ForeignLabel _ info _ _) = info
foreignLabelStdcallInfo _lbl = Nothing
-- Constructing Large*Labels
mkLargeSRTLabel :: Unique -> CLabel
mkBitmapLabel :: Unique -> CLabel
mkLargeSRTLabel uniq = LargeSRTLabel uniq
mkBitmapLabel uniq = LargeBitmapLabel uniq
-- Constructin CaseLabels
mkReturnPtLabel :: Unique -> CLabel
mkReturnInfoLabel :: Unique -> CLabel
mkAltLabel :: Unique -> ConTag -> CLabel
mkDefaultLabel :: Unique -> CLabel
mkReturnPtLabel uniq = CaseLabel uniq CaseReturnPt
mkReturnInfoLabel uniq = CaseLabel uniq CaseReturnInfo
mkAltLabel uniq tag = CaseLabel uniq (CaseAlt tag)
mkDefaultLabel uniq = CaseLabel uniq CaseDefault
-- Constructing Cost Center Labels
mkCCLabel :: CostCentre -> CLabel
mkCCSLabel :: CostCentreStack -> CLabel
mkCCLabel cc = CC_Label cc
mkCCSLabel ccs = CCS_Label ccs
mkRtsApFastLabel :: FastString -> CLabel
mkRtsApFastLabel str = RtsLabel (RtsApFast str)
mkRtsSlowFastTickyCtrLabel :: String -> CLabel
mkRtsSlowFastTickyCtrLabel pat = RtsLabel (RtsSlowFastTickyCtr pat)
-- Constructing Code Coverage Labels
mkHpcTicksLabel :: Module -> CLabel
mkHpcTicksLabel = HpcTicksLabel
-- Constructing labels used for dynamic linking
mkDynamicLinkerLabel :: DynamicLinkerLabelInfo -> CLabel -> CLabel
mkDynamicLinkerLabel = DynamicLinkerLabel
dynamicLinkerLabelInfo :: CLabel -> Maybe (DynamicLinkerLabelInfo, CLabel)
dynamicLinkerLabelInfo (DynamicLinkerLabel info lbl) = Just (info, lbl)
dynamicLinkerLabelInfo _ = Nothing
mkPicBaseLabel :: CLabel
mkPicBaseLabel = PicBaseLabel
-- Constructing miscellaneous other labels
mkDeadStripPreventer :: CLabel -> CLabel
mkDeadStripPreventer lbl = DeadStripPreventer lbl
mkStringLitLabel :: Unique -> CLabel
mkStringLitLabel = StringLitLabel
mkAsmTempLabel :: Uniquable a => a -> CLabel
mkAsmTempLabel a = AsmTempLabel (getUnique a)
mkAsmTempDerivedLabel :: CLabel -> FastString -> CLabel
mkAsmTempDerivedLabel = AsmTempDerivedLabel
mkAsmTempEndLabel :: CLabel -> CLabel
mkAsmTempEndLabel l = mkAsmTempDerivedLabel l (fsLit "_end")
mkPlainModuleInitLabel :: Module -> CLabel
mkPlainModuleInitLabel mod = PlainModuleInitLabel mod
-- | Construct a label for a DWARF Debug Information Entity (DIE)
-- describing another symbol.
mkAsmTempDieLabel :: CLabel -> CLabel
mkAsmTempDieLabel l = mkAsmTempDerivedLabel l (fsLit "_die")
-- -----------------------------------------------------------------------------
-- Convert between different kinds of label
toClosureLbl :: CLabel -> CLabel
toClosureLbl (IdLabel n c _) = IdLabel n c Closure
toClosureLbl (CmmLabel m str _) = CmmLabel m str CmmClosure
toClosureLbl l = pprPanic "toClosureLbl" (ppr l)
toSlowEntryLbl :: CLabel -> CLabel
toSlowEntryLbl (IdLabel n c _) = IdLabel n c Slow
toSlowEntryLbl l = pprPanic "toSlowEntryLbl" (ppr l)
toEntryLbl :: CLabel -> CLabel
toEntryLbl (IdLabel n c LocalInfoTable) = IdLabel n c LocalEntry
toEntryLbl (IdLabel n c ConInfoTable) = IdLabel n c ConEntry
toEntryLbl (IdLabel n c StaticInfoTable) = IdLabel n c StaticConEntry
toEntryLbl (IdLabel n c _) = IdLabel n c Entry
toEntryLbl (CaseLabel n CaseReturnInfo) = CaseLabel n CaseReturnPt
toEntryLbl (CmmLabel m str CmmInfo) = CmmLabel m str CmmEntry
toEntryLbl (CmmLabel m str CmmRetInfo) = CmmLabel m str CmmRet
toEntryLbl l = pprPanic "toEntryLbl" (ppr l)
toInfoLbl :: CLabel -> CLabel
toInfoLbl (IdLabel n c Entry) = IdLabel n c InfoTable
toInfoLbl (IdLabel n c LocalEntry) = IdLabel n c LocalInfoTable
toInfoLbl (IdLabel n c ConEntry) = IdLabel n c ConInfoTable
toInfoLbl (IdLabel n c StaticConEntry) = IdLabel n c StaticInfoTable
toInfoLbl (IdLabel n c _) = IdLabel n c InfoTable
toInfoLbl (CaseLabel n CaseReturnPt) = CaseLabel n CaseReturnInfo
toInfoLbl (CmmLabel m str CmmEntry) = CmmLabel m str CmmInfo
toInfoLbl (CmmLabel m str CmmRet) = CmmLabel m str CmmRetInfo
toInfoLbl l = pprPanic "CLabel.toInfoLbl" (ppr l)
toRednCountsLbl :: CLabel -> Maybe CLabel
toRednCountsLbl = fmap mkRednCountsLabel . hasHaskellName
hasHaskellName :: CLabel -> Maybe Name
hasHaskellName (IdLabel n _ _) = Just n
hasHaskellName _ = Nothing
-- -----------------------------------------------------------------------------
-- Does a CLabel's referent itself refer to a CAF?
hasCAF :: CLabel -> Bool
hasCAF (IdLabel _ _ RednCounts) = False -- Note [ticky for LNE]
hasCAF (IdLabel _ MayHaveCafRefs _) = True
hasCAF _ = False
-- Note [ticky for LNE]
-- ~~~~~~~~~~~~~~~~~~~~~
-- Until 14 Feb 2013, every ticky counter was associated with a
-- closure. Thus, ticky labels used IdLabel. It is odd that
-- CmmBuildInfoTables.cafTransfers would consider such a ticky label
-- reason to add the name to the CAFEnv (and thus eventually the SRT),
-- but it was harmless because the ticky was only used if the closure
-- was also.
--
-- Since we now have ticky counters for LNEs, it is no longer the case
-- that every ticky counter has an actual closure. So I changed the
-- generation of ticky counters' CLabels to not result in their
-- associated id ending up in the SRT.
--
-- NB IdLabel is still appropriate for ticky ids (as opposed to
-- CmmLabel) because the LNE's counter is still related to an .hs Id,
-- that Id just isn't for a proper closure.
-- -----------------------------------------------------------------------------
-- Does a CLabel need declaring before use or not?
--
-- See wiki:Commentary/Compiler/Backends/PprC#Prototypes
needsCDecl :: CLabel -> Bool
-- False <=> it's pre-declared; don't bother
-- don't bother declaring Bitmap labels, we always make sure
-- they are defined before use.
needsCDecl (SRTLabel _) = True
needsCDecl (LargeSRTLabel _) = False
needsCDecl (LargeBitmapLabel _) = False
needsCDecl (IdLabel _ _ _) = True
needsCDecl (CaseLabel _ _) = True
needsCDecl (PlainModuleInitLabel _) = True
needsCDecl (StringLitLabel _) = False
needsCDecl (AsmTempLabel _) = False
needsCDecl (AsmTempDerivedLabel _ _) = False
needsCDecl (RtsLabel _) = False
needsCDecl (CmmLabel pkgId _ _)
-- Prototypes for labels defined in the runtime system are imported
-- into HC files via includes/Stg.h.
| pkgId == rtsUnitId = False
-- For other labels we inline one into the HC file directly.
| otherwise = True
needsCDecl l@(ForeignLabel{}) = not (isMathFun l)
needsCDecl (CC_Label _) = True
needsCDecl (CCS_Label _) = True
needsCDecl (HpcTicksLabel _) = True
needsCDecl (DynamicLinkerLabel {}) = panic "needsCDecl DynamicLinkerLabel"
needsCDecl PicBaseLabel = panic "needsCDecl PicBaseLabel"
needsCDecl (DeadStripPreventer {}) = panic "needsCDecl DeadStripPreventer"
-- | If a label is a local temporary used for native code generation
-- then return just its unique, otherwise nothing.
maybeAsmTemp :: CLabel -> Maybe Unique
maybeAsmTemp (AsmTempLabel uq) = Just uq
maybeAsmTemp _ = Nothing
-- | Check whether a label corresponds to a C function that has
-- a prototype in a system header somehere, or is built-in
-- to the C compiler. For these labels we avoid generating our
-- own C prototypes.
isMathFun :: CLabel -> Bool
isMathFun (ForeignLabel fs _ _ _) = fs `elementOfUniqSet` math_funs
isMathFun _ = False
math_funs :: UniqSet FastString
math_funs = mkUniqSet [
-- _ISOC99_SOURCE
(fsLit "acos"), (fsLit "acosf"), (fsLit "acosh"),
(fsLit "acoshf"), (fsLit "acoshl"), (fsLit "acosl"),
(fsLit "asin"), (fsLit "asinf"), (fsLit "asinl"),
(fsLit "asinh"), (fsLit "asinhf"), (fsLit "asinhl"),
(fsLit "atan"), (fsLit "atanf"), (fsLit "atanl"),
(fsLit "atan2"), (fsLit "atan2f"), (fsLit "atan2l"),
(fsLit "atanh"), (fsLit "atanhf"), (fsLit "atanhl"),
(fsLit "cbrt"), (fsLit "cbrtf"), (fsLit "cbrtl"),
(fsLit "ceil"), (fsLit "ceilf"), (fsLit "ceill"),
(fsLit "copysign"), (fsLit "copysignf"), (fsLit "copysignl"),
(fsLit "cos"), (fsLit "cosf"), (fsLit "cosl"),
(fsLit "cosh"), (fsLit "coshf"), (fsLit "coshl"),
(fsLit "erf"), (fsLit "erff"), (fsLit "erfl"),
(fsLit "erfc"), (fsLit "erfcf"), (fsLit "erfcl"),
(fsLit "exp"), (fsLit "expf"), (fsLit "expl"),
(fsLit "exp2"), (fsLit "exp2f"), (fsLit "exp2l"),
(fsLit "expm1"), (fsLit "expm1f"), (fsLit "expm1l"),
(fsLit "fabs"), (fsLit "fabsf"), (fsLit "fabsl"),
(fsLit "fdim"), (fsLit "fdimf"), (fsLit "fdiml"),
(fsLit "floor"), (fsLit "floorf"), (fsLit "floorl"),
(fsLit "fma"), (fsLit "fmaf"), (fsLit "fmal"),
(fsLit "fmax"), (fsLit "fmaxf"), (fsLit "fmaxl"),
(fsLit "fmin"), (fsLit "fminf"), (fsLit "fminl"),
(fsLit "fmod"), (fsLit "fmodf"), (fsLit "fmodl"),
(fsLit "frexp"), (fsLit "frexpf"), (fsLit "frexpl"),
(fsLit "hypot"), (fsLit "hypotf"), (fsLit "hypotl"),
(fsLit "ilogb"), (fsLit "ilogbf"), (fsLit "ilogbl"),
(fsLit "ldexp"), (fsLit "ldexpf"), (fsLit "ldexpl"),
(fsLit "lgamma"), (fsLit "lgammaf"), (fsLit "lgammal"),
(fsLit "llrint"), (fsLit "llrintf"), (fsLit "llrintl"),
(fsLit "llround"), (fsLit "llroundf"), (fsLit "llroundl"),
(fsLit "log"), (fsLit "logf"), (fsLit "logl"),
(fsLit "log10l"), (fsLit "log10"), (fsLit "log10f"),
(fsLit "log1pl"), (fsLit "log1p"), (fsLit "log1pf"),
(fsLit "log2"), (fsLit "log2f"), (fsLit "log2l"),
(fsLit "logb"), (fsLit "logbf"), (fsLit "logbl"),
(fsLit "lrint"), (fsLit "lrintf"), (fsLit "lrintl"),
(fsLit "lround"), (fsLit "lroundf"), (fsLit "lroundl"),
(fsLit "modf"), (fsLit "modff"), (fsLit "modfl"),
(fsLit "nan"), (fsLit "nanf"), (fsLit "nanl"),
(fsLit "nearbyint"), (fsLit "nearbyintf"), (fsLit "nearbyintl"),
(fsLit "nextafter"), (fsLit "nextafterf"), (fsLit "nextafterl"),
(fsLit "nexttoward"), (fsLit "nexttowardf"), (fsLit "nexttowardl"),
(fsLit "pow"), (fsLit "powf"), (fsLit "powl"),
(fsLit "remainder"), (fsLit "remainderf"), (fsLit "remainderl"),
(fsLit "remquo"), (fsLit "remquof"), (fsLit "remquol"),
(fsLit "rint"), (fsLit "rintf"), (fsLit "rintl"),
(fsLit "round"), (fsLit "roundf"), (fsLit "roundl"),
(fsLit "scalbln"), (fsLit "scalblnf"), (fsLit "scalblnl"),
(fsLit "scalbn"), (fsLit "scalbnf"), (fsLit "scalbnl"),
(fsLit "sin"), (fsLit "sinf"), (fsLit "sinl"),
(fsLit "sinh"), (fsLit "sinhf"), (fsLit "sinhl"),
(fsLit "sqrt"), (fsLit "sqrtf"), (fsLit "sqrtl"),
(fsLit "tan"), (fsLit "tanf"), (fsLit "tanl"),
(fsLit "tanh"), (fsLit "tanhf"), (fsLit "tanhl"),
(fsLit "tgamma"), (fsLit "tgammaf"), (fsLit "tgammal"),
(fsLit "trunc"), (fsLit "truncf"), (fsLit "truncl"),
-- ISO C 99 also defines these function-like macros in math.h:
-- fpclassify, isfinite, isinf, isnormal, signbit, isgreater,
-- isgreaterequal, isless, islessequal, islessgreater, isunordered
-- additional symbols from _BSD_SOURCE
(fsLit "drem"), (fsLit "dremf"), (fsLit "dreml"),
(fsLit "finite"), (fsLit "finitef"), (fsLit "finitel"),
(fsLit "gamma"), (fsLit "gammaf"), (fsLit "gammal"),
(fsLit "isinf"), (fsLit "isinff"), (fsLit "isinfl"),
(fsLit "isnan"), (fsLit "isnanf"), (fsLit "isnanl"),
(fsLit "j0"), (fsLit "j0f"), (fsLit "j0l"),
(fsLit "j1"), (fsLit "j1f"), (fsLit "j1l"),
(fsLit "jn"), (fsLit "jnf"), (fsLit "jnl"),
(fsLit "lgamma_r"), (fsLit "lgammaf_r"), (fsLit "lgammal_r"),
(fsLit "scalb"), (fsLit "scalbf"), (fsLit "scalbl"),
(fsLit "significand"), (fsLit "significandf"), (fsLit "significandl"),
(fsLit "y0"), (fsLit "y0f"), (fsLit "y0l"),
(fsLit "y1"), (fsLit "y1f"), (fsLit "y1l"),
(fsLit "yn"), (fsLit "ynf"), (fsLit "ynl")
]
-- -----------------------------------------------------------------------------
-- | Is a CLabel visible outside this object file or not?
-- From the point of view of the code generator, a name is
-- externally visible if it has to be declared as exported
-- in the .o file's symbol table; that is, made non-static.
externallyVisibleCLabel :: CLabel -> Bool -- not C "static"
externallyVisibleCLabel (CaseLabel _ _) = False
externallyVisibleCLabel (StringLitLabel _) = False
externallyVisibleCLabel (AsmTempLabel _) = False
externallyVisibleCLabel (AsmTempDerivedLabel _ _)= False
externallyVisibleCLabel (PlainModuleInitLabel _)= True
externallyVisibleCLabel (RtsLabel _) = True
externallyVisibleCLabel (CmmLabel _ _ _) = True
externallyVisibleCLabel (ForeignLabel{}) = True
externallyVisibleCLabel (IdLabel name _ info) = isExternalName name && externallyVisibleIdLabel info
externallyVisibleCLabel (CC_Label _) = True
externallyVisibleCLabel (CCS_Label _) = True
externallyVisibleCLabel (DynamicLinkerLabel _ _) = False
externallyVisibleCLabel (HpcTicksLabel _) = True
externallyVisibleCLabel (LargeBitmapLabel _) = False
externallyVisibleCLabel (SRTLabel _) = False
externallyVisibleCLabel (LargeSRTLabel _) = False
externallyVisibleCLabel (PicBaseLabel {}) = panic "externallyVisibleCLabel PicBaseLabel"
externallyVisibleCLabel (DeadStripPreventer {}) = panic "externallyVisibleCLabel DeadStripPreventer"
externallyVisibleIdLabel :: IdLabelInfo -> Bool
externallyVisibleIdLabel SRT = False
externallyVisibleIdLabel LocalInfoTable = False
externallyVisibleIdLabel LocalEntry = False
externallyVisibleIdLabel _ = True
-- -----------------------------------------------------------------------------
-- Finding the "type" of a CLabel
-- For generating correct types in label declarations:
data CLabelType
= CodeLabel -- Address of some executable instructions
| DataLabel -- Address of data, not a GC ptr
| GcPtrLabel -- Address of a (presumably static) GC object
isCFunctionLabel :: CLabel -> Bool
isCFunctionLabel lbl = case labelType lbl of
CodeLabel -> True
_other -> False
isGcPtrLabel :: CLabel -> Bool
isGcPtrLabel lbl = case labelType lbl of
GcPtrLabel -> True
_other -> False
-- | Work out the general type of data at the address of this label
-- whether it be code, data, or static GC object.
labelType :: CLabel -> CLabelType
labelType (CmmLabel _ _ CmmData) = DataLabel
labelType (CmmLabel _ _ CmmClosure) = GcPtrLabel
labelType (CmmLabel _ _ CmmCode) = CodeLabel
labelType (CmmLabel _ _ CmmInfo) = DataLabel
labelType (CmmLabel _ _ CmmEntry) = CodeLabel
labelType (CmmLabel _ _ CmmPrimCall) = CodeLabel
labelType (CmmLabel _ _ CmmRetInfo) = DataLabel
labelType (CmmLabel _ _ CmmRet) = CodeLabel
labelType (RtsLabel (RtsSelectorInfoTable _ _)) = DataLabel
labelType (RtsLabel (RtsApInfoTable _ _)) = DataLabel
labelType (RtsLabel (RtsApFast _)) = CodeLabel
labelType (CaseLabel _ CaseReturnInfo) = DataLabel
labelType (CaseLabel _ _) = CodeLabel
labelType (PlainModuleInitLabel _) = CodeLabel
labelType (SRTLabel _) = DataLabel
labelType (LargeSRTLabel _) = DataLabel
labelType (LargeBitmapLabel _) = DataLabel
labelType (ForeignLabel _ _ _ IsFunction) = CodeLabel
labelType (IdLabel _ _ info) = idInfoLabelType info
labelType _ = DataLabel
idInfoLabelType :: IdLabelInfo -> CLabelType
idInfoLabelType info =
case info of
InfoTable -> DataLabel
LocalInfoTable -> DataLabel
Closure -> GcPtrLabel
ConInfoTable -> DataLabel
StaticInfoTable -> DataLabel
ClosureTable -> DataLabel
RednCounts -> DataLabel
_ -> CodeLabel
-- -----------------------------------------------------------------------------
-- Does a CLabel need dynamic linkage?
-- When referring to data in code, we need to know whether
-- that data resides in a DLL or not. [Win32 only.]
-- @labelDynamic@ returns @True@ if the label is located
-- in a DLL, be it a data reference or not.
labelDynamic :: DynFlags -> UnitId -> Module -> CLabel -> Bool
labelDynamic dflags this_pkg this_mod lbl =
case lbl of
-- is the RTS in a DLL or not?
RtsLabel _ -> (WayDyn `elem` ways dflags) && (this_pkg /= rtsUnitId)
IdLabel n _ _ -> isDllName dflags this_pkg this_mod n
-- When compiling in the "dyn" way, each package is to be linked into
-- its own shared library.
CmmLabel pkg _ _
| os == OSMinGW32 ->
(WayDyn `elem` ways dflags) && (this_pkg /= pkg)
| otherwise ->
True
ForeignLabel _ _ source _ ->
if os == OSMinGW32
then case source of
-- Foreign label is in some un-named foreign package (or DLL).
ForeignLabelInExternalPackage -> True
-- Foreign label is linked into the same package as the
-- source file currently being compiled.
ForeignLabelInThisPackage -> False
-- Foreign label is in some named package.
-- When compiling in the "dyn" way, each package is to be
-- linked into its own DLL.
ForeignLabelInPackage pkgId ->
(WayDyn `elem` ways dflags) && (this_pkg /= pkgId)
else -- On Mac OS X and on ELF platforms, false positives are OK,
-- so we claim that all foreign imports come from dynamic
-- libraries
True
PlainModuleInitLabel m -> (WayDyn `elem` ways dflags) && this_pkg /= (moduleUnitId m)
HpcTicksLabel m -> (WayDyn `elem` ways dflags) && this_mod /= m
-- Note that DynamicLinkerLabels do NOT require dynamic linking themselves.
_ -> False
where os = platformOS (targetPlatform dflags)
-----------------------------------------------------------------------------
-- Printing out CLabels.
{-
Convention:
<name>_<type>
where <name> is <Module>_<name> for external names and <unique> for
internal names. <type> is one of the following:
info Info table
srt Static reference table
srtd Static reference table descriptor
entry Entry code (function, closure)
slow Slow entry code (if any)
ret Direct return address
vtbl Vector table
<n>_alt Case alternative (tag n)
dflt Default case alternative
btm Large bitmap vector
closure Static closure
con_entry Dynamic Constructor entry code
con_info Dynamic Constructor info table
static_entry Static Constructor entry code
static_info Static Constructor info table
sel_info Selector info table
sel_entry Selector entry code
cc Cost centre
ccs Cost centre stack
Many of these distinctions are only for documentation reasons. For
example, _ret is only distinguished from _entry to make it easy to
tell whether a code fragment is a return point or a closure/function
entry.
Note [Closure and info labels]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For a function 'foo, we have:
foo_info : Points to the info table describing foo's closure
(and entry code for foo with tables next to code)
foo_closure : Static (no-free-var) closure only:
points to the statically-allocated closure
For a data constructor (such as Just or Nothing), we have:
Just_con_info: Info table for the data constructor itself
the first word of a heap-allocated Just
Just_info: Info table for the *worker function*, an
ordinary Haskell function of arity 1 that
allocates a (Just x) box:
Just = \x -> Just x
Just_closure: The closure for this worker
Nothing_closure: a statically allocated closure for Nothing
Nothing_static_info: info table for Nothing_closure
All these must be exported symbol, EXCEPT Just_info. We don't need to
export this because in other modules we either have
* A reference to 'Just'; use Just_closure
* A saturated call 'Just x'; allocate using Just_con_info
Not exporting these Just_info labels reduces the number of symbols
somewhat.
-}
instance Outputable CLabel where
ppr c = sdocWithPlatform $ \platform -> pprCLabel platform c
pprCLabel :: Platform -> CLabel -> SDoc
pprCLabel platform (AsmTempLabel u)
| cGhcWithNativeCodeGen == "YES"
= getPprStyle $ \ sty ->
if asmStyle sty then
ptext (asmTempLabelPrefix platform) <> pprUnique u
else
char '_' <> pprUnique u
pprCLabel platform (AsmTempDerivedLabel l suf)
| cGhcWithNativeCodeGen == "YES"
= ptext (asmTempLabelPrefix platform)
<> case l of AsmTempLabel u -> pprUnique u
_other -> pprCLabel platform l
<> ftext suf
pprCLabel platform (DynamicLinkerLabel info lbl)
| cGhcWithNativeCodeGen == "YES"
= pprDynamicLinkerAsmLabel platform info lbl
pprCLabel _ PicBaseLabel
| cGhcWithNativeCodeGen == "YES"
= text "1b"
pprCLabel platform (DeadStripPreventer lbl)
| cGhcWithNativeCodeGen == "YES"
= pprCLabel platform lbl <> text "_dsp"
pprCLabel platform lbl
= getPprStyle $ \ sty ->
if cGhcWithNativeCodeGen == "YES" && asmStyle sty
then maybe_underscore (pprAsmCLbl platform lbl)
else pprCLbl lbl
maybe_underscore :: SDoc -> SDoc
maybe_underscore doc
| underscorePrefix = pp_cSEP <> doc
| otherwise = doc
pprAsmCLbl :: Platform -> CLabel -> SDoc
pprAsmCLbl platform (ForeignLabel fs (Just sz) _ _)
| platformOS platform == OSMinGW32
-- In asm mode, we need to put the suffix on a stdcall ForeignLabel.
-- (The C compiler does this itself).
= ftext fs <> char '@' <> int sz
pprAsmCLbl _ lbl
= pprCLbl lbl
pprCLbl :: CLabel -> SDoc
pprCLbl (StringLitLabel u)
= pprUnique u <> text "_str"
pprCLbl (CaseLabel u CaseReturnPt)
= hcat [pprUnique u, text "_ret"]
pprCLbl (CaseLabel u CaseReturnInfo)
= hcat [pprUnique u, text "_info"]
pprCLbl (CaseLabel u (CaseAlt tag))
= hcat [pprUnique u, pp_cSEP, int tag, text "_alt"]
pprCLbl (CaseLabel u CaseDefault)
= hcat [pprUnique u, text "_dflt"]
pprCLbl (SRTLabel u)
= pprUnique u <> pp_cSEP <> text "srt"
pprCLbl (LargeSRTLabel u) = pprUnique u <> pp_cSEP <> text "srtd"
pprCLbl (LargeBitmapLabel u) = text "b" <> pprUnique u <> pp_cSEP <> text "btm"
-- Some bitsmaps for tuple constructors have a numeric tag (e.g. '7')
-- until that gets resolved we'll just force them to start
-- with a letter so the label will be legal assmbly code.
pprCLbl (CmmLabel _ str CmmCode) = ftext str
pprCLbl (CmmLabel _ str CmmData) = ftext str
pprCLbl (CmmLabel _ str CmmPrimCall) = ftext str
pprCLbl (RtsLabel (RtsApFast str)) = ftext str <> text "_fast"
pprCLbl (RtsLabel (RtsSelectorInfoTable upd_reqd offset))
= sdocWithDynFlags $ \dflags ->
ASSERT(offset >= 0 && offset <= mAX_SPEC_SELECTEE_SIZE dflags)
hcat [text "stg_sel_", text (show offset),
ptext (if upd_reqd
then (sLit "_upd_info")
else (sLit "_noupd_info"))
]
pprCLbl (RtsLabel (RtsSelectorEntry upd_reqd offset))
= sdocWithDynFlags $ \dflags ->
ASSERT(offset >= 0 && offset <= mAX_SPEC_SELECTEE_SIZE dflags)
hcat [text "stg_sel_", text (show offset),
ptext (if upd_reqd
then (sLit "_upd_entry")
else (sLit "_noupd_entry"))
]
pprCLbl (RtsLabel (RtsApInfoTable upd_reqd arity))
= sdocWithDynFlags $ \dflags ->
ASSERT(arity > 0 && arity <= mAX_SPEC_AP_SIZE dflags)
hcat [text "stg_ap_", text (show arity),
ptext (if upd_reqd
then (sLit "_upd_info")
else (sLit "_noupd_info"))
]
pprCLbl (RtsLabel (RtsApEntry upd_reqd arity))
= sdocWithDynFlags $ \dflags ->
ASSERT(arity > 0 && arity <= mAX_SPEC_AP_SIZE dflags)
hcat [text "stg_ap_", text (show arity),
ptext (if upd_reqd
then (sLit "_upd_entry")
else (sLit "_noupd_entry"))
]
pprCLbl (CmmLabel _ fs CmmInfo)
= ftext fs <> text "_info"
pprCLbl (CmmLabel _ fs CmmEntry)
= ftext fs <> text "_entry"
pprCLbl (CmmLabel _ fs CmmRetInfo)
= ftext fs <> text "_info"
pprCLbl (CmmLabel _ fs CmmRet)
= ftext fs <> text "_ret"
pprCLbl (CmmLabel _ fs CmmClosure)
= ftext fs <> text "_closure"
pprCLbl (RtsLabel (RtsPrimOp primop))
= text "stg_" <> ppr primop
pprCLbl (RtsLabel (RtsSlowFastTickyCtr pat))
= text "SLOW_CALL_fast_" <> text pat <> ptext (sLit "_ctr")
pprCLbl (ForeignLabel str _ _ _)
= ftext str
pprCLbl (IdLabel name _cafs flavor) = ppr name <> ppIdFlavor flavor
pprCLbl (CC_Label cc) = ppr cc
pprCLbl (CCS_Label ccs) = ppr ccs
pprCLbl (PlainModuleInitLabel mod)
= text "__stginit_" <> ppr mod
pprCLbl (HpcTicksLabel mod)
= text "_hpc_tickboxes_" <> ppr mod <> ptext (sLit "_hpc")
pprCLbl (AsmTempLabel {}) = panic "pprCLbl AsmTempLabel"
pprCLbl (AsmTempDerivedLabel {})= panic "pprCLbl AsmTempDerivedLabel"
pprCLbl (DynamicLinkerLabel {}) = panic "pprCLbl DynamicLinkerLabel"
pprCLbl (PicBaseLabel {}) = panic "pprCLbl PicBaseLabel"
pprCLbl (DeadStripPreventer {}) = panic "pprCLbl DeadStripPreventer"
ppIdFlavor :: IdLabelInfo -> SDoc
ppIdFlavor x = pp_cSEP <>
(case x of
Closure -> text "closure"
SRT -> text "srt"
InfoTable -> text "info"
LocalInfoTable -> text "info"
Entry -> text "entry"
LocalEntry -> text "entry"
Slow -> text "slow"
RednCounts -> text "ct"
ConEntry -> text "con_entry"
ConInfoTable -> text "con_info"
StaticConEntry -> text "static_entry"
StaticInfoTable -> text "static_info"
ClosureTable -> text "closure_tbl"
)
pp_cSEP :: SDoc
pp_cSEP = char '_'
instance Outputable ForeignLabelSource where
ppr fs
= case fs of
ForeignLabelInPackage pkgId -> parens $ text "package: " <> ppr pkgId
ForeignLabelInThisPackage -> parens $ text "this package"
ForeignLabelInExternalPackage -> parens $ text "external package"
-- -----------------------------------------------------------------------------
-- Machine-dependent knowledge about labels.
underscorePrefix :: Bool -- leading underscore on assembler labels?
underscorePrefix = (cLeadingUnderscore == "YES")
asmTempLabelPrefix :: Platform -> LitString -- for formatting labels
asmTempLabelPrefix platform = case platformOS platform of
OSDarwin -> sLit "L"
OSAIX -> sLit "__L" -- follow IBM XL C's convention
_ -> sLit ".L"
pprDynamicLinkerAsmLabel :: Platform -> DynamicLinkerLabelInfo -> CLabel -> SDoc
pprDynamicLinkerAsmLabel platform dllInfo lbl
= if platformOS platform == OSDarwin
then if platformArch platform == ArchX86_64
then case dllInfo of
CodeStub -> char 'L' <> ppr lbl <> text "$stub"
SymbolPtr -> char 'L' <> ppr lbl <> text "$non_lazy_ptr"
GotSymbolPtr -> ppr lbl <> text "@GOTPCREL"
GotSymbolOffset -> ppr lbl
else case dllInfo of
CodeStub -> char 'L' <> ppr lbl <> text "$stub"
SymbolPtr -> char 'L' <> ppr lbl <> text "$non_lazy_ptr"
_ -> panic "pprDynamicLinkerAsmLabel"
else if platformOS platform == OSAIX
then case dllInfo of
SymbolPtr -> text "LC.." <> ppr lbl -- GCC's naming convention
_ -> panic "pprDynamicLinkerAsmLabel"
else if osElfTarget (platformOS platform)
then if platformArch platform == ArchPPC
then case dllInfo of
CodeStub -> -- See Note [.LCTOC1 in PPC PIC code]
ppr lbl <> text "+32768@plt"
SymbolPtr -> text ".LC_" <> ppr lbl
_ -> panic "pprDynamicLinkerAsmLabel"
else if platformArch platform == ArchX86_64
then case dllInfo of
CodeStub -> ppr lbl <> text "@plt"
GotSymbolPtr -> ppr lbl <> text "@gotpcrel"
GotSymbolOffset -> ppr lbl
SymbolPtr -> text ".LC_" <> ppr lbl
else if platformArch platform == ArchPPC_64 ELF_V1
|| platformArch platform == ArchPPC_64 ELF_V2
then case dllInfo of
GotSymbolPtr -> text ".LC_" <> ppr lbl
<> text "@toc"
GotSymbolOffset -> ppr lbl
SymbolPtr -> text ".LC_" <> ppr lbl
_ -> panic "pprDynamicLinkerAsmLabel"
else case dllInfo of
CodeStub -> ppr lbl <> text "@plt"
SymbolPtr -> text ".LC_" <> ppr lbl
GotSymbolPtr -> ppr lbl <> text "@got"
GotSymbolOffset -> ppr lbl <> text "@gotoff"
else if platformOS platform == OSMinGW32
then case dllInfo of
SymbolPtr -> text "__imp_" <> ppr lbl
_ -> panic "pprDynamicLinkerAsmLabel"
else panic "pprDynamicLinkerAsmLabel"
|
sgillespie/ghc
|
compiler/cmm/CLabel.hs
|
bsd-3-clause
| 52,794
| 0
| 16
| 14,849
| 10,908
| 5,722
| 5,186
| 856
| 27
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module Phabricator where
import qualified Data.Text.Encoding as TE
import GHC.Generics (Generic)
import Data.Int
import Data.Maybe (mapMaybe, fromJust, fromMaybe)
import Data.Either (lefts, rights)
import Data.Text (Text)
import Data.List
import Data.Ord
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Aeson
import Data.Aeson.TH
import qualified Data.Aeson.Types as J
import Data.Time.Clock (DiffTime, diffTimeToPicoseconds)
import Data.Text.Encoding (decodeUtf8)
import System.IO.Streams.List (toList)
import Database.MySQL.Base
import Network.Conduit.Client hiding (User, Repo)
import Control.Monad
import Trac
import Debug.Trace
import Config
import Types
import Data.IORef
import qualified Data.IntMap as M
import Data.IntMap ((!))
import qualified Data.HashMap.Strict as H ((!))
import Data.Monoid
import qualified Trac.Convert as T
import qualified Database.MySQL.Base as M
import qualified Data.ByteString as B (readFile, ByteString)
import qualified Data.ByteString.Char8 as C8
import qualified Data.ByteString.Base64 as B (encode)
import Network.Mime
data PhabricatorConnection
= PC { pcManiphest :: C 'Ticket
, pcUser :: C 'User
, pcProject :: C 'Project
, pcRepo :: C 'Repo }
connectPhab :: IO PhabricatorConnection
connectPhab = do
cm <- C <$> M.connect phabConnectInfo { ciDatabase = "bitnami_phabricator_maniphest" }
cu <- C <$> M.connect phabConnectInfo { ciDatabase = "bitnami_phabricator_user" }
cp <- C <$> M.connect phabConnectInfo { ciDatabase = "bitnami_phabricator_project" }
cr <- C <$> M.connect phabConnectInfo { ciDatabase = "bitnami_phabricator_repository" }
return (PC cm cu cp cr)
closePhab :: PhabricatorConnection -> IO ()
closePhab (PC (C c1) (C c2) (C c3) (C c4)) = M.close c1 >> M.close c2 >> M.close c3 >> M.close c4
newtype C a = C { getConn :: M.MySQLConn }
data APIPHID a = APIPHID
{ api_phid :: PHID a
} deriving (Show, Generic)
$(deriveJSON defaultOptions{fieldLabelModifier = drop 4} ''APIPHID)
data ManiphestPriority = Unbreak | Triage | High | Normal | Low | Wishlist
deriving (Show)
data PhabricatorUser = PhabricatorUser
{ u_phid :: UserID
, u_userName :: Text
} deriving (Show)
data PhabricatorProject = PhabricatorProject
{ p_phid :: ProjectID
, p_projectName :: Text
} deriving Show
data ManiphestTicket = ManiphestTicket
{ m_tracn :: Int
, m_title :: Text
, m_description :: Maybe Text
, m_authorPHID :: UserID
, m_ownerPHID :: Maybe UserID
, m_cc :: [UserID]
, m_priority :: ManiphestPriority
, m_created :: DiffTime
, m_modified :: DiffTime
-- , m_phid :: Maybe TicketID
, m_status :: Text
, m_projects :: [ProjectID] -- Milestone, keywords, type,
, m_changes :: [ManiphestChange]
, m_commits :: [ManiphestCommit]
, m_attachments :: [ManiphestAttachment]
} deriving (Show)
data ManiphestAttachment = ManiphestAttachment
{ ma_tracn :: Int
, ma_name :: Text
-- , ma_size :: Text
, ma_time :: DiffTime
, ma_desc :: Text
, ma_author :: UserID } deriving Show
data ManiphestChange = ManiphestChange
{ mc_type :: MCType
, mc_created :: DiffTime
, mc_authorId :: UserID
} deriving Show
data ManiphestCommit = ManiphestCommit
{ mc_id :: Text
, mc_author :: UserID
, mc_time :: DiffTime
} deriving Show
data MCType = MCComment Text
| MCCCRemove [UserID]
| MCCCAdd [UserID]
| MCArchitecture Text
| MCBlockedBy [TicketID]
| MCComponent Text
| MCDescription Text
| MCDifferential [DiffID]
| MCDifficulty Text
| MCFailure Text
| MCAddKeyword [ProjectID]
| MCRemoveKeyword [ProjectID]
| MCMilestone Text
| MCOS Text
| MCOwner (Maybe UserID) -- Nothing to unassign
| MCPatch
| MCPriority ManiphestPriority
| MCRelated
| MCReporter
| MCResolution Text
| MCSeverity
| MCStatus Text
| MCSummary Text
| MCTestcase
| MCType Text
| MCVersion Text
| MCWiki Text
| Dummy Text deriving Show
mysqlToUser :: [MySQLValue] -> Maybe PhabricatorUser
mysqlToUser values =
case values of
[x,y] -> PhabricatorUser <$> decodePHID x <*> decodeUserName y
_ -> Nothing
where
decodePHID p = case p of
MySQLBytes v -> Just . PHID $ decodeUtf8 v
_ -> Nothing
decodeUserName u = case u of
MySQLText t -> Just t
_ -> Nothing
mysqlToProject :: [MySQLValue] -> Maybe PhabricatorProject
mysqlToProject values =
case values of
[x,y] -> PhabricatorProject <$> decodePHID x <*> decodeUserName y
_ -> Nothing
where
decodeUserName u = case u of
MySQLText t -> Just t
_ -> Nothing
decodePHID p = case p of
MySQLBytes v -> Just . PHID $ decodeUtf8 v
_ -> Nothing
mysqlToUsers :: [[MySQLValue]] -> [PhabricatorUser]
mysqlToUsers = mapMaybe mysqlToUser
mysqlToProjects :: [[MySQLValue]] -> [PhabricatorProject]
mysqlToProjects = mapMaybe mysqlToProject
getPhabricatorUsers :: C 'User -> IO [PhabricatorUser]
getPhabricatorUsers (C conn) = do
(_, rawUsersStream) <- query_ conn "SELECT phid, userName FROM user"
rawUsers <- toList rawUsersStream
return $ mysqlToUsers rawUsers
getPhabricatorProjects :: C 'Project -> IO [PhabricatorProject]
getPhabricatorProjects (C conn) = do
(_, rawProjectStream) <- query_ conn "SELECT phid, name FROM project"
rawProjects <- toList rawProjectStream
return $ mysqlToProjects rawProjects
createPhabricatorTickets :: C 'Ticket -> [ManiphestTicket] -> IO ()
createPhabricatorTickets conn tickets = do
tm <- newIORef M.empty
let as = concatMap (createPhabricatorTicketAction tm conn) tickets
doActions as
fixSubscribers conn
doActions :: [Action] -> IO ()
doActions as = do
let as' = sort as
print as'
mapM_ getAction as'
instance Ord Action where
compare (Action at t _) (Action at' t' _) = compare at at' <> compare t t'
instance Eq Action where
a == b = a == b
instance Ord ActionType where
compare (TicketCreate n) (TicketCreate m) = compare n m
compare (TicketCreate _) _ = LT
compare TicketUpdate TicketUpdate = EQ
compare TicketUpdate _ = GT
instance Eq ActionType where
a == b = a == b
data Action = Action ActionType DiffTime (IO ())
instance Show Action where
show = printAction
printAction :: Action -> String
printAction (Action at d _) = show (at, d)
getAction :: Action -> IO ()
getAction (Action _ _ io) = io
data ActionType = TicketCreate Int | TicketUpdate deriving Show
mkTicketCreate :: Int -> DiffTime -> IO () -> Action
mkTicketCreate n t ac = Action (TicketCreate n) t ac
mkTicketUpdate :: DiffTime -> IO () -> Action
mkTicketUpdate t ac = Action TicketUpdate t ac
type TicketMap = IORef (M.IntMap TicketID)
badTickets = [8539]
createPhabricatorTicketAction :: TicketMap -> C 'Ticket -> ManiphestTicket
-> [Action]
createPhabricatorTicketAction tm conn ticket = do
traceShowM (T.concat [T.pack (show $ m_tracn ticket),": ", m_title ticket])
if m_tracn ticket `elem` badTickets
then []
else
mkTicketCreate
(m_tracn ticket)
(m_created ticket)
(mkTicket ticket tm >> updatePhabricatorTicket tm conn ticket)
: doTransactions tm conn ticket
mkTicket :: ManiphestTicket -> TicketMap -> IO ()
mkTicket t tm = do
APIPHID pid <- fromConduitResult <$> callConduitPairs conduit "maniphest.createtask" (ticketToConduitPairs t)
modifyIORef tm (M.insert (m_tracn t) pid)
fromConduitResult :: ConduitResponse a -> a
fromConduitResult (ConduitResult a) = a
fromConduitResult (ConduitError code info) = error (show code ++ show info)
buildTransaction :: ManiphestChange -> Maybe Value
buildTransaction = doOne
where
doOne :: ManiphestChange -> Maybe Value
doOne ManiphestChange{..} =
case mc_type of
MCComment c -> Just $ mkTransaction "comment" c
MCCCRemove cs -> Just $ mkTransaction "subscribers.remove" cs
MCCCAdd cs -> Just $ mkTransaction "subscribers.add" cs
MCArchitecture v -> Just $ mkTransaction "custom.ghc:architecture" v
MCBlockedBy bs -> Nothing --Just $ mkTransaction "parent" bs
MCComponent c -> Just $ mkTransaction "custom.ghc:failure" c
MCDescription d -> Just $ mkTransaction "description" d
MCDifferential d -> Nothing --Just $ mkTransaction "" -- Add edge
MCDifficulty d -> Just $ mkTransaction "custom.ghc:difficulty" d
MCFailure f -> Just $ mkTransaction "custom.ghc:failure" f
-- MCKeywords pids -> Just $ mkTransaction "projects.set" pids
MCMilestone m -> Just $ mkTransaction "custom.ghc:milestone" m
MCOS os -> Just $ mkTransaction "custom.ghc:os" os
MCOwner mown -> Just $ mkTransaction "owner" mown
MCPatch -> Nothing -- Junk field
MCPriority p -> Just $ mkTransaction "priority" (show (priorityToInteger p))
MCRelated -> Nothing -- Unsure
MCReporter -> Nothing -- Handled and old
MCResolution r -> Just $ mkTransaction "status" r -- Resolutions are actually closed statuses
MCSeverity -> Nothing -- Not used
MCStatus s -> Just $ mkTransaction "status" s
MCSummary s -> Just $ mkTransaction "title" s
MCTestcase -> Nothing --TODO if important
MCType t -> Just $ mkTransaction "custom.ghc:type" t
MCVersion v -> Just $ mkTransaction "custom.ghc:version" v
MCWiki w -> Nothing -- TO implement this field
-- We try to remove the old one and add the new one.
MCAddKeyword new -> Just $ mkTransaction "projects.add" new
MCRemoveKeyword old -> Just $ mkTransaction "projects.remove" old
Dummy diag -> Nothing
mkTransaction :: ToJSON a => Text -> a -> Value
mkTransaction ty val = object [ "type" .= ty
, "value" .= val ]
ticketToConduitPairs :: ManiphestTicket -> [J.Pair]
ticketToConduitPairs ticket =
[ "title" .= m_title ticket
, "description" .= m_description ticket
, "ownerPHID" .= m_ownerPHID ticket
, "priority" .= priorityToInteger (m_priority ticket)
, "ccPHIDs" .= m_cc ticket
, "projectPHIDs" .= m_projects ticket
, "user" .= [m_authorPHID ticket]
]
-- Two transactions, upload the file and post a comment saying the
-- attachment was added.
attachmentTransaction :: TicketMap -> C 'Ticket
-> ManiphestTicket -> ManiphestAttachment -> Action
attachmentTransaction tm conn n a@ManiphestAttachment{..} =
mkTicketUpdate ma_time $ do
aid <- uploadAttachment a
let attachmentChange :: ManiphestChange
attachmentChange = ManiphestChange (MCComment attachmentComment)
ma_time
ma_author
attachmentComment = T.unwords ["Attachment", aid, "added"]
fromMaybe (return ()) (doOneTransaction tm conn n attachmentChange)
commitTransaction :: TicketMap -> C 'Ticket -> ManiphestTicket
-> ManiphestCommit -> Maybe Action
commitTransaction tm conn n ManiphestCommit{..} =
mkOneAction tm conn n (ManiphestChange (MCComment commitComment)
mc_time
mc_author )
where
commitComment = T.unwords ["This ticket was mentioned in", mc_id]
doTransactions :: TicketMap -> C 'Ticket -> ManiphestTicket -> [Action]
doTransactions tm conn mt =
let cs = m_changes mt
in
map (attachmentTransaction tm conn mt) (m_attachments mt)
++ mapMaybe (commitTransaction tm conn mt) (m_commits mt)
++ mapMaybe (mkOneAction tm conn mt) cs
mkOneAction :: TicketMap -> C 'Ticket -> ManiphestTicket -> ManiphestChange -> Maybe Action
mkOneAction tm conn n mc =
mkTicketUpdate (mc_created mc) <$>
doOneTransaction tm conn n mc
-- We have to do each one individually with 10000s of API calls to make
-- sure we get exactly 0 or 1 transactions for each update so we can match
-- the author and time information correctly.
doOneTransaction :: TicketMap -> C 'Ticket -> ManiphestTicket -> ManiphestChange -> Maybe (IO ())
doOneTransaction tm conn n mc =
case buildTransaction mc of
Nothing -> Nothing
Just v -> Just $ do
traceM (show $ (m_tracn n, mc_created mc, take 50 (show mc)))
tid <- getTicketID n tm
rawres <- callConduitPairs conduit "maniphest.edit"
[ "objectIdentifier" .= tid
, "transactions" .= [v]
, "author" .= mc_authorId mc ]
let res = case rawres of
ConduitResult r -> r
_ -> error (show rawres)
let ts = case J.parseEither transactionParser res of
Left e -> error e
Right r -> r
traceShowM ts
case ts of
-- Uncomment to debug
ts -> mapM_ (fixTransactionInformation conn (mc_authorId mc) (mc_created mc)) ts
-- Exactly one, do the transaction update
[t] -> fixTransactionInformation conn (mc_authorId mc) (mc_created mc) t
-- Zero, the edit had no effect
[] -> return ()
-- More than one, bad, better to abort
_ -> error (show ts)
{-
isComment :: ManiphestChange -> Bool
isComment ManiphestChange{mc_type = "comment"} = True
isComment _ = False
-}
transactionParser :: Object -> J.Parser [TransactionID]
transactionParser o = do
ts <- o .: "transactions"
J.listParser (withObject "" (.: "phid")) ts
-- parseJSON ts
-- Need to go into two tables, phabricator_manifest_transaction and
-- phabricator_manifest_comment
fixTransactionInformation ::
C 'Ticket
-> UserID
-> DiffTime
-> TransactionID
-> IO ()
fixTransactionInformation (C conn) (PHID maid) date (PHID tid) =
let fix1 = "UPDATE maniphest_transaction SET dateCreated=?, dateModified=? WHERE phid=?"
fix2 = "UPDATE maniphest_transaction_comment SET authorPHID=? WHERE transactionPHID=?"
values1 = [ MySQLInt64 $ convertTime date, MySQLInt64 $ convertTime date, MySQLText tid]
values2 = [values1 !! 2, values1 !! 3]
in
void $ execute conn fix1 values1 -- >> execute conn fix2 values2
priorityToInteger :: ManiphestPriority -> Integer
priorityToInteger p =
case p of
Unbreak -> 100
Triage -> 90
High -> 80
Normal -> 50
Low -> 25
Wishlist -> 0
updatePhabricatorTicket :: TicketMap -> C 'Ticket -> ManiphestTicket -> IO ()
updatePhabricatorTicket tm (C conn) ticket = do
let q = "UPDATE maniphest_task SET id=?, dateCreated=?, dateModified=?, authorPHID=? WHERE phid=?;"
-- Some queries go from this separate table rather than the actual information in the ticket.
q2 = "UPDATE maniphest_transaction SET dateCreated=?, authorPHID=? WHERE objectPHID=?"
t <- getTicketID ticket tm
let values = ticketToUpdateTuple t ticket
execute conn q values
execute conn q2 [values !! 1 , values !! 3, values !! 4]
return ()
fixSubscribers :: C 'Ticket -> IO ()
fixSubscribers (C conn) = do
-- A subscriber is automatically added
-- This is where the notification a subscriber is added is
-- populated from. We have to be careful to just remove the bot
-- user ID. Doing any action with the API adds you as a subscriber
-- so you should remove the edges at the END as well.
let q3 = "DELETE FROM maniphest_transaction WHERE transactionType=? AND newValue like '%cv4luanhibq47r6o2zrb%' "
-- This is where the subscribers info is populated from
q4 = "DELETE FROM edge WHERE dst=?"
execute conn q3 [MySQLText "core:subscribers" ]
execute conn q4 [MySQLText $ unwrapPHID botUser]
return ()
ticketToUpdateTuple :: TicketID -> ManiphestTicket -> [MySQLValue]
ticketToUpdateTuple (PHID t) ticket =
[ MySQLInt64 $ fromIntegral (m_tracn ticket)
, MySQLInt64 $ convertTime (m_created ticket)
, MySQLInt64 $ convertTime (m_modified ticket)
, MySQLText $ unwrapPHID (m_authorPHID ticket)
, MySQLText t
]
getTicketID :: ManiphestTicket -> TicketMap -> IO TicketID
getTicketID m tm = (! m_tracn m) <$> readIORef tm
deleteProjectInfo :: C 'Project -> IO ()
deleteProjectInfo (C conn) = void $ do
execute_ conn "DELETE FROM project"
execute_ conn "DELETE FROM project_transaction"
execute_ conn "DELETE FROM project_column"
execute_ conn "DELETE FROM project_columnposition"
execute_ conn "DELETE FROM project_columntransaction"
execute_ conn "DELETE FROM project_transaction"
execute_ conn "DELETE FROM edge"
execute_ conn "DELETE FROM project_slug"
deleteTicketInfo :: C 'Ticket -> IO ()
deleteTicketInfo (C conn) = void $ do
execute_ conn "DELETE FROM maniphest_task"
execute_ conn "DELETE FROM maniphest_transaction"
execute_ conn "DELETE FROM maniphest_transaction_comment"
execute_ conn "DELETE FROM edge"
createProject :: Text -> IO (Maybe ProjectID)
createProject "" = return Nothing
createProject i@kw = do
response <- callConduitPairs conduit "project.create" ["name" .= kw
-- ,"icon" .= keywordTypeToIcon ty
-- ,"colour" .= keywordTypeToColour ty
-- The API call
-- fails if you
-- don't pass this
-- param
, "members" .= ([] :: [()])]
traceShowM (i, response :: ConduitResponse (APIPHID 'Project))
case response of
ConduitResult (APIPHID a) -> return (Just a)
ConduitError {} -> do
traceShowM response
return Nothing
keywordTypeToIcon :: KeywordType -> Text
keywordTypeToIcon t =
case t of
Milestone -> "release"
_ -> "project"
keywordTypeToColour :: KeywordType -> Text
keywordTypeToColour t = "red"
data SubOrMil = Sub | Mil
addSubproject :: ProjectID -> SubOrMil -> Text -> IO ()
addSubproject phid sorm name = do
(response :: ConduitResponse Value) <- callConduitPairs conduit "project.edit"
[ "transactions" .= [mkTransaction (tt sorm) phid
, mkTransaction "name" name ]
]
traceShowM response
return ()
where
tt Sub = "parent"
tt Mil = "milestone"
convertTime :: DiffTime -> Int64
convertTime t = fromIntegral $ diffTimeToPicoseconds t `div` 1000000
lookupCommitID :: C 'Repo -> Text -> IO CommitID
lookupCommitID (C conn) t = do
[[rs]] <- toList . snd =<< query conn "SELECT phid FROM repository_commit WHERE commitIdentifier=?" [MySQLText t]
traceShowM rs
return (fromJust $ decodePHID rs)
-- Attachments
-- If a file is an image we upload it to FILE
-- If it is a text attachment we upload it to PASTE
--
-- Returns the name we want to refer to it as.
uploadAttachment :: ManiphestAttachment -> IO Text
uploadAttachment a =
let mime = C8.unpack $ defaultMimeLookup (ma_name a)
in case mime of
't':'e':'x':'t':_ -> uploadPasteAttachment a
_ -> uploadFileAttachment a
uploadPasteAttachment :: ManiphestAttachment -> IO Text
uploadPasteAttachment a = do
fileData <- T.readFile filePath
(response :: Object) <- fromConduitResult <$>
callConduitPairs conduit "paste.create"
[ "content" .= fileData
, "title" .= fileName
]
return ((\(String s) -> s) $ response H.! "objectName")
where
filePath :: String
filePath = T.unpack (maniphestAttachmentToPath a)
fileName :: Text
fileName = ma_name a
uploadFileAttachment :: ManiphestAttachment -> IO Text
uploadFileAttachment a = do
fileData <- TE.decodeUtf8 . B.encode <$> B.readFile filePath
phid :: Text <- fromConduitResult <$>
callConduitPairs conduit "file.upload"
[ "data_base64" .= fileData
, "name" .= fileName
]
(fileInfo :: Object) <- fromConduitResult <$>
callConduitPairs conduit "file.info"
[ "phid" .= phid ]
return ((\(String s) -> s) $ fileInfo H.! "objectName")
where
filePath :: String
filePath = T.unpack (maniphestAttachmentToPath a)
fileName :: Text
fileName = ma_name a
maniphestAttachmentToPath (ManiphestAttachment{..}) =
mkAttachmentPath ma_tracn ma_name
|
danpalmer/trac-to-phabricator
|
src/Phabricator.hs
|
bsd-3-clause
| 21,281
| 0
| 19
| 5,690
| 5,488
| 2,820
| 2,668
| 455
| 28
|
import Text.Template
main :: IO ()
main = do
t <- readFile "samples/sample1.tp"
mr <- template convert get t
maybe (return ()) putStr mr
convert :: String -> [String]
convert "name" = ["Yoshikuni", "Kazuhiro"]
convert "i" = map show [1 :: Int ..]
convert _ = []
get :: String -> IO [String]
get = mapM readFile . (`map` ["1", "2"]) . (++) . ("samples/" ++)
|
YoshikuniJujo/template
|
tests/test2.hs
|
bsd-3-clause
| 363
| 0
| 10
| 72
| 172
| 92
| 80
| 12
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module EncodeSpec where
import Data.IP
import Test.Hspec
import Network.DNS
spec :: Spec
spec = do
describe "encode" $ do
it "encodes DNSMessage correctly" $ do
check1 testQueryA
check1 testQueryAAAA
check1 testResponseA
check1 testResponseTXT
describe "decode" $ do
it "decodes DNSMessage correctly" $ do
check2 testQueryA
check2 testQueryAAAA
check2 testResponseA
check2 testResponseTXT
check1 :: DNSMessage -> Expectation
check1 inp = out `shouldBe` Right inp
where
bs = encode inp
out = decode bs
check2 :: DNSMessage -> Expectation
check2 inp = bs' `shouldBe` bs
where
bs = encode inp
Right out = decode bs
bs' = encode out
defaultHeader :: DNSHeader
defaultHeader = header defaultQuery
testQueryA :: DNSMessage
testQueryA = defaultQuery {
header = defaultHeader {
identifier = 1000
}
, question = [Question "www.mew.org." A]
}
testQueryAAAA :: DNSMessage
testQueryAAAA = defaultQuery {
header = defaultHeader {
identifier = 1001
}
, question = [Question "www.mew.org." AAAA]
}
testResponseA :: DNSMessage
testResponseA = DNSMessage {
header = DNSHeader {
identifier = 61046
, flags = DNSFlags {
qOrR = QR_Response
, opcode = OP_STD
, authAnswer = False
, trunCation = False
, recDesired = True
, recAvailable = True
, rcode = NoErr
, authenData = False
, chkDisable = False
}
}
, ednsHeader = NoEDNS
, question = [Question {
qname = "492056364.qzone.qq.com."
, qtype = A
}
]
, answer =
[ ResourceRecord "492056364.qzone.qq.com." A classIN 568 (RD_A $ toIPv4 [119, 147, 15, 122])
, ResourceRecord "492056364.qzone.qq.com." A classIN 568 (RD_A $ toIPv4 [119, 147, 79, 106])
, ResourceRecord "492056364.qzone.qq.com." A classIN 568 (RD_A $ toIPv4 [183, 60, 55, 43])
, ResourceRecord "492056364.qzone.qq.com." A classIN 568 (RD_A $ toIPv4 [183, 60, 55, 107])
, ResourceRecord "492056364.qzone.qq.com." A classIN 568 (RD_A $ toIPv4 [113, 108, 7, 172])
, ResourceRecord "492056364.qzone.qq.com." A classIN 568 (RD_A $ toIPv4 [113, 108, 7, 174])
, ResourceRecord "492056364.qzone.qq.com." A classIN 568 (RD_A $ toIPv4 [113, 108, 7, 175])
, ResourceRecord "492056364.qzone.qq.com." A classIN 568 (RD_A $ toIPv4 [119, 147, 15, 100])
]
, authority =
[ ResourceRecord "qzone.qq.com." NS classIN 45919 (RD_NS "ns-tel2.qq.com.")
, ResourceRecord "qzone.qq.com." NS classIN 45919 (RD_NS "ns-tel1.qq.com.")
]
, additional =
[ ResourceRecord "ns-tel1.qq.com." A classIN 46520 (RD_A $ toIPv4 [121, 14, 73, 115])
, ResourceRecord "ns-tel2.qq.com." A classIN 2890 (RD_A $ toIPv4 [222, 73, 76, 226])
, ResourceRecord "ns-tel2.qq.com." A classIN 2890 (RD_A $ toIPv4 [183, 60, 3, 202])
, ResourceRecord "ns-tel2.qq.com." A classIN 2890 (RD_A $ toIPv4 [218, 30, 72, 180])
]
}
testResponseTXT :: DNSMessage
testResponseTXT = DNSMessage {
header = DNSHeader {
identifier = 48724
, flags = DNSFlags {
qOrR = QR_Response
, opcode = OP_STD
, authAnswer = False
, trunCation = False
, recDesired = True
, recAvailable = True
, rcode = NoErr
, authenData = False
, chkDisable = False
}
}
, ednsHeader = EDNSheader defaultEDNS
, question = [Question {
qname = "492056364.qzone.qq.com."
, qtype = TXT
}
]
, answer =
[ ResourceRecord "492056364.qzone.qq.com." TXT classIN 0 (RD_TXT "simple txt line")
]
, authority =
[ ResourceRecord "qzone.qq.com." NS classIN 45919 (RD_NS "ns-tel2.qq.com.")
, ResourceRecord "qzone.qq.com." NS classIN 45919 (RD_NS "ns-tel1.qq.com.")
]
, additional =
[ ResourceRecord "ns-tel1.qq.com." A classIN 46520 (RD_A $ toIPv4 [121, 14, 73, 115])
, ResourceRecord "ns-tel2.qq.com." A classIN 2890 (RD_A $ toIPv4 [222, 73, 76, 226])
, ResourceRecord "ns-tel2.qq.com." A classIN 2890 (RD_A $ toIPv4 [183, 60, 3, 202])
, ResourceRecord "ns-tel2.qq.com." A classIN 2890 (RD_A $ toIPv4 [218, 30, 72, 180])
]
}
|
kazu-yamamoto/dns
|
test/EncodeSpec.hs
|
bsd-3-clause
| 4,570
| 0
| 13
| 1,409
| 1,257
| 703
| 554
| 103
| 1
|
{-# LANGUAGE DataKinds, GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Page4.Page4
(Tree()
,empty
,insert
) where
import Data.Type.Natural
import Page4.Types
empty :: Tree a
empty = Tree Leaf
insert :: (Ord a, Show a) => Tree a -> a -> Tree a
insert (Tree r) v = unwindR . inject v . findLeaf v $ toRootZip r
toRootZip :: Black n a -> Either (RedZip n a) (BlackZip n a)
toRootZip b = toZip (Right b) (Left RootCrumb)
toZip :: Either (Red n a) (Black n a) -> RBCrumb n a -> Either (RedZip n a) (BlackZip n a)
toZip n c =
case n of
(Right Leaf) -> Right (LeafZip c)
(Right (Black2 v l r)) -> Right (Black2Zip v l r c)
(Right (Black3 v l r)) -> Right (Black3Zip v l r c)
(Right (Black4 v (Red lv ll lr) (Red rv rl rr))) ->
case c of
Right cb -> Left (RedZip v (Black2 lv ll lr) (Black2 rv rl rr) cb)
Left cr -> Left (TempZip v (Black2 lv ll lr) (Black2 rv rl rr) cr)
(Left (Red v l r)) ->
case c of
(Right cb) -> Left (RedZip v l r cb)
(Left cr) -> Left (TempZip v l r cr)
findLeaf
:: forall a n. (Ord a,Show a)
=> a -> Either (RedZip n a) (BlackZip n a) -> BlackZip Z a
findLeaf u z =
case z of
Right l@(LeafZip _) -> l
Right (Black2Zip v l r c)
| u < v -> go (Right l) (Right $ RightBlack2Crumb v r c)
| otherwise -> go (Right r) (Right $ LeftBlack2Crumb v l c)
Right (Black3Zip v l r c)
| u < v -> go (Left l) (Right $ RightBlack2Crumb v r c)
| otherwise -> go (Right r) (Right $ LeftBlack3Crumb v l c)
Left (RedZip v l r c)
| u < v -> go (Right l) (Left $ RightRedCrumb v r c)
| otherwise -> go (Right r) (Left $ LeftRedCrumb v l c)
Left TempZip {} ->
-- impossible: will never see TempZip on way down
error (show z)
where go :: Either (Red m a) (Black m a) -> RBCrumb m a -> BlackZip Z a
go n c = findLeaf u (toZip n c)
inject :: a -> BlackZip Z a -> RedZip Z a
inject v (LeafZip (Right c)) = RedZip v Leaf Leaf c
inject v (LeafZip (Left c)) = TempZip v Leaf Leaf c
unwindB :: Show a => BlackZip n a -> Tree a
unwindB z =
case z of
(LeafZip (Left RootCrumb)) -> Tree Leaf
(Black2Zip v l r (Left RootCrumb)) -> Tree (Black2 v l r)
(Black3Zip v l r (Left RootCrumb)) -> Tree (Black3 v l r)
-- Leaf
(LeafZip (Left (LeftRedCrumb pv pl pc))) ->
unwindR (RedZip pv pl Leaf pc)
(LeafZip (Left (RightRedCrumb pv pr pc))) ->
unwindR (RedZip pv Leaf pr pc)
(LeafZip (Right (LeftBlack2Crumb pv pl pc))) ->
unwindB (Black2Zip pv pl Leaf pc)
(LeafZip (Right (RightBlack2Crumb pv pr pc))) ->
unwindB (Black2Zip pv Leaf pr pc)
(LeafZip (Right (LeftBlack3Crumb pv pl pc))) ->
unwindB (Black3Zip pv pl Leaf pc)
-- Black2
(Black2Zip v l r (Left (LeftRedCrumb pv pl pc))) ->
unwindR (RedZip pv pl (Black2 v l r) pc)
(Black2Zip v l r (Left (RightRedCrumb pv pr pc))) ->
unwindR (RedZip pv (Black2 v l r) pr pc)
(Black2Zip v l r (Right (LeftBlack2Crumb pv pl pc))) ->
unwindB (Black2Zip pv pl (Black2 v l r) pc)
(Black2Zip v l r (Right (RightBlack2Crumb pv pr pc))) ->
unwindB (Black2Zip pv (Black2 v l r) pr pc)
(Black2Zip v l r (Right (LeftBlack3Crumb pv pl pc))) ->
unwindB (Black3Zip pv pl (Black2 v l r) pc)
-- Black3
(Black3Zip v l r (Left (LeftRedCrumb pv pl pc))) ->
unwindR (RedZip pv pl (Black3 v l r) pc)
(Black3Zip v l r (Left (RightRedCrumb pv pr pc))) ->
unwindR (RedZip pv (Black3 v l r) pr pc)
(Black3Zip v l r (Right (LeftBlack2Crumb pv pl pc))) ->
unwindB (Black2Zip pv pl (Black3 v l r) pc)
(Black3Zip v l r (Right (RightBlack2Crumb pv pr pc))) ->
unwindB (Black2Zip pv (Black3 v l r) pr pc)
(Black3Zip v l r (Right (LeftBlack3Crumb pv pl pc))) ->
unwindB (Black3Zip pv pl (Black3 v l r) pc)
unwindR :: Show a => RedZip n a -> Tree a
unwindR z = case z of
(TempZip v l r RootCrumb) ->
Tree (Black2 v l r)
(TempZip b xl xr (LeftRedCrumb a hl hp)) ->
-- left rotate
unwindR (TempZip a hl xl (RightRedCrumb b xr hp))
(TempZip v l r (RightRedCrumb a xr (RightBlack2Crumb b hr hp))) ->
-- rotate right + flip
let xl = Black2 v l r
in case hp of
Right bhp -> unwindR (RedZip a xl (Black2 b xr hr) bhp)
Left rhp -> unwindR (TempZip a xl (Black2 b xr hr) rhp)
(TempZip _v _l _r (RightRedCrumb _b _xr (LeftBlack2Crumb _a _hl _hp))) ->
-- impossible - needed a red right subtree
error (show z)
(TempZip _v _l _r (RightRedCrumb _b _xr (LeftBlack3Crumb _a _hr _hp))) ->
-- impossible - needed a red right subtree
error (show z)
(RedZip b xl xr (LeftBlack2Crumb a hl hp)) ->
unwindB (Black3Zip b (Red a hl xl) xr hp)
(RedZip v l r (RightBlack2Crumb pv pr pc)) ->
unwindB (Black3Zip pv (Red v l r) pr pc)
(RedZip v l r (LeftBlack3Crumb pv (Red plv pll plr) epc)) ->
-- flip
case epc of
Right pc -> unwindR (RedZip pv (Black2 plv pll plr) (Black2 v l r) pc)
Left pc -> unwindR (TempZip pv (Black2 plv pll plr) (Black2 v l r) pc)
|
farrellm/dependent-rbtree
|
src/Page4/Page4.hs
|
bsd-3-clause
| 5,090
| 0
| 17
| 1,421
| 2,624
| 1,283
| 1,341
| 112
| 18
|
module Text.EBNF.Build.Parser (build, ioTryBuild, lookupGrammar) where
import Text.EBNF.SyntaxTree
import Text.EBNF.Informal (syntax)
import Text.EBNF.Helper
import Text.EBNF.Build.Parser.Parts
import Text.EBNF.Build.Parser.Except
import Text.Parsec.String
import System.IO
import Data.Either
{-|
given a syntax tree for a valid EBNF grammar, returns a
association list with the key as the meta identifier.
-}
build :: SyntaxTree -> [GrammarRule]
build st = rights . buildSyntax $ st
{-|
transform that discards the information in a EBNF AST
generated by EBNF.Informal that is not relevant.
-}
discard :: SyntaxTree -> SyntaxTree
discard = prune (\a -> identifier a `elem` list)
where
list = [ "irrelevent"
, "concatenate symbol"
, "definition separator symbol"
, "defining symbol"
, "terminator symbol"]
{-|
IO function, outputs errors if build fails.
-}
ioTryBuild :: SyntaxTree -> IO [GrammarRule]
ioTryBuild st =
case generateReport st of
{-
The tree has no detectable errors, continue
with the program as normal.
-}
Clean -> return $ build st
{-
The tree has one or more non-critical errors,
print these to stderr and continue with the
building process.
-}
Warning warns -> do
hPrint stderr $ Warning warns
return $ build st
{-
The tree has one or more critical errors, the
program exits with an error code.
-}
Failed fails -> (die . show $ Failed fails) >> return []
|
Lokidottir/monadic-ebnf-bff
|
src/Text/EBNF/Build/Parser.hs
|
mit
| 1,735
| 0
| 11
| 574
| 271
| 153
| 118
| 26
| 3
|
import Geometry
import Drawing
main = drawPicture myPicture
myPicture points =
drawPoints list &
drawAutoLabels list &
message "Points"
where list = take 10 points
|
alphalambda/hsmath
|
src/Learn/Geometry/demo01points.hs
|
gpl-2.0
| 183
| 0
| 7
| 44
| 52
| 25
| 27
| 8
| 1
|
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
module SPL.Top where
import Data.Map as M hiding (take)
import System.IO.Unsafe
import SPL.Parser2
import SPL.Compiler
import SPL.Types
import SPL.Code
import SPL.Check3
import SPL.Optimizer1
import Debug.Trace
data Fun = Fun C T | Lib [Char]
observe s v = trace ("{"++s++":"++show v++"}") v
observeN s v = v
check0 o = check_with_rename o SPL.Top.get_types False
check1 o e =
case check o e True of
SPL.Check3.P (a, b, c) -> SPL.Check3.P (opt a, b, c)
o -> o
check2 o =
case check_with_rename o SPL.Top.get_types True of
SPL.Check3.P (a, b, c) -> SPL.Check3.P (opt a, b, c)
o -> o
eval0 c =
eval c get_codes
compile0 c =
compile c get_types
ff_functi name t = (,) name $ Fun (error $ name ++ " is not implemented") (TT t)
ff_method thisType name t = ff_functi name $ (T thisType) : t
ff_constr thisType name t = ff_functi name $ t ++ [T thisType]
tdt td t = TD td [T t]
base = M.fromList $
("sum", Fun
(CL (CInFun 2 (InFun "" do_sum)) (K []))
(TT [T "num", T "num", T "num"]))
:("sub", Fun
(CL (CInFun 2 (InFun "" do_sub)) (K []))
(TT [T "num", T "num", T "num"]))
:("eq", Fun
(CL (CInFun 2 (InFun "" do_eq)) (K []))
(TT [T "num", T "num", T "boolean"]))
:("less", Fun
(CL (CInFun 2 (InFun "" do_less)) (K []))
(TT [T "num", T "num", T "boolean"]))
:("not", Fun
(CL (CInFun 1 (InFun "" do_not)) (K []))
(TT [T "boolean", T "boolean"]))
:("incr", Fun
(CL (CInFun 1 (InFun "" do_incr)) (K []))
(TT [T "num", T "num"]))
:("elist", Fun
(CList [])
(TD "list" [TU "a"]))
:("head", Fun
(CL (CInFun 1 (InFun "" do_head)) (K []))
(TT [TD "list" [TU "a"], TU "a"]))
:("tail", Fun
(CL (CInFun 1 (InFun "" do_tail)) (K []))
(TT [TD "list" [TU "a"], TD "list" [TU "a"]]))
:("reverse", Fun
(CL (CInFun 1 (InFun "" do_reverse)) (K []))
(TT [TD "list" [TU "a"], TD "list" [TU "a"]]))
:("filter", Fun
(CL (CInFun 2 (InFun "" do_filter)) (K []))
(TT [TT [TU "a", T "boolean"], TD "list" [TU "a"], TD "list" [TU "a"]]))
:("join1", Fun
(CL (CInFun 2 (InFun "" do_join1)) (K []))
(TT [TU "a", TD "list" [TU "a"], TD "list" [TU "a"]]))
:("concat", Fun
(CL (CInFun 2 (InFun "" do_concat)) (K []))
(TT [TD "list" [TU "a"], TD "list" [TU "a"], TD "list" [TU "a"]]))
:("length", Fun
(CL (CInFun 1 (InFun "" do_length)) (K []))
(TT [TD "list" [TU "a"], T "num"]))
:("to_string", Fun
(CL (CInFun 1 (InFun "" do_to_string)) (K []))
(TT [TU "num", T "string"]))
:("pair", Fun
(CL (CInFun 2 (InFun "" do_pair)) (K []))
(TT [TU "a", TU "b", TD "pair" [TU "a",TU "b"]]))
:("debug", Fun
(CL (CInFun 1 (InFun "" do_debug)) (K []))
(TT [TU "a", TU "a"]))
:("go", Fun
(CNum 0)
TL)
:("iff", Fun
(CL (CInFun 2 (InFun "" do_iff)) (K []))
(TT [TD "list" [TD "pair" [T "boolean", TT [TL, TU "a"]]], TT [TL, TU "a"], TU "a"]))
:("if", Fun
(CL (CInFun 3 (InFun "" do_if)) (K []))
(TT [T "boolean",TT [TL, TU "a"], TT [TL, TU "a"], TU "a"]))
:("_if", Fun
(CL (CInFun 3 (InFun "" do_if)) (K []))
(TT [T "boolean",TU "a", TU "a", TU "a"]))
:("foldr", Fun
(CL (CInFun 3 (InFun "" do_foldr)) (K []))
(TT [TT [TU "a", TU "b", TU "b"], TU "b", TD "list" [TU "a"], TU "b"]))
:ff_functi "print" [TU "a", TD "IO" [T "void"]]
:ff_method "udp_socket" "udp_send" [T "string", tdt "IO" "void"]
:ff_method "udp_socket" "udp_reply" [T "string", tdt "IO" "void"]
:ff_method "udp_socket" "udp_receive" [tdt "IO" "string"]
:ff_constr "udp_socket" "udp_connect" [T "string", T "num"]
:ff_constr "udp_socket" "udp_listen" [T "num"]
:ff_functi "bind" [ TD "IO" [TU "a"], TT [TU "a", TD "IO" [TU "b"]], TD "IO" [TU "b"]]
:ff_functi "forever" [tdt "IO" "void", tdt "IO" "void"]
:("readnum", Fun
(CNum 0)
(TD "IO" [T "num"] ))
:("time_msec", Fun
(CNum 0)
(tdt "IO" "num"))
:ff_functi "voidbind" [TD "IO" [T "void"], TD "IO" [TU "a"], TD "IO" [TU "a"]]
:ff_functi "natrec" [TT [T "num", TU "a", TU "a"], TU "a", T "num", TU "a"]
:("load", Fun
(CL (CInFun 1 (InFun "" do_load)) (K []))
(TT [T "string", TU "a"]))
:("out", Fun
(CL (CInFun 1 (InFun "" do_out)) (K []))
(TT [T "string", T "void"]))
{- :("str", Fun
(CStruct $ M.fromList
[("concat", CL (CInFun 2 (InFun "" do_str_concat)) (K []))])
(TS $ M.fromList
[("concat", TT [T "string", T "string", T "string"])]
))-}
:("to", Fun
(CL (CInFun 1 (InFun "" do_to)) (K []))
(TT [T "num", TD "list" [T "num"]]))
:("mul", Fun
(CL (CInFun 2 (InFun "" do_mul)) (K []))
(TT [T "num", T "num", T "num"]))
:("mod", Fun
(CL (CInFun 2 (InFun "" do_mod)) (K []))
(TT [T "num", T "num", T "num"]))
:("div", Fun
(CL (CInFun 2 (InFun "" do_div)) (K []))
(TT [T "num", T "num", T "num"]))
:("or", Fun
(CL (CInFun 2 (InFun "" do_or)) (K []))
(TT [T "boolean", T "boolean", T "boolean"]))
:("_or", Fun
(CL (CInFun 2 (InFun "" do_or)) (K []))
(TT [T "boolean", T "boolean", T "boolean"]))
:("map", Fun
(CL (CInFun 2 (InFun "" do_map)) (K []))
(TT [TT [TU "a", TU "b"], TD "list" [TU "a"], TD "list" [TU "b"]]))
:("str", Lib "spllib/str.spl")
:("bn", Lib "spllib/bn.spl")
-- :("adt", Lib "spllib/adt.spl")
:[]
put_name n (CL (CInFun i (InFun "" f)) (K [])) = CL (CInFun i (InFun n f)) (K [])
put_name n o = o
get_code n (Fun c _) = put_name n c
get_code n (Lib f) = do_load (CStr f:[]) get_codes
get_type (Fun _ t) = t
get_type (Lib f) =
case check0 $ get_code "" (Lib f) of
SPL.Check3.P (_, ur, t)|M.null ur -> t
SPL.Check3.P (_, ur, _) -> error "get_type"
SPL.Check3.N i e -> error "get_type"
get_codes = M.mapWithKey get_code base
get_types = M.map get_type base
-- native functions
do_sum = binary_int_op (+)
do_sub = binary_int_op (-)
do_less (CNum a:CNum b:[]) e = CBool (a < b)
do_eq (CNum a:CNum b:[]) e = CBool (a == b)
do_not (CBool b:[]) e = CBool (not b)
do_incr (CNum a:[]) e = CL (CVal "sum") (K [CNum a, CNum 1])
do_incr o e = error ("do_incr"++show o)
do_join1 (a:CList b:[]) e = CList (a:b)
do_join1 o e = error $ show o
do_concat (CList a:CList b:[]) e = CList (a++b)
do_head (CList a:[]) e = head a
do_tail (CList a:[]) e = CList (tail a)
do_reverse (CList a:[]) e = CList (reverse a)
cbool_val (CBool b) = b
do_filter (a:CList l:[]) e = CList $ Prelude.filter (\x -> cbool_val $ eval (CL a (K [x])) e) l
do_length (CList l:[]) e = CNum (length l)
do_debug (a:[]) e = a
do_to_string (a:[]) e = CStr (show a)
do_pair (a:b:[]) e = CPair (a:b:[])
do_iff (CList []:CL c L:[]) e = CL (CL c L) (K [CVal "go"])
do_iff (CList ((CPair (CBool True:exp:[])):is):CL c L:[]) e = CL exp (K [CVal "go"])
do_iff (CList ((CPair (CBool False:exp:[])):is):CL c L:[]) e = do_iff (CList is:CL c L:[]) e
do_iff o e = error ("do_iff: "++show o)
do_foldr (f:b:CList []:[]) e = b
do_foldr (f:b:CList (a:as):[]) e =
eval (CL f (K [a, do_foldr (f:b:CList as:[]) e])) e
do_load (CStr f:[]) e =
unsafePerformIO $
do
str <- readFile f
return $ case SPL.Parser2.parse str of
SPL.Parser2.P _ i p _ ->
case compile p get_types of
SPL.Compiler.P c ->
case check0 $ c of
SPL.Check3.P (_, ur, _)|M.null ur -> {-eval -}c{- e-}
SPL.Check3.P (_, ur, _) -> error "load error1"
SPL.Check3.N i e -> error ("load error: "++e)
SPL.Compiler.N i e -> error ("load error218: "++e);
SPL.Parser2.N i _ -> error ("load error3: "++f)
do_out (CStr s:[]) e =
unsafePerformIO $
do
putStrLn s
return (CNum 0)
do_str_concat (CStr s1:CStr s2:[]) e =
CStr $ (++) s1 s2
do_to (CNum n:[]) e =
CList $ Prelude.map CNum $ take n $ enumFrom 0
binary_int_op op (CNum n1:CNum n2:[]) _ = CNum $ op n1 n2
do_mul = binary_int_op (*)
do_mod = binary_int_op mod
do_div = binary_int_op div
do_or (CBool n1:CBool n2:[]) e =
CBool $ (||) n1 n2
do_map (f:CList []:[]) e = CList []
do_map (f:CList (a:as):[]) e =
case do_map (f:CList as:[]) e of
CList l -> CList $ (:) (eval (CL f (K [a])) e) l
_ -> error "do_map"
do_if (CBool True:t:_:[]) e = eval (CL t (K [CVal "go"])) e
do_if (CBool False:_:el:[]) e = eval (CL el (K [CVal "go"])) e
do_if o e = error $ "if: "++show o
res = check2 (CL (CL (CNum 1) (W [("foo",CNum 2)])) (W [("foo",CBool True)]))
res2 = check2 (CL (CNum 1) (S ["z"]))
res3 = check2 (CL (CL (CVal "foo") (W [("foo",CL (CBool True) (W [("foo",CL (CVal "less") (K [CNum 2,CNum 2]))]))])) (W [("foo",CL (CVal "less") (K [CNum 2,CL (CVal "sum") (K [CNum 2,CNum 2])]))]))
|
nponeccop/HNC
|
SPL/Top.hs
|
lgpl-3.0
| 8,365
| 162
| 58
| 1,788
| 5,579
| 2,812
| 2,767
| 222
| 5
|
-- Copyright 2012-2013 Greg Horn
--
-- This file is part of rawesome.
--
-- rawesome is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- rawesome is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public License
-- along with rawesome. If not, see <http://www.gnu.org/licenses/>.
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE DeriveDataTypeable #-}
module ParseArgs ( getip
) where
import System.Console.CmdArgs ( (&=), Data, Typeable )
import qualified System.Console.CmdArgs as CA
data VisArgs = VisArgs { ipfile :: String
, ip :: String
, followkite :: Bool
} deriving (Show, Data, Typeable)
myargs :: VisArgs
myargs = VisArgs { ipfile = "" &= CA.help "file to read IP address out of" &= CA.typ "FILENAME"
, ip = "" &= CA.help "an IP address" &= CA.typ "ADDRESS"
, followkite = False &= CA.help "rotate the camera to follow the current estimate"
} &= CA.summary "the kite visualizer program"
getip :: String -> IO (String,Bool)
getip defaultip = do
a <- CA.cmdArgs (myargs &= CA.program "wtfviz")
ip' <- case (ipfile a,ip a) of
("","") -> return defaultip
("",x) -> return x
(f,"") -> fmap (head . lines) (readFile f)
(_,_) -> error "please only specify your ip address one way"
return (ip', followkite a)
|
ghorn/rawesome
|
wtfviz/src/ParseArgs.hs
|
lgpl-3.0
| 1,819
| 0
| 13
| 453
| 344
| 195
| 149
| 23
| 4
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="fil-PH">
<title>>Patakbuhin ang mga Aplikasyon | Mga extensyon ng ZAP</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Mga Nilalaman</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Indeks</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Maghanap</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Mga paborito</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/invoke/src/main/javahelp/org/zaproxy/zap/extension/invoke/resources/help_fil_PH/helpset_fil_PH.hs
|
apache-2.0
| 1,014
| 78
| 55
| 166
| 435
| 218
| 217
| -1
| -1
|
module Reddit.Types.SubredditSettings
( SubredditSettings(..)
, ContentOptions(..)
, SpamFilterStrength(..)
, SubredditType(..)
, WikiEditMode(..) ) where
import Reddit.Parser
import Reddit.Utilities
import Control.Applicative
import Data.Aeson
import Data.Default.Class
import Data.Monoid hiding (Any(..))
import Data.Text (Text)
import Network.API.Builder.Query
import Prelude
data SubredditSettings = SubredditSettings { sidebarText :: Text
, descriptionText :: Text
, title :: Text
, linkType :: ContentOptions
, hideScoreMins :: Integer
, submitLinkLabel :: Maybe Text
, submitTextLabel :: Maybe Text
, domainCSS :: Bool
, domainSidebar :: Bool
, showMedia :: Bool
, over18 :: Bool
, language :: Text
, wikiEditKarma :: Integer
, wikiEditAge :: Integer
, wikiEditMode :: WikiEditMode
, spamComments :: SpamFilterStrength
, spamSelfposts :: SpamFilterStrength
, spamLinks :: SpamFilterStrength
, publicTrafficStats :: Bool
, subredditType :: SubredditType }
deriving (Show, Read, Eq)
instance FromJSON SubredditSettings where
parseJSON (Object o) = do
o `ensureKind` subredditSettingsPrefix
d <- o .: "data"
SubredditSettings <$> (unescape <$> d .: "description")
<*> d .: "public_description"
<*> d .: "title"
<*> d .: "content_options"
<*> d .: "comment_score_hide_mins"
<*> d .: "submit_link_label"
<*> d .: "submit_text_label"
<*> d .: "domain_css"
<*> d .: "domain_sidebar"
<*> d .: "show_media"
<*> d .: "over_18"
<*> d .: "language"
<*> d .: "wiki_edit_karma"
<*> d .: "wiki_edit_age"
<*> d .: "wikimode"
<*> d .: "spam_comments"
<*> d .: "spam_selfposts"
<*> d .: "spam_links"
<*> d .: "public_traffic"
<*> d .: "subreddit_type"
parseJSON _ = mempty
instance ToJSON SubredditSettings where
toJSON settings = object
[ "description" .= sidebarText settings
, "public_description" .= descriptionText settings
, "title" .= title settings
, "content_options" .= linkType settings
, "comment_score_hide_mins" .= hideScoreMins settings
, "submit_link_label" .= submitLinkLabel settings
, "submit_text_label" .= submitTextLabel settings
, "domain_css" .= domainCSS settings
, "domain_sidebar" .= domainSidebar settings
, "show_media" .= showMedia settings
, "over_18" .= over18 settings
, "language" .= language settings
, "wiki_edit_karma" .= wikiEditKarma settings
, "wiki_edit_age" .= wikiEditAge settings
, "wikimode" .= wikiEditMode settings
, "spam_comments" .= spamComments settings
, "spam_selfposts" .= spamSelfposts settings
, "spam_links" .= spamLinks settings
, "public_traffic" .= publicTrafficStats settings
, "subreddit_type" .= subredditType settings ]
data SubredditType = Public
| Private
| Restricted
| GoldRestricted
| Archived
deriving (Show, Read, Eq)
subredditTypeText :: SubredditType -> Text
subredditTypeText Public = "public"
subredditTypeText Private = "private"
subredditTypeText Restricted = "restricted"
subredditTypeText GoldRestricted = "gold_restricted"
subredditTypeText Archived = "archived"
instance FromJSON SubredditType where
parseJSON (String s) =
case s of
"public" -> return Public
"private" -> return Private
"restricted" -> return Restricted
"gold_restricted" -> return GoldRestricted
"archived" -> return Archived
_ -> mempty
parseJSON _ = mempty
instance ToJSON SubredditType where
toJSON = String . subredditTypeText
instance Default SubredditType where
def = Public
instance ToQuery SubredditType where
toQuery k v = [(k, subredditTypeText v)]
data ContentOptions = Any
| Link
| Self
deriving (Show, Read, Eq)
contentOptionsText :: ContentOptions -> Text
contentOptionsText Any = "any"
contentOptionsText Link = "link"
contentOptionsText Self = "self"
instance FromJSON ContentOptions where
parseJSON (String s) =
case s of
"any" -> return Any
"link" -> return Link
"self" -> return Self
_ -> mempty
parseJSON _ = mempty
instance ToJSON ContentOptions where
toJSON = String . contentOptionsText
instance ToQuery ContentOptions where
toQuery k v = [(k, contentOptionsText v)]
instance Default ContentOptions where
def = Any
data SpamFilterStrength = FilterLow
| FilterHigh
| FilterAll
deriving (Show, Read, Eq)
instance FromJSON SpamFilterStrength where
parseJSON (String s) =
case s of
"low" -> return FilterLow
"high" -> return FilterHigh
"all" -> return FilterAll
_ -> mempty
parseJSON _ = mempty
spamFilterStrengthText :: SpamFilterStrength -> Text
spamFilterStrengthText FilterLow = "low"
spamFilterStrengthText FilterHigh = "high"
spamFilterStrengthText FilterAll = "all"
instance ToJSON SpamFilterStrength where
toJSON = String . spamFilterStrengthText
instance ToQuery SpamFilterStrength where
toQuery k v = [(k, spamFilterStrengthText v)]
data WikiEditMode = Anyone
| ApprovedOnly
| ModOnly
deriving (Show, Read, Eq)
instance FromJSON WikiEditMode where
parseJSON (String s) =
case s of
"disabled" -> return ModOnly
"modonly" -> return ApprovedOnly
"anyone" -> return Anyone
_ -> mempty
parseJSON _ = mempty
wikiEditModeText :: WikiEditMode -> Text
wikiEditModeText ModOnly = "disabled"
wikiEditModeText Anyone = "anyone"
wikiEditModeText ApprovedOnly = "modonly"
instance ToJSON WikiEditMode where
toJSON = String . wikiEditModeText
instance ToQuery WikiEditMode where
toQuery k v = [(k, wikiEditModeText v)]
instance Default WikiEditMode where
def = Anyone
subredditSettingsPrefix :: Text
subredditSettingsPrefix = "subreddit_settings"
|
FranklinChen/reddit
|
src/Reddit/Types/SubredditSettings.hs
|
bsd-2-clause
| 7,043
| 0
| 49
| 2,446
| 1,483
| 791
| 692
| 177
| 1
|
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE FlexibleContexts #-}
module Propellor.PrivData (
withPrivData,
withSomePrivData,
addPrivData,
setPrivData,
unsetPrivData,
dumpPrivData,
editPrivData,
filterPrivData,
listPrivDataFields,
makePrivDataDir,
decryptPrivData,
PrivMap,
) where
import Control.Applicative
import System.IO
import System.Directory
import Data.Maybe
import Data.Monoid
import Data.List
import Control.Monad
import Control.Monad.IfElse
import "mtl" Control.Monad.Reader
import qualified Data.Map as M
import qualified Data.Set as S
import Propellor.Types
import Propellor.Types.PrivData
import Propellor.Message
import Propellor.Info
import Propellor.Gpg
import Propellor.PrivData.Paths
import Utility.Monad
import Utility.PartialPrelude
import Utility.Exception
import Utility.Tmp
import Utility.SafeCommand
import Utility.Misc
import Utility.FileMode
import Utility.Env
import Utility.Table
-- | Allows a Property to access the value of a specific PrivDataField,
-- for use in a specific Context or HostContext.
--
-- Example use:
--
-- > withPrivData (PrivFile pemfile) (Context "joeyh.name") $ \getdata ->
-- > property "joeyh.name ssl cert" $ getdata $ \privdata ->
-- > liftIO $ writeFile pemfile privdata
-- > where pemfile = "/etc/ssl/certs/web.pem"
--
-- Note that if the value is not available, the action is not run
-- and instead it prints a message to help the user make the necessary
-- private data available.
--
-- The resulting Property includes Info about the PrivDataField
-- being used, which is necessary to ensure that the privdata is sent to
-- the remote host by propellor.
withPrivData
:: (IsContext c, IsPrivDataSource s, IsProp (Property i))
=> s
-> c
-> (((PrivData -> Propellor Result) -> Propellor Result) -> Property i)
-> Property HasInfo
withPrivData s = withPrivData' snd [s]
-- Like withPrivData, but here any one of a list of PrivDataFields can be used.
withSomePrivData
:: (IsContext c, IsPrivDataSource s, IsProp (Property i))
=> [s]
-> c
-> ((((PrivDataField, PrivData) -> Propellor Result) -> Propellor Result) -> Property i)
-> Property HasInfo
withSomePrivData = withPrivData' id
withPrivData'
:: (IsContext c, IsPrivDataSource s, IsProp (Property i))
=> ((PrivDataField, PrivData) -> v)
-> [s]
-> c
-> (((v -> Propellor Result) -> Propellor Result) -> Property i)
-> Property HasInfo
withPrivData' feed srclist c mkprop = addinfo $ mkprop $ \a ->
maybe missing (a . feed) =<< getM get fieldlist
where
get field = do
context <- mkHostContext hc <$> asks hostName
maybe Nothing (\privdata -> Just (field, privdata))
<$> liftIO (getLocalPrivData field context)
missing = do
Context cname <- mkHostContext hc <$> asks hostName
warningMessage $ "Missing privdata " ++ intercalate " or " fieldnames ++ " (for " ++ cname ++ ")"
liftIO $ putStrLn $ "Fix this by running:"
liftIO $ showSet $
map (\s -> (privDataField s, Context cname, describePrivDataSource s)) srclist
return FailedChange
addinfo p = infoProperty
(propertyDesc p)
(propertySatisfy p)
(propertyInfo p <> mempty { _privData = privset })
(propertyChildren p)
privset = S.fromList $ map (\s -> (privDataField s, describePrivDataSource s, hc)) srclist
fieldnames = map show fieldlist
fieldlist = map privDataField srclist
hc = asHostContext c
showSet :: [(PrivDataField, Context, Maybe PrivDataSourceDesc)] -> IO ()
showSet l = forM_ l $ \(f, Context c, md) -> do
putStrLn $ " propellor --set '" ++ show f ++ "' '" ++ c ++ "' \\"
maybe noop (\d -> putStrLn $ " " ++ d) md
putStrLn ""
addPrivData :: (PrivDataField, Maybe PrivDataSourceDesc, HostContext) -> Property HasInfo
addPrivData v = pureInfoProperty (show v) $
mempty { _privData = S.singleton v }
{- Gets the requested field's value, in the specified context if it's
- available, from the host's local privdata cache. -}
getLocalPrivData :: PrivDataField -> Context -> IO (Maybe PrivData)
getLocalPrivData field context =
getPrivData field context . fromMaybe M.empty <$> localcache
where
localcache = catchDefaultIO Nothing $ readish <$> readFile privDataLocal
type PrivMap = M.Map (PrivDataField, Context) PrivData
-- | Get only the set of PrivData that the Host's Info says it uses.
filterPrivData :: Host -> PrivMap -> PrivMap
filterPrivData host = M.filterWithKey (\k _v -> S.member k used)
where
used = S.map (\(f, _, c) -> (f, mkHostContext c (hostName host))) $
_privData $ hostInfo host
getPrivData :: PrivDataField -> Context -> PrivMap -> Maybe PrivData
getPrivData field context = M.lookup (field, context)
setPrivData :: PrivDataField -> Context -> IO ()
setPrivData field context = do
putStrLn "Enter private data on stdin; ctrl-D when done:"
setPrivDataTo field context =<< hGetContentsStrict stdin
unsetPrivData :: PrivDataField -> Context -> IO ()
unsetPrivData field context = do
modifyPrivData $ M.delete (field, context)
putStrLn "Private data unset."
dumpPrivData :: PrivDataField -> Context -> IO ()
dumpPrivData field context =
maybe (error "Requested privdata is not set.") putStrLn
=<< (getPrivData field context <$> decryptPrivData)
editPrivData :: PrivDataField -> Context -> IO ()
editPrivData field context = do
v <- getPrivData field context <$> decryptPrivData
v' <- withTmpFile "propellorXXXX" $ \f h -> do
hClose h
maybe noop (writeFileProtected f) v
editor <- getEnvDefault "EDITOR" "vi"
unlessM (boolSystem editor [File f]) $
error "Editor failed; aborting."
readFile f
setPrivDataTo field context v'
listPrivDataFields :: [Host] -> IO ()
listPrivDataFields hosts = do
m <- decryptPrivData
section "Currently set data:"
showtable $ map mkrow (M.keys m)
let missing = M.keys $ M.difference wantedmap m
unless (null missing) $ do
section "Missing data that would be used if set:"
showtable $ map mkrow missing
section "How to set missing data:"
showSet $ map (\(f, c) -> (f, c, join $ M.lookup (f, c) descmap)) missing
where
header = ["Field", "Context", "Used by"]
mkrow k@(field, (Context context)) =
[ shellEscape $ show field
, shellEscape context
, intercalate ", " $ sort $ fromMaybe [] $ M.lookup k usedby
]
mkhostmap host mkv = M.fromList $ map (\(f, d, c) -> ((f, mkHostContext c (hostName host)), mkv d)) $
S.toList $ _privData $ hostInfo host
usedby = M.unionsWith (++) $ map (\h -> mkhostmap h $ const $ [hostName h]) hosts
wantedmap = M.fromList $ zip (M.keys usedby) (repeat "")
descmap = M.unions $ map (\h -> mkhostmap h id) hosts
section desc = putStrLn $ "\n" ++ desc
showtable rows = do
putStr $ unlines $ formatTable $ tableWithHeader header rows
setPrivDataTo :: PrivDataField -> Context -> PrivData -> IO ()
setPrivDataTo field context value = do
modifyPrivData set
putStrLn "Private data set."
where
set = M.insert (field, context) (chomp value)
chomp s
| end s == "\n" = chomp (beginning s)
| otherwise = s
modifyPrivData :: (PrivMap -> PrivMap) -> IO ()
modifyPrivData f = do
makePrivDataDir
m <- decryptPrivData
let m' = f m
gpgEncrypt privDataFile (show m')
void $ boolSystem "git" [Param "add", File privDataFile]
decryptPrivData :: IO PrivMap
decryptPrivData = fromMaybe M.empty . readish <$> gpgDecrypt privDataFile
makePrivDataDir :: IO ()
makePrivDataDir = createDirectoryIfMissing False privDataDir
|
sjfloat/propellor
|
src/Propellor/PrivData.hs
|
bsd-2-clause
| 7,337
| 129
| 18
| 1,284
| 2,082
| 1,125
| 957
| 169
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE StandaloneDeriving #-}
module Database.HDBC.SqlValue
(
-- * SQL value marshalling
SqlValue(..),
safeFromSql, toSql, fromSql,
nToSql, iToSql, posixToSql
)
where
import Data.Dynamic
import qualified Data.ByteString.UTF8 as BUTF8
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BSL
import Data.Char(ord,toUpper)
import Data.Word
import Data.Int
import qualified System.Time as ST
import Data.Time ( Day (ModifiedJulianDay), DiffTime, LocalTime, NominalDiffTime, ParseTime
, TimeOfDay, TimeZone, UTCTime, ZonedTime, formatTime, localDay, localTimeOfDay
, timeOfDayToTime, timeToTimeOfDay, toModifiedJulianDay, utc
, utcToZonedTime, zonedTimeToLocalTime, zonedTimeToUTC, zonedTimeZone
#if MIN_TIME_15
, parseTimeM
#else
, parseTime
#endif
)
import Data.Time.Clock.POSIX
import Database.HDBC.Locale (defaultTimeLocale, iso8601DateFormat)
import Data.Ratio
import Data.Convertible
import Data.Fixed
import qualified Data.Text as TS
import qualified Data.Text.Lazy as TL
quickError :: (Typeable a, Convertible SqlValue a) => SqlValue -> ConvertResult a
quickError sv = convError "incompatible types" sv
{- | Convert a value to an 'SqlValue'. This function is simply
a restricted-type wrapper around 'convert'. See extended notes on 'SqlValue'. -}
toSql :: Convertible a SqlValue => a -> SqlValue
toSql = convert
{- | Conversions to and from 'SqlValue's and standard Haskell types.
This function converts from an 'SqlValue' to a Haskell value. Many people will use the simpler
'fromSql' instead. This function is simply a restricted-type wrapper around
'safeConvert'. -}
safeFromSql :: Convertible SqlValue a => SqlValue -> ConvertResult a
safeFromSql = safeConvert
{- | Convert from an 'SqlValue' to a Haskell value. Any problem is indicated by
calling 'error'. This function is simply a restricted-type wrapper around
'convert'. See extended notes on 'SqlValue'. -}
fromSql :: Convertible SqlValue a => SqlValue -> a
fromSql = convert
{- | Converts any Integral type to a 'SqlValue' by using toInteger. -}
nToSql :: Integral a => a -> SqlValue
nToSql n = SqlInteger (toInteger n)
{- | Convenience function for using numeric literals in your program. -}
iToSql :: Int -> SqlValue
iToSql = toSql
{- | Convenience function for converting 'POSIXTime' to a 'SqlValue', because
'toSql' cannot do the correct thing in this instance. -}
posixToSql :: POSIXTime -> SqlValue
posixToSql x = SqlPOSIXTime x
{- | 'SqlValue' is the main type for expressing Haskell values to SQL databases.
/INTRODUCTION TO SQLVALUE/
This type is used to marshall Haskell data to and from database APIs.
HDBC driver interfaces will do their best to use the most accurate and
efficient way to send a particular value to the database server.
Values read back from the server are constructed with the most appropriate 'SqlValue'
constructor. 'fromSql' or 'safeFromSql'
can then be used to convert them into whatever type
is needed locally in Haskell.
Most people will use 'toSql' and 'fromSql' instead of manipulating
'SqlValue's directly.
/EASY CONVERSIONS BETWEEN HASKELL TYPES/
Conversions are powerful; for instance, you can call 'fromSql' on a SqlInt32
and get a String or a Double out of it. This class attempts to Do
The Right Thing whenever possible, and will raise an error when asked to
do something incorrect. In particular, when converting to any type
except a Maybe, 'SqlNull' as the input will cause an error to be raised.
Conversions are implemented in terms of the "Data.Convertible" module, part of the
convertible package. You can refer to its documentation, and import that module,
if you wish to parse the Left result from 'safeFromSql' yourself, or write your
own conversion instances.
Here are some notes about conversion:
* Fractions of a second are not preserved on time values
* There is no @safeToSql@ because 'toSql' never fails.
See also 'toSql', 'safeFromSql', 'fromSql', 'nToSql', 'iToSql', 'posixToSql'.
/ERROR CONDITIONS/
There may sometimes be an error during conversion. For instance, if you have a
'SqlString' and are attempting to convert it to an Integer, but it doesn't parse as
an Integer, you will get an error. This will be indicated as an exception if using
'fromSql', or a Left result if using 'safeFromSql'.
/SPECIAL NOTE ON POSIXTIME/
Note that a 'NominalDiffTime' or 'POSIXTime' is converted to 'SqlDiffTime' by
'toSql'. HDBC cannot differentiate between 'NominalDiffTime' and 'POSIXTime'
since they are the same underlying type. You must construct 'SqlPOSIXTime'
manually or via 'posixToSql', or use 'SqlUTCTime'.
/DETAILS ON SQL TYPES/
HDBC database backends are expected to marshal date and time data back and
forth using the appropriate representation for the underlying database engine.
Databases such as PostgreSQL with builtin date and time types should see automatic
conversion between these Haskell types to database types. Other databases will be
presented with an integer or a string. Care should be taken to use the same type on
the Haskell side as you use on the database side. For instance, if your database
type lacks timezone information, you ought not to use ZonedTime, but
instead LocalTime or UTCTime. Database type systems are not always as rich
as Haskell. For instance, for data stored in a TIMESTAMP
WITHOUT TIME ZONE column, HDBC may not be able to tell if it is intended
as UTCTime or LocalTime data, and will happily convert it to both,
upon your request. It is
your responsibility to ensure that you treat timezone issues with due care.
This behavior also exists for other types. For instance, many databases do not
have a Rational type, so they will just use the show function and
store a Rational as a string.
The conversion between Haskell types and database types is complex,
and generic code in HDBC or its backends cannot possibly accomodate
every possible situation. In some cases, you may be best served by converting your
Haskell type to a String, and passing that to the database.
/UNICODE AND BYTESTRINGS/
Beginning with HDBC v2.0, interactions with a database are presumed to occur in UTF-8.
To accomplish this, whenever a ByteString must be converted to or from a String,
the ByteString is assumed to be in UTF-8 encoding, and will be decoded or encoded
as appropriate. Database drivers will generally present text or string data they have
received from the database as a SqlValue holding a ByteString, which 'fromSql' will
automatically convert to a String, and thus automatically decode UTF-8, when
you need it. In the other direction, database drivers will generally convert
a 'SqlString' to a ByteString in UTF-8 encoding before passing it to the
database engine.
If you are handling some sort of binary data that is not in UTF-8, you can of course
work with the ByteString directly, which will bypass any conversion.
Due to lack of support by database engines, lazy ByteStrings are not passed to database
drivers. When you use 'toSql' on a lazy ByteString, it will be converted to a strict
ByteString for storage. Similarly, 'fromSql' will convert a strict ByteString to
a lazy ByteString if you demand it.
/EQUALITY OF SQLVALUE/
Two SqlValues are considered to be equal if one of these hold. The
first comparison that can be made is controlling; if none of these
comparisons can be made, then they are not equal:
* Both are NULL
* Both represent the same type and the encapsulated values are considered equal
by applying (==) to them
* The values of each, when converted to a string, are equal
/STRING VERSIONS OF TIMES/
Default string representations are given as comments below where such are non-obvious.
These are used for 'fromSql' when a 'String' is desired. They are also defaults for
representing data to SQL backends, though individual backends may override them
when a different format is demanded by the underlying database. Date and time formats
use ISO8601 date format, with HH:MM:SS added for time, and -HHMM added for timezone
offsets.
/DEPRECATED CONSTRUCTORS/
'SqlEpochTime' and 'SqlTimeDiff' are no longer created automatically by any
'toSql' or 'fromSql' functions or database backends. They may still be manually
constructed, but are
expected to be removed in a future version. Although these two constructures will
be removed, support for marshalling to and from the old System.Time data will be
maintained as long as System.Time is, simply using the newer data types for conversion.
-}
data SqlValue = SqlString String
| SqlByteString B.ByteString
| SqlWord32 Word32
| SqlWord64 Word64
| SqlInt32 Int32
| SqlInt64 Int64
| SqlInteger Integer
| SqlChar Char
| SqlBool Bool
| SqlDouble Double
| SqlRational Rational
| SqlLocalDate Day -- ^ Local YYYY-MM-DD (no timezone).
| SqlLocalTimeOfDay TimeOfDay -- ^ Local HH:MM:SS (no timezone).
| SqlZonedLocalTimeOfDay TimeOfDay TimeZone -- ^ Local HH:MM:SS -HHMM. Converts to and from (TimeOfDay, TimeZone).
| SqlLocalTime LocalTime -- ^ Local YYYY-MM-DD HH:MM:SS (no timezone).
| SqlZonedTime ZonedTime -- ^ Local YYYY-MM-DD HH:MM:SS -HHMM. Considered equal if both convert to the same UTC time.
| SqlUTCTime UTCTime -- ^ UTC YYYY-MM-DD HH:MM:SS.
| SqlDiffTime NominalDiffTime -- ^ Calendar diff between seconds. Rendered as Integer when converted to String, but greater precision may be preserved for other types or to underlying database.
| SqlPOSIXTime POSIXTime -- ^ Time as seconds since midnight Jan 1 1970 UTC. Integer rendering as for 'SqlDiffTime'.
| SqlEpochTime Integer -- ^ DEPRECATED Representation of ClockTime or CalendarTime. Use SqlPOSIXTime instead.
| SqlTimeDiff Integer -- ^ DEPRECATED Representation of TimeDiff. Use SqlDiffTime instead.
| SqlNull -- ^ NULL in SQL or Nothing in Haskell.
deriving (Show, Typeable)
instance Eq SqlValue where
SqlString a == SqlString b = a == b
SqlByteString a == SqlByteString b = a == b
SqlWord32 a == SqlWord32 b = a == b
SqlWord64 a == SqlWord64 b = a == b
SqlInt32 a == SqlInt32 b = a == b
SqlInt64 a == SqlInt64 b = a == b
SqlInteger a == SqlInteger b = a == b
SqlChar a == SqlChar b = a == b
SqlBool a == SqlBool b = a == b
SqlDouble a == SqlDouble b = a == b
SqlRational a == SqlRational b = a == b
SqlLocalTimeOfDay a == SqlLocalTimeOfDay b = a == b
SqlZonedLocalTimeOfDay a b == SqlZonedLocalTimeOfDay c d = a == c && b == d
SqlLocalTime a == SqlLocalTime b = a == b
SqlLocalDate a == SqlLocalDate b = a == b
SqlZonedTime a == SqlZonedTime b = zonedTimeToUTC a == zonedTimeToUTC b
SqlUTCTime a == SqlUTCTime b = a == b
SqlPOSIXTime a == SqlPOSIXTime b = a == b
SqlDiffTime a == SqlDiffTime b = a == b
SqlEpochTime a == SqlEpochTime b = a == b
SqlTimeDiff a == SqlTimeDiff b = a == b
SqlNull == SqlNull = True
SqlNull == _ = False
_ == SqlNull = False
a == b = ((safeFromSql a)::ConvertResult String) ==
((safeFromSql b)::ConvertResult String)
deriving instance Typeable ST.ClockTime
deriving instance Typeable ST.TimeDiff
instance Convertible SqlValue SqlValue where
safeConvert = return
instance Convertible String SqlValue where
safeConvert = return . SqlString
instance Convertible SqlValue String where
safeConvert (SqlString x) = return x
safeConvert (SqlByteString x) = return . BUTF8.toString $ x
safeConvert (SqlInt32 x) = return . show $ x
safeConvert (SqlInt64 x) = return . show $ x
safeConvert (SqlWord32 x) = return . show $ x
safeConvert (SqlWord64 x) = return . show $ x
safeConvert (SqlInteger x) = return . show $ x
safeConvert (SqlChar x) = return [x]
safeConvert (SqlBool x) = return . show $ x
safeConvert (SqlDouble x) = return . show $ x
safeConvert (SqlRational x) = return . show $ x
safeConvert (SqlLocalDate x) =
return . formatTime defaultTimeLocale (iso8601DateFormat Nothing) $ x
safeConvert (SqlLocalTimeOfDay x) =
return . formatTime defaultTimeLocale "%T%Q" $ x
safeConvert (SqlZonedLocalTimeOfDay tod tz) =
return $ formatTime defaultTimeLocale "%T%Q " tod ++
formatTime defaultTimeLocale "%z" tz
safeConvert (SqlLocalTime x) =
return . formatTime defaultTimeLocale (iso8601DateFormat (Just "%T%Q")) $ x
safeConvert (SqlZonedTime x) =
return . formatTime defaultTimeLocale (iso8601DateFormat (Just "%T%Q %z")) $ x
safeConvert (SqlUTCTime x) =
return . formatTime defaultTimeLocale (iso8601DateFormat (Just "%T%Q")) $ x
safeConvert (SqlDiffTime x) = return $ showFixed True fixedval
where fixedval :: Pico
fixedval = fromRational . toRational $ x
safeConvert (SqlPOSIXTime x) = return $ showFixed True fixedval
where fixedval :: Pico
fixedval = fromRational . toRational $ x
safeConvert (SqlEpochTime x) = return . show $ x
safeConvert (SqlTimeDiff x) = return . show $ x
safeConvert y@(SqlNull) = quickError y
instance Convertible TS.Text SqlValue where
safeConvert = return . SqlString . TS.unpack
instance Convertible SqlValue TS.Text where
safeConvert = fmap TS.pack . safeConvert
instance Convertible TL.Text SqlValue where
safeConvert = return . SqlString . TL.unpack
instance Convertible SqlValue TL.Text where
safeConvert = fmap TL.pack . safeConvert
#ifdef __HUGS__
instance Typeable B.ByteString where
typeOf _ = mkTypeName "ByteString"
#endif
instance Convertible B.ByteString SqlValue where
safeConvert = return . SqlByteString
instance Convertible SqlValue B.ByteString where
safeConvert (SqlByteString x) = return x
safeConvert y@(SqlNull) = quickError y
safeConvert x = safeConvert x >>= return . BUTF8.fromString
instance Convertible BSL.ByteString SqlValue where
safeConvert = return . SqlByteString . B.concat . BSL.toChunks
instance Convertible SqlValue BSL.ByteString where
safeConvert x = do bs <- safeConvert x
return (BSL.fromChunks [bs])
instance Convertible Int SqlValue where
safeConvert x =
do i <- ((safeConvert x)::ConvertResult Int64)
return $ SqlInt64 i
instance Convertible SqlValue Int where
safeConvert (SqlString x) = read' x
safeConvert (SqlByteString x) = (read' . BUTF8.toString) x
safeConvert (SqlInt32 x) = safeConvert x
safeConvert (SqlInt64 x) = safeConvert x
safeConvert (SqlWord32 x) = safeConvert x
safeConvert (SqlWord64 x) = safeConvert x
safeConvert (SqlInteger x) = safeConvert x
safeConvert (SqlChar x) = safeConvert x
safeConvert (SqlBool x) = return (if x then 1 else 0)
safeConvert (SqlDouble x) = safeConvert x
safeConvert (SqlRational x) = safeConvert x
safeConvert y@(SqlLocalDate _) = viaInteger y fromIntegral
safeConvert y@(SqlLocalTimeOfDay _) = viaInteger y fromIntegral
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert y@(SqlLocalTime _) = viaInteger y fromIntegral
safeConvert y@(SqlZonedTime _) = viaInteger y fromIntegral
safeConvert (SqlUTCTime x) = safeConvert x
safeConvert (SqlDiffTime x) = safeConvert x
safeConvert (SqlPOSIXTime x) = safeConvert x
safeConvert (SqlEpochTime x) = safeConvert x
safeConvert (SqlTimeDiff x) = safeConvert x
safeConvert y@(SqlNull) = quickError y
instance Convertible Int32 SqlValue where
safeConvert = return . SqlInt32
instance Convertible SqlValue Int32 where
safeConvert (SqlString x) = read' x
safeConvert (SqlByteString x) = (read' . BUTF8.toString) x
safeConvert (SqlInt32 x) = return x
safeConvert (SqlInt64 x) = safeConvert x
safeConvert (SqlWord32 x) = safeConvert x
safeConvert (SqlWord64 x) = safeConvert x
safeConvert (SqlInteger x) = safeConvert x
safeConvert (SqlChar x) = safeConvert x
safeConvert (SqlBool x) = return (if x then 1 else 0)
safeConvert (SqlDouble x) = safeConvert x
safeConvert (SqlRational x) = safeConvert x
safeConvert y@(SqlLocalDate _) = viaInteger y fromIntegral
safeConvert y@(SqlLocalTimeOfDay _) = viaInteger y fromIntegral
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert y@(SqlLocalTime _) = viaInteger y fromIntegral
safeConvert y@(SqlZonedTime _) = viaInteger y fromIntegral
safeConvert y@(SqlUTCTime _) = viaInteger y fromIntegral
safeConvert y@(SqlDiffTime _) = viaInteger y fromIntegral
safeConvert y@(SqlPOSIXTime _) = viaInteger y fromIntegral
safeConvert (SqlEpochTime x) = safeConvert x
safeConvert (SqlTimeDiff x) = safeConvert x
safeConvert y@(SqlNull) = quickError y
instance Convertible Int64 SqlValue where
safeConvert = return . SqlInt64
instance Convertible SqlValue Int64 where
safeConvert (SqlString x) = read' x
safeConvert (SqlByteString x) = (read' . BUTF8.toString) x
safeConvert (SqlInt32 x) = safeConvert x
safeConvert (SqlInt64 x) = return x
safeConvert (SqlWord32 x) = safeConvert x
safeConvert (SqlWord64 x) = safeConvert x
safeConvert (SqlInteger x) = safeConvert x
safeConvert (SqlChar x) = safeConvert x
safeConvert (SqlBool x) = return (if x then 1 else 0)
safeConvert (SqlDouble x) = safeConvert x
safeConvert (SqlRational x) = safeConvert x
safeConvert y@(SqlLocalDate _) = viaInteger y fromIntegral
safeConvert y@(SqlLocalTimeOfDay _) = viaInteger y fromIntegral
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert y@(SqlLocalTime _) = viaInteger y fromIntegral
safeConvert y@(SqlZonedTime _) = viaInteger y fromIntegral
safeConvert y@(SqlUTCTime _) = viaInteger y fromIntegral
safeConvert y@(SqlDiffTime _) = viaInteger y fromIntegral
safeConvert y@(SqlPOSIXTime _) = viaInteger y fromIntegral
safeConvert (SqlEpochTime x) = safeConvert x
safeConvert (SqlTimeDiff x) = safeConvert x
safeConvert y@(SqlNull) = quickError y
instance Convertible Word32 SqlValue where
safeConvert = return . SqlWord32
instance Convertible SqlValue Word32 where
safeConvert (SqlString x) = read' x
safeConvert (SqlByteString x) = (read' . BUTF8.toString) x
safeConvert (SqlInt32 x) = safeConvert x
safeConvert (SqlInt64 x) = safeConvert x
safeConvert (SqlWord32 x) = return x
safeConvert (SqlWord64 x) = safeConvert x
safeConvert (SqlInteger x) = safeConvert x
safeConvert (SqlChar x) = safeConvert x
safeConvert (SqlBool x) = return (if x then 1 else 0)
safeConvert (SqlDouble x) = safeConvert x
safeConvert (SqlRational x) = safeConvert x
safeConvert y@(SqlLocalDate _) = viaInteger y fromIntegral
safeConvert y@(SqlLocalTimeOfDay _) = viaInteger y fromIntegral
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert y@(SqlLocalTime _) = viaInteger y fromIntegral
safeConvert y@(SqlZonedTime _) = viaInteger y fromIntegral
safeConvert y@(SqlUTCTime _) = viaInteger y fromIntegral
safeConvert y@(SqlDiffTime _) = viaInteger y fromIntegral
safeConvert y@(SqlPOSIXTime _) = viaInteger y fromIntegral
safeConvert (SqlEpochTime x) = safeConvert x
safeConvert (SqlTimeDiff x) = safeConvert x
safeConvert y@(SqlNull) = quickError y
instance Convertible Word64 SqlValue where
safeConvert = return . SqlWord64
instance Convertible SqlValue Word64 where
safeConvert (SqlString x) = read' x
safeConvert (SqlByteString x) = (read' . BUTF8.toString) x
safeConvert (SqlInt32 x) = safeConvert x
safeConvert (SqlInt64 x) = safeConvert x
safeConvert (SqlWord32 x) = safeConvert x
safeConvert (SqlWord64 x) = return x
safeConvert (SqlInteger x) = safeConvert x
safeConvert (SqlChar x) = safeConvert x
safeConvert (SqlBool x) = return (if x then 1 else 0)
safeConvert (SqlDouble x) = safeConvert x
safeConvert (SqlRational x) = safeConvert x
safeConvert y@(SqlLocalDate _) = viaInteger y fromIntegral
safeConvert y@(SqlLocalTimeOfDay _) = viaInteger y fromIntegral
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert y@(SqlLocalTime _) = viaInteger y fromIntegral
safeConvert y@(SqlZonedTime _) = viaInteger y fromIntegral
safeConvert y@(SqlUTCTime _) = viaInteger y fromIntegral
safeConvert y@(SqlDiffTime _) = viaInteger y fromIntegral
safeConvert y@(SqlPOSIXTime _) = viaInteger y fromIntegral
safeConvert (SqlEpochTime x) = safeConvert x
safeConvert (SqlTimeDiff x) = safeConvert x
safeConvert y@(SqlNull) = quickError y
instance Convertible Integer SqlValue where
safeConvert = return . SqlInteger
instance Convertible SqlValue Integer where
safeConvert (SqlString x) = read' x
safeConvert (SqlByteString x) = (read' . BUTF8.toString) x
safeConvert (SqlInt32 x) = safeConvert x
safeConvert (SqlInt64 x) = safeConvert x
safeConvert (SqlWord32 x) = safeConvert x
safeConvert (SqlWord64 x) = safeConvert x
safeConvert (SqlInteger x) = return x
safeConvert (SqlChar x) = safeConvert x
safeConvert (SqlBool x) = return (if x then 1 else 0)
safeConvert (SqlDouble x) = safeConvert x
safeConvert (SqlRational x) = safeConvert x
safeConvert (SqlLocalDate x) = return . toModifiedJulianDay $ x
safeConvert (SqlLocalTimeOfDay x) =
return . fromIntegral . fromEnum . timeOfDayToTime $ x
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert y@(SqlLocalTime _) = quickError y
safeConvert (SqlZonedTime x) =
return . truncate . utcTimeToPOSIXSeconds . zonedTimeToUTC $ x
safeConvert (SqlUTCTime x) = safeConvert x
safeConvert (SqlDiffTime x) = safeConvert x
safeConvert (SqlPOSIXTime x) = safeConvert x
safeConvert (SqlEpochTime x) = return x
safeConvert (SqlTimeDiff x) = return x
safeConvert y@(SqlNull) = quickError y
instance Convertible Bool SqlValue where
safeConvert = return . SqlBool
instance Convertible SqlValue Bool where
safeConvert y@(SqlString x) =
case map toUpper x of
"TRUE" -> Right True
"T" -> Right True
"FALSE" -> Right False
"F" -> Right False
"0" -> Right False
"1" -> Right True
_ -> convError "Cannot parse given String as Bool" y
safeConvert (SqlByteString x) = (safeConvert . SqlString . BUTF8.toString) x
safeConvert (SqlInt32 x) = numToBool x
safeConvert (SqlInt64 x) = numToBool x
safeConvert (SqlWord32 x) = numToBool x
safeConvert (SqlWord64 x) = numToBool x
safeConvert (SqlInteger x) = numToBool x
safeConvert (SqlChar x) = numToBool (ord x)
safeConvert (SqlBool x) = return x
safeConvert (SqlDouble x) = numToBool x
safeConvert (SqlRational x) = numToBool x
safeConvert y@(SqlLocalDate _) = quickError y
safeConvert y@(SqlLocalTimeOfDay _) = quickError y
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert y@(SqlLocalTime _) = quickError y
safeConvert y@(SqlZonedTime _) = quickError y
safeConvert y@(SqlUTCTime _) = quickError y
safeConvert y@(SqlDiffTime _) = quickError y
safeConvert y@(SqlPOSIXTime _) = quickError y
safeConvert (SqlEpochTime x) = numToBool x
safeConvert (SqlTimeDiff x) = numToBool x
safeConvert y@(SqlNull) = quickError y
numToBool :: (Eq a, Num a) => a -> ConvertResult Bool
numToBool x = Right (x /= 0)
instance Convertible Char SqlValue where
safeConvert = return . SqlChar
instance Convertible SqlValue Char where
safeConvert (SqlString [x]) = return x
safeConvert y@(SqlString _) = convError "String length /= 1" y
safeConvert (SqlByteString x) =
safeConvert . SqlString . BUTF8.toString $ x
safeConvert y@(SqlInt32 _) = quickError y
safeConvert y@(SqlInt64 _) = quickError y
safeConvert y@(SqlWord32 _) = quickError y
safeConvert y@(SqlWord64 _) = quickError y
safeConvert y@(SqlInteger _) = quickError y
safeConvert (SqlChar x) = return x
safeConvert (SqlBool x) = return (if x then '1' else '0')
safeConvert y@(SqlDouble _) = quickError y
safeConvert y@(SqlRational _) = quickError y
safeConvert y@(SqlLocalDate _) = quickError y
safeConvert y@(SqlLocalTimeOfDay _) = quickError y
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert y@(SqlLocalTime _) = quickError y
safeConvert y@(SqlZonedTime _) = quickError y
safeConvert y@(SqlUTCTime _) = quickError y
safeConvert y@(SqlDiffTime _) = quickError y
safeConvert y@(SqlPOSIXTime _) = quickError y
safeConvert y@(SqlEpochTime _) = quickError y
safeConvert y@(SqlTimeDiff _) = quickError y
safeConvert y@(SqlNull) = quickError y
instance Convertible Double SqlValue where
safeConvert = return . SqlDouble
instance Convertible SqlValue Double where
safeConvert (SqlString x) = read' x
safeConvert (SqlByteString x) = (read' . BUTF8.toString) x
safeConvert (SqlInt32 x) = safeConvert x
safeConvert (SqlInt64 x) = safeConvert x
safeConvert (SqlWord32 x) = safeConvert x
safeConvert (SqlWord64 x) = safeConvert x
safeConvert (SqlInteger x) = safeConvert x
safeConvert (SqlChar x) = return . fromIntegral . fromEnum $ x
safeConvert (SqlBool x) = return (if x then 1.0 else 0.0)
safeConvert (SqlDouble x) = return x
safeConvert (SqlRational x) = safeConvert x
safeConvert y@(SqlLocalDate _) = ((safeConvert y)::ConvertResult Integer) >>=
(return . fromIntegral)
safeConvert (SqlLocalTimeOfDay x) =
return . fromRational . toRational . timeOfDayToTime $ x
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert y@(SqlLocalTime _) = quickError y
safeConvert (SqlZonedTime x) =
safeConvert . SqlUTCTime . zonedTimeToUTC $ x
safeConvert (SqlUTCTime x) =
return . fromRational . toRational . utcTimeToPOSIXSeconds $ x
safeConvert (SqlDiffTime x) = safeConvert x
safeConvert (SqlPOSIXTime x) = safeConvert x
safeConvert (SqlEpochTime x) = safeConvert x
safeConvert (SqlTimeDiff x) = safeConvert x
safeConvert y@(SqlNull) = quickError y
instance Convertible Rational SqlValue where
safeConvert = return . SqlRational
instance Convertible SqlValue Rational where
safeConvert (SqlString x) = read' x
safeConvert (SqlByteString x) = (read' . BUTF8.toString) x
safeConvert (SqlInt32 x) = safeConvert x
safeConvert (SqlInt64 x) = safeConvert x
safeConvert (SqlWord32 x) = safeConvert x
safeConvert (SqlWord64 x) = safeConvert x
safeConvert (SqlInteger x) = safeConvert x
safeConvert (SqlChar x) = return . fromIntegral . fromEnum $ x
safeConvert (SqlBool x) = return $ if x then fromIntegral (1::Int)
else fromIntegral (0::Int)
safeConvert (SqlDouble x) = safeConvert x
safeConvert (SqlRational x) = return x
safeConvert y@(SqlLocalDate _) = ((safeConvert y)::ConvertResult Integer) >>=
(return . fromIntegral)
safeConvert (SqlLocalTimeOfDay x) = return . toRational . timeOfDayToTime $ x
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert y@(SqlLocalTime _) = quickError y
safeConvert (SqlZonedTime x) = safeConvert . SqlUTCTime . zonedTimeToUTC $ x
safeConvert (SqlUTCTime x) = safeConvert x
safeConvert (SqlDiffTime x) = safeConvert x
safeConvert (SqlPOSIXTime x) = safeConvert x
safeConvert (SqlEpochTime x) = return . fromIntegral $ x
safeConvert (SqlTimeDiff x) = return . fromIntegral $ x
safeConvert y@(SqlNull) = quickError y
instance Convertible Day SqlValue where
safeConvert = return . SqlLocalDate
instance Convertible SqlValue Day where
safeConvert (SqlString x) = parseTime' (iso8601DateFormat Nothing) x
safeConvert (SqlByteString x) = safeConvert (SqlString (BUTF8.toString x))
safeConvert (SqlInt32 x) =
return $ ModifiedJulianDay {toModifiedJulianDay = fromIntegral x}
safeConvert (SqlInt64 x) =
return $ ModifiedJulianDay {toModifiedJulianDay = fromIntegral x}
safeConvert (SqlWord32 x) =
return $ ModifiedJulianDay {toModifiedJulianDay = fromIntegral x}
safeConvert (SqlWord64 x) =
return $ ModifiedJulianDay {toModifiedJulianDay = fromIntegral x}
safeConvert (SqlInteger x) =
return $ ModifiedJulianDay {toModifiedJulianDay = x}
safeConvert y@(SqlChar _) = quickError y
safeConvert y@(SqlBool _) = quickError y
safeConvert (SqlDouble x) =
return $ ModifiedJulianDay {toModifiedJulianDay = truncate x}
safeConvert (SqlRational x) = safeConvert . SqlDouble . fromRational $ x
safeConvert (SqlLocalDate x) = return x
safeConvert y@(SqlLocalTimeOfDay _) = quickError y
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert (SqlLocalTime x) = return . localDay $ x
safeConvert y@(SqlZonedTime _) = safeConvert y >>= return . localDay
safeConvert y@(SqlUTCTime _) = safeConvert y >>= return . localDay
safeConvert y@(SqlDiffTime _) = quickError y
safeConvert y@(SqlPOSIXTime _) = safeConvert y >>= return . localDay
safeConvert y@(SqlEpochTime _) = safeConvert y >>= return . localDay
safeConvert y@(SqlTimeDiff _) = quickError y
safeConvert y@(SqlNull) = quickError y
instance Convertible TimeOfDay SqlValue where
safeConvert = return . SqlLocalTimeOfDay
instance Convertible SqlValue TimeOfDay where
safeConvert (SqlString x) = parseTime' "%T%Q" x
safeConvert (SqlByteString x) = safeConvert (SqlString (BUTF8.toString x))
safeConvert (SqlInt32 x) = return . timeToTimeOfDay . fromIntegral $ x
safeConvert (SqlInt64 x) = return . timeToTimeOfDay . fromIntegral $ x
safeConvert (SqlWord32 x) = return . timeToTimeOfDay . fromIntegral $ x
safeConvert (SqlWord64 x) = return . timeToTimeOfDay . fromIntegral $ x
safeConvert (SqlInteger x) = return . timeToTimeOfDay . fromInteger $ x
safeConvert y@(SqlChar _) = quickError y
safeConvert y@(SqlBool _) = quickError y
safeConvert (SqlDouble x) =
return . timeToTimeOfDay . fromIntegral $ ((truncate x)::Integer)
safeConvert (SqlRational x) = safeConvert . SqlDouble . fromRational $ x
safeConvert y@(SqlLocalDate _) = quickError y
safeConvert (SqlLocalTimeOfDay x) = return x
safeConvert (SqlZonedLocalTimeOfDay tod _) = return tod
safeConvert (SqlLocalTime x) = return . localTimeOfDay $ x
safeConvert y@(SqlZonedTime _) = safeConvert y >>= return . localTimeOfDay
safeConvert y@(SqlUTCTime _) = safeConvert y >>= return . localTimeOfDay
safeConvert y@(SqlDiffTime _) = quickError y
safeConvert y@(SqlPOSIXTime _) = safeConvert y >>= return . localTimeOfDay
safeConvert y@(SqlEpochTime _) = safeConvert y >>= return . localTimeOfDay
safeConvert y@(SqlTimeDiff _) = quickError y
safeConvert y@SqlNull = quickError y
instance Convertible (TimeOfDay, TimeZone) SqlValue where
safeConvert (tod, tz) = return (SqlZonedLocalTimeOfDay tod tz)
instance Convertible SqlValue (TimeOfDay, TimeZone) where
safeConvert (SqlString x) =
do tod <- parseTime' "%T%Q %z" x
#if MIN_TIME_15
tz <- case parseTimeM True defaultTimeLocale "%T%Q %z" x of
#else
tz <- case parseTime defaultTimeLocale "%T%Q %z" x of
#endif
Nothing -> convError "Couldn't extract timezone in" (SqlString x)
Just y -> Right y
return (tod, tz)
safeConvert (SqlByteString x) = safeConvert (SqlString (BUTF8.toString x))
safeConvert y@(SqlInt32 _) = quickError y
safeConvert y@(SqlInt64 _) = quickError y
safeConvert y@(SqlWord32 _) = quickError y
safeConvert y@(SqlWord64 _) = quickError y
safeConvert y@(SqlInteger _) = quickError y
safeConvert y@(SqlChar _) = quickError y
safeConvert y@(SqlBool _) = quickError y
safeConvert y@(SqlDouble _) = quickError y
safeConvert y@(SqlRational _) = quickError y
safeConvert y@(SqlLocalDate _) = quickError y
safeConvert y@(SqlLocalTimeOfDay _) = quickError y
safeConvert (SqlZonedLocalTimeOfDay x y) = return (x, y)
safeConvert y@(SqlLocalTime _) = quickError y
safeConvert (SqlZonedTime x) = return (localTimeOfDay . zonedTimeToLocalTime $ x,
zonedTimeZone x)
safeConvert y@(SqlUTCTime _) = quickError y
safeConvert y@(SqlDiffTime _) = quickError y
safeConvert y@(SqlPOSIXTime _) = quickError y
safeConvert y@(SqlEpochTime _) = quickError y
safeConvert y@(SqlTimeDiff _) = quickError y
safeConvert y@SqlNull = quickError y
instance Convertible LocalTime SqlValue where
safeConvert = return . SqlLocalTime
instance Convertible SqlValue LocalTime where
safeConvert (SqlString x) = parseTime' (iso8601DateFormat (Just "%T%Q")) x
safeConvert (SqlByteString x) = safeConvert (SqlString (BUTF8.toString x))
safeConvert y@(SqlInt32 _) = quickError y
safeConvert y@(SqlInt64 _) = quickError y
safeConvert y@(SqlWord32 _) = quickError y
safeConvert y@(SqlWord64 _) = quickError y
safeConvert y@(SqlInteger _) = quickError y
safeConvert y@(SqlChar _) = quickError y
safeConvert y@(SqlBool _) = quickError y
safeConvert y@(SqlDouble _) = quickError y
safeConvert y@(SqlRational _) = quickError y
safeConvert y@(SqlLocalDate _) = quickError y
safeConvert y@(SqlLocalTimeOfDay _) = quickError y
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert (SqlLocalTime x) = return x
safeConvert (SqlZonedTime x) = return . zonedTimeToLocalTime $ x
safeConvert y@(SqlUTCTime _) = safeConvert y >>= return . zonedTimeToLocalTime
safeConvert y@(SqlDiffTime _) = quickError y
safeConvert y@(SqlPOSIXTime _) = safeConvert y >>= return . zonedTimeToLocalTime
safeConvert y@(SqlEpochTime _) = safeConvert y >>= return . zonedTimeToLocalTime
safeConvert y@(SqlTimeDiff _) = quickError y
safeConvert y@SqlNull = quickError y
instance Convertible ZonedTime SqlValue where
safeConvert = return . SqlZonedTime
instance Convertible SqlValue ZonedTime where
safeConvert (SqlString x) = parseTime' (iso8601DateFormat (Just "%T%Q %z")) x
safeConvert (SqlByteString x) = safeConvert (SqlString (BUTF8.toString x))
safeConvert (SqlInt32 x) = safeConvert (SqlInteger (fromIntegral x))
safeConvert (SqlInt64 x) = safeConvert (SqlInteger (fromIntegral x))
safeConvert (SqlWord32 x) = safeConvert (SqlInteger (fromIntegral x))
safeConvert (SqlWord64 x) = safeConvert (SqlInteger (fromIntegral x))
safeConvert y@(SqlInteger _) = safeConvert y >>= return . utcToZonedTime utc
safeConvert y@(SqlChar _) = quickError y
safeConvert y@(SqlBool _) = quickError y
safeConvert y@(SqlDouble _) = safeConvert y >>= return . utcToZonedTime utc
safeConvert y@(SqlRational _) = safeConvert y >>= return . utcToZonedTime utc
safeConvert y@(SqlLocalDate _) = quickError y
safeConvert y@(SqlLocalTime _) = quickError y
safeConvert y@(SqlLocalTimeOfDay _) = quickError y
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert (SqlZonedTime x) = return x
safeConvert (SqlUTCTime x) = return . utcToZonedTime utc $ x
safeConvert y@(SqlDiffTime _) = quickError y
safeConvert y@(SqlPOSIXTime _) = safeConvert y >>= return . utcToZonedTime utc
safeConvert y@(SqlEpochTime _) = safeConvert y >>= return . utcToZonedTime utc
safeConvert y@(SqlTimeDiff _) = quickError y
safeConvert y@SqlNull = quickError y
instance Convertible UTCTime SqlValue where
safeConvert = return . SqlUTCTime
instance Convertible SqlValue UTCTime where
safeConvert (SqlString x) = parseTime' (iso8601DateFormat (Just "%T%Q")) x
safeConvert (SqlByteString x) = safeConvert (SqlString (BUTF8.toString x))
safeConvert y@(SqlInt32 _) = safeConvert y >>= return . posixSecondsToUTCTime
safeConvert y@(SqlInt64 _) = safeConvert y >>= return . posixSecondsToUTCTime
safeConvert y@(SqlWord32 _) = safeConvert y >>= return . posixSecondsToUTCTime
safeConvert y@(SqlWord64 _) = safeConvert y >>= return . posixSecondsToUTCTime
safeConvert y@(SqlInteger _) = safeConvert y >>= return . posixSecondsToUTCTime
safeConvert y@(SqlChar _) = quickError y
safeConvert y@(SqlBool _) = quickError y
safeConvert y@(SqlDouble _) = safeConvert y >>= return . posixSecondsToUTCTime
safeConvert y@(SqlRational _) = safeConvert y >>= return . posixSecondsToUTCTime
safeConvert y@(SqlLocalDate _) = quickError y
safeConvert y@(SqlLocalTimeOfDay _) = quickError y
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert y@(SqlLocalTime _) = quickError y
safeConvert (SqlZonedTime x) = return . zonedTimeToUTC $ x
safeConvert (SqlUTCTime x) = return x
safeConvert y@(SqlDiffTime _) = convError "incompatible types (did you mean SqlPOSIXTime?)" y
safeConvert (SqlPOSIXTime x) = return . posixSecondsToUTCTime $ x
safeConvert y@(SqlEpochTime _) = safeConvert y >>= return . posixSecondsToUTCTime
safeConvert y@(SqlTimeDiff _) = convError "incompatible types (did you mean SqlPOSIXTime?)" y
safeConvert y@SqlNull = quickError y
stringToPico :: String -> ConvertResult Pico
stringToPico s =
let (base, fracwithdot) = span (/= '.') s
shortfrac = drop 1 fracwithdot -- strip of dot; don't use tail because it may be empty
frac = take 12 (rpad 12 '0' shortfrac)
rpad :: Int -> a -> [a] -> [a]
-- next line lifted from Data.Time
rpad n c xs = xs ++ replicate (n - length xs) c
mkPico :: Integer -> Integer -> Pico
-- next line also lifted from Data.Time
mkPico i f = fromInteger i + fromRational (f % 1000000000000)
in do parsedBase <- read' base
parsedFrac <- read' frac
return (mkPico parsedBase parsedFrac)
instance Convertible NominalDiffTime SqlValue where
safeConvert = return . SqlDiffTime
instance Convertible SqlValue NominalDiffTime where
safeConvert (SqlString x) = stringToPico x >>=
return . realToFrac
safeConvert (SqlByteString x) = (stringToPico (BUTF8.toString x)) >>=
return . realToFrac
safeConvert (SqlInt32 x) = return . fromIntegral $ x
safeConvert (SqlInt64 x) = return . fromIntegral $ x
safeConvert (SqlWord32 x) = return . fromIntegral $ x
safeConvert (SqlWord64 x) = return . fromIntegral $ x
safeConvert (SqlInteger x) = return . fromIntegral $ x
safeConvert y@(SqlChar _) = quickError y
safeConvert y@(SqlBool _) = quickError y
safeConvert (SqlDouble x) = return . fromRational . toRational $ x
safeConvert (SqlRational x) = return . fromRational $ x
safeConvert (SqlLocalDate x) = return . fromIntegral . (\y -> y * 60 * 60 * 24) .
toModifiedJulianDay $ x
safeConvert (SqlLocalTimeOfDay x) =
return . fromRational . toRational . timeOfDayToTime $ x
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert y@(SqlLocalTime _) = quickError y
safeConvert (SqlZonedTime x) = return . utcTimeToPOSIXSeconds . zonedTimeToUTC $ x
safeConvert (SqlUTCTime x) = return . utcTimeToPOSIXSeconds $ x
safeConvert (SqlDiffTime x) = return x
safeConvert (SqlPOSIXTime x) = return x
safeConvert (SqlEpochTime x) = return . fromIntegral $ x
safeConvert (SqlTimeDiff x) = return . fromIntegral $ x
safeConvert y@SqlNull = quickError y
instance Convertible ST.ClockTime SqlValue where
safeConvert x = safeConvert x >>= return . SqlPOSIXTime
instance Convertible SqlValue ST.ClockTime where
safeConvert (SqlString x) = do r <- read' x
return $ ST.TOD r 0
safeConvert (SqlByteString x) = safeConvert . SqlString . BUTF8.toString $ x
safeConvert (SqlInt32 x) = return $ ST.TOD (fromIntegral x) 0
safeConvert (SqlInt64 x) = return $ ST.TOD (fromIntegral x) 0
safeConvert (SqlWord32 x) = return $ ST.TOD (fromIntegral x) 0
safeConvert (SqlWord64 x) = return $ ST.TOD (fromIntegral x) 0
safeConvert (SqlInteger x) = return $ ST.TOD x 0
safeConvert y@(SqlChar _) = quickError y
safeConvert y@(SqlBool _) = quickError y
safeConvert (SqlDouble x) = return $ ST.TOD (truncate x) 0
safeConvert (SqlRational x) = return $ ST.TOD (truncate x) 0
safeConvert y@(SqlLocalDate _) = quickError y
safeConvert y@(SqlLocalTimeOfDay _) = quickError y
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert y@(SqlLocalTime _) = quickError y
safeConvert y@(SqlZonedTime _) = safeConvert y >>= (\z -> return $ ST.TOD z 0)
safeConvert y@(SqlUTCTime _) = safeConvert y >>= (\z -> return $ ST.TOD z 0)
safeConvert y@(SqlDiffTime _) = quickError y
safeConvert y@(SqlPOSIXTime _) = safeConvert y >>= (\z -> return $ ST.TOD z 0)
safeConvert (SqlEpochTime x) = return $ ST.TOD x 0
safeConvert y@(SqlTimeDiff _) = quickError y
safeConvert y@SqlNull = quickError y
instance Convertible ST.TimeDiff SqlValue where
safeConvert x = safeConvert x >>= return . SqlDiffTime
instance Convertible SqlValue ST.TimeDiff where
safeConvert y@(SqlString _) =
do r <- safeConvert y
safeConvert (SqlDiffTime r)
safeConvert (SqlByteString x) = safeConvert . SqlString . BUTF8.toString $ x
safeConvert (SqlInt32 x) = secs2td (fromIntegral x)
safeConvert (SqlInt64 x) = secs2td (fromIntegral x)
safeConvert (SqlWord32 x) = secs2td (fromIntegral x)
safeConvert (SqlWord64 x) = secs2td (fromIntegral x)
safeConvert (SqlInteger x) = secs2td x
safeConvert y@(SqlChar _) = quickError y
safeConvert y@(SqlBool _) = quickError y
safeConvert (SqlDouble x) = secs2td (truncate x)
safeConvert (SqlRational x) = secs2td (truncate x)
safeConvert y@(SqlLocalDate _) = quickError y
safeConvert y@(SqlLocalTimeOfDay _) = quickError y
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert y@(SqlLocalTime _) = quickError y
safeConvert y@(SqlZonedTime _) = quickError y
safeConvert y@(SqlUTCTime _) = quickError y
safeConvert y@(SqlPOSIXTime _) = quickError y
safeConvert (SqlDiffTime x) = safeConvert x
safeConvert y@(SqlEpochTime _) = quickError y
safeConvert (SqlTimeDiff x) = secs2td x
safeConvert y@SqlNull = quickError y
instance Convertible DiffTime SqlValue where
safeConvert = return . SqlDiffTime . fromRational . toRational
instance Convertible SqlValue DiffTime where
safeConvert (SqlString x) = read' x >>= return . fromInteger
safeConvert (SqlByteString x) = safeConvert . SqlString . BUTF8.toString $ x
safeConvert (SqlInt32 x) = return . fromIntegral $ x
safeConvert (SqlInt64 x) = return . fromIntegral $ x
safeConvert (SqlWord32 x) = return . fromIntegral $ x
safeConvert (SqlWord64 x) = return . fromIntegral $ x
safeConvert (SqlInteger x) = return . fromIntegral $ x
safeConvert y@(SqlChar _) = quickError y
safeConvert y@(SqlBool _) = quickError y
safeConvert (SqlDouble x) = return . fromRational . toRational $ x
safeConvert (SqlRational x) = return . fromRational $ x
safeConvert y@(SqlLocalDate _) = quickError y
safeConvert y@(SqlLocalTimeOfDay _) = quickError y
safeConvert y@(SqlZonedLocalTimeOfDay _ _) = quickError y
safeConvert y@(SqlLocalTime _) = quickError y
safeConvert y@(SqlZonedTime _) = quickError y
safeConvert y@(SqlUTCTime _) = quickError y
safeConvert (SqlDiffTime x) = return . fromRational . toRational $ x
safeConvert y@(SqlPOSIXTime _) = quickError y
safeConvert y@(SqlEpochTime _) = quickError y
safeConvert (SqlTimeDiff x) = return . fromIntegral $ x
safeConvert y@SqlNull = quickError y
instance Convertible ST.CalendarTime SqlValue where
-- convert via ZonedTime
safeConvert x = safeConvert x >>= return . SqlZonedTime
instance Convertible SqlValue ST.CalendarTime where
-- convert via ZonedTime
safeConvert = convertVia (undefined::ZonedTime)
instance (Convertible a SqlValue) => Convertible (Maybe a) SqlValue where
safeConvert Nothing = return SqlNull
safeConvert (Just a) = safeConvert a
instance (Convertible SqlValue a) => Convertible SqlValue (Maybe a) where
safeConvert SqlNull = return Nothing
safeConvert a = safeConvert a >>= (return . Just)
viaInteger' :: (Convertible SqlValue a, Bounded a, Show a, Convertible a Integer,
Typeable a) => SqlValue -> (Integer -> ConvertResult a) -> ConvertResult a
viaInteger' sv func =
do i <- ((safeConvert sv)::ConvertResult Integer)
boundedConversion func i
viaInteger :: (Convertible SqlValue a, Bounded a, Show a, Convertible a Integer,
Typeable a) => SqlValue -> (Integer -> a) -> ConvertResult a
viaInteger sv func = viaInteger' sv (return . func)
secs2td :: Integer -> ConvertResult ST.TimeDiff
secs2td x = safeConvert x
-- | Read a value from a string, and give an informative message
-- if it fails.
read' :: (Typeable a, Read a, Convertible SqlValue a) => String -> ConvertResult a
read' s =
case reads s of
[(x,"")] -> Right x
_ -> convError "Cannot read source value as dest type" (SqlString s)
#ifdef __HUGS__
parseTime' :: (Typeable t, Convertible SqlValue t) => String -> String -> ConvertResult t
parseTime' _ inpstr =
convError "Hugs does not support time parsing" (SqlString inpstr)
#else
parseTime' :: (Typeable t, Convertible SqlValue t, ParseTime t) => String -> String -> ConvertResult t
parseTime' fmtstr inpstr =
#if MIN_TIME_15
case parseTimeM True defaultTimeLocale fmtstr inpstr of
#else
case parseTime defaultTimeLocale fmtstr inpstr of
#endif
Nothing -> convError ("Cannot parse using default format string " ++ show fmtstr)
(SqlString inpstr)
Just x -> Right x
#endif
|
cabrera/hdbc
|
Database/HDBC/SqlValue.hs
|
bsd-3-clause
| 46,524
| 2
| 14
| 9,966
| 13,300
| 6,633
| 6,667
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
-- | Examples that should always compile. If reading on Haddock, you
-- can view the sources to each of these.
module Formatting.Examples where
import Data.Text.Lazy (Text)
import Data.Text.Lazy.Builder (Builder)
import Formatting
-- | Simple hello, world!
hello :: Text
hello = format ("Hello, World!")
-- | Printing strings.
strings :: Text
strings =
format ("Here comes a string: " % string % " and another " % string)
"Hello, World!"
"Ahoy!"
-- | Printing texts.
texts :: Text
texts =
format ("Here comes a string: " % text % " and another " % text)
"Hello, World!"
"Ahoy!"
-- | Printing builders.
builders :: Text
builders =
format ("Here comes a string: " % builder % " and another " % text)
("Hello, World!" :: Builder)
"Ahoy!"
-- | Printing integers.
integers :: Text
integers =
format ("Here comes an integer: " % int % " and another: " % int)
(23 :: Int)
(0 :: Integer)
-- | Printing floating points.
floats :: Text
floats =
format ("Here comes a float: " % float % " and a double with sci notation: " % prec 6)
(123.2342 :: Float)
(13434242423.23420000 :: Double)
-- | Printing integrals in hex (base-16).
hexes :: Text
hexes =
format ("Here comes a hex: " % hex)
(123 :: Int)
-- | Padding.
padding :: Text
padding =
format ("A left-padded number: " % left 3 '0')
(9 :: Int)
|
bitemyapp/formatting
|
src/Formatting/Examples.hs
|
bsd-3-clause
| 1,454
| 0
| 9
| 374
| 313
| 181
| 132
| 40
| 1
|
{-# LANGUAGE
TypeFamilies
, FlexibleContexts
, DeriveFunctor
, DeriveFoldable
, DeriveTraversable
#-}
module Compiler.Expression where
import Compiler.Generics
import Control.Monad.State
import Data.Foldable hiding (elem, mapM_, concatMap, concat, foldr)
import Data.Traversable hiding (mapM)
import Prelude hiding (lookup)
-- Expression datatype.
type Con = String
type Name = String
type Var = String
type Body = [Var] -> String
data ExpressionF f =
App f f
| Con Con
| Lam [Var] f
| Name String f
| Prim Body [Var]
| Var Var
deriving (Functor, Foldable, Traversable)
instance Eq f => Eq (ExpressionF f) where
App f g == App h i = f == h && g == i
Con c == Con d = c == d
Lam vs e == Lam ws f = vs == ws && e == f
Name n e == Name m f = n == m && e == f
Prim b vs == Prim c ws = b vs == c ws
Var v == Var w = v == w
_ == _ = False
type ExpressionA a = FixA a ExpressionF
type Expression = Fix ExpressionF
-- Smart constructors.
app :: Expression -> Expression -> Expression
app a b = In (Id (App a b))
con :: Con -> Expression
con a = In (Id (Con a))
lam :: [Var] -> Expression -> Expression
lam as f = In (Id (Lam as f))
name :: Name -> Expression -> Expression
name a b = In (Id (Name a b))
prim :: Body -> [Var] -> Expression
prim f as = In (Id (Prim f as))
var :: Var -> Expression
var a = In (Id (Var a))
|
sebastiaanvisser/AwesomePrelude
|
src/Compiler/Expression.hs
|
bsd-3-clause
| 1,438
| 0
| 9
| 403
| 613
| 318
| 295
| 46
| 1
|
{-# LANGUAGE ScopedTypeVariables #-}
{-
Copyright (C) 2009 John MacFarlane <jgm@berkeley.edu>
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
-}
{- | Useful functions for defining wiki handlers.
-}
module Network.Gitit.Framework (
-- * Combinators for dealing with users
withUserFromSession
, withUserFromHTTPAuth
, authenticateUserThat
, authenticate
, getLoggedInUser
-- * Combinators to exclude certain actions
, unlessNoEdit
, unlessNoDelete
-- * Guards for routing
, guardCommand
, guardPath
, guardIndex
, guardBareBase
-- * Functions to get info from the request
, getPath
, getPage
, getReferer
, getWikiBase
, uriPath
-- * Useful predicates
, isPage
, isPageFile
, isDiscussPage
, isDiscussPageFile
, isSourceCode
-- * Combinators that change the request locally
, withMessages
-- * Miscellaneous
, urlForPage
, pathForPage
, getMimeTypeForExtension
, validate
, filestoreFromConfig
)
where
import Safe
import Network.Gitit.Server
import Network.Gitit.State
import Network.Gitit.Types
import Data.FileStore
import Data.Char (toLower)
import Control.Monad (mzero, liftM, unless)
import qualified Data.Map as M
import qualified Data.ByteString.UTF8 as UTF8
import qualified Data.ByteString.Lazy.UTF8 as LazyUTF8
import Data.Maybe (fromJust, fromMaybe)
import Data.List (intercalate, isPrefixOf, isInfixOf)
import System.FilePath ((<.>), takeExtension, takeFileName)
import Text.Highlighting.Kate
import Text.ParserCombinators.Parsec
import Network.URL (decString, encString)
import Network.URI (isUnescapedInURI)
import Data.ByteString.Base64 (decodeLenient)
import Network.HTTP (urlEncodeVars)
-- | Require a logged in user if the authentication level demands it.
-- Run the handler if a user is logged in, otherwise redirect
-- to login page.
authenticate :: AuthenticationLevel -> Handler -> Handler
authenticate = authenticateUserThat (const True)
-- | Like 'authenticate', but with a predicate that the user must satisfy.
authenticateUserThat :: (User -> Bool) -> AuthenticationLevel -> Handler -> Handler
authenticateUserThat predicate level handler = do
cfg <- getConfig
if level <= requireAuthentication cfg
then do
mbUser <- getLoggedInUser
rq <- askRq
let url = rqUri rq ++ rqQuery rq
case mbUser of
Nothing -> tempRedirect ("/_login?" ++ urlEncodeVars [("destination", url)]) $ toResponse ()
Just u -> if predicate u
then handler
else error "Not authorized."
else handler
-- | Run the handler after setting @REMOTE_USER@ with the user from
-- the session.
withUserFromSession :: Handler -> Handler
withUserFromSession handler = withData $ \(sk :: Maybe SessionKey) -> do
mbSd <- maybe (return Nothing) getSession sk
cfg <- getConfig
mbUser <- case mbSd of
Nothing -> return Nothing
Just sd -> do
addCookie (MaxAge $ sessionTimeout cfg) (mkCookie "sid" (show $ fromJust sk)) -- refresh timeout
case sessionUser sd of
Nothing -> return Nothing
Just user -> getUser user
let user = maybe "" uUsername mbUser
localRq (setHeader "REMOTE_USER" user) handler
-- | Run the handler after setting @REMOTE_USER@ from the "authorization"
-- header. Works with simple HTTP authentication or digest authentication.
withUserFromHTTPAuth :: Handler -> Handler
withUserFromHTTPAuth handler = do
req <- askRq
let user = case getHeader "authorization" req of
Nothing -> ""
Just authHeader -> case parse pAuthorizationHeader "" (UTF8.toString authHeader) of
Left _ -> ""
Right u -> u
localRq (setHeader "REMOTE_USER" user) handler
-- | Returns @Just@ logged in user or @Nothing@.
getLoggedInUser :: GititServerPart (Maybe User)
getLoggedInUser = do
req <- askRq
case maybe "" UTF8.toString (getHeader "REMOTE_USER" req) of
"" -> return Nothing
u -> do
mbUser <- getUser u
case mbUser of
Just user -> return $ Just user
Nothing -> return $ Just User{uUsername = u, uEmail = "", uPassword = undefined}
pAuthorizationHeader :: GenParser Char st String
pAuthorizationHeader = try pBasicHeader <|> pDigestHeader
pDigestHeader :: GenParser Char st String
pDigestHeader = do
_ <- string "Digest username=\""
result' <- many (noneOf "\"")
_ <- char '"'
return result'
pBasicHeader :: GenParser Char st String
pBasicHeader = do
_ <- string "Basic "
result' <- many (noneOf " \t\n")
return $ takeWhile (/=':') $ UTF8.toString
$ decodeLenient $ UTF8.fromString result'
-- | @unlessNoEdit responder fallback@ runs @responder@ unless the
-- page has been designated not editable in configuration; in that
-- case, runs @fallback@.
unlessNoEdit :: Handler
-> Handler
-> Handler
unlessNoEdit responder fallback = withData $ \(params :: Params) -> do
cfg <- getConfig
page <- getPage
if page `elem` noEdit cfg
then withMessages ("Page is locked." : pMessages params) fallback
else responder
-- | @unlessNoDelete responder fallback@ runs @responder@ unless the
-- page has been designated not deletable in configuration; in that
-- case, runs @fallback@.
unlessNoDelete :: Handler
-> Handler
-> Handler
unlessNoDelete responder fallback = withData $ \(params :: Params) -> do
cfg <- getConfig
page <- getPage
if page `elem` noDelete cfg
then withMessages ("Page cannot be deleted." : pMessages params) fallback
else responder
-- | Returns the current path (subtracting initial commands like @\/_edit@).
getPath :: ServerMonad m => m String
getPath = liftM (intercalate "/" . rqPaths) askRq
-- | Returns the current page name (derived from the path).
getPage :: GititServerPart String
getPage = do
conf <- getConfig
path' <- getPath
if null path'
then return (frontPage conf)
else if isPage path'
then return path'
else mzero -- fail if not valid page name
-- | Returns the contents of the "referer" header.
getReferer :: ServerMonad m => m String
getReferer = do
req <- askRq
base' <- getWikiBase
return $ case getHeader "referer" req of
Just r -> case UTF8.toString r of
"" -> base'
s -> s
Nothing -> base'
-- | Returns the base URL of the wiki in the happstack server.
-- So, if the wiki handlers are behind a @dir 'foo'@, getWikiBase will
-- return @\/foo/@. getWikiBase doesn't know anything about HTTP
-- proxies, so if you use proxies to map a gitit wiki to @\/foo/@,
-- you'll still need to follow the instructions in README.
getWikiBase :: ServerMonad m => m String
getWikiBase = do
path' <- getPath
uri' <- liftM (fromJust . decString True . rqUri) askRq
case calculateWikiBase path' uri' of
Just b -> return b
Nothing -> error $ "Could not getWikiBase: (path, uri) = " ++ show (path',uri')
-- | The pure core of 'getWikiBase'.
calculateWikiBase :: String -> String -> Maybe String
calculateWikiBase path' uri' =
let revpaths = reverse . filter (not . null) $ splitOn '/' path'
revuris = reverse . filter (not . null) $ splitOn '/' uri'
in if revpaths `isPrefixOf` revuris
then let revbase = drop (length revpaths) revuris
-- a path like _feed is not part of the base...
revbase' = case revbase of
(x:xs) | startsWithUnderscore x -> xs
xs -> xs
base' = intercalate "/" $ reverse revbase'
in Just $ if null base' then "" else '/' : base'
else Nothing
startsWithUnderscore :: String -> Bool
startsWithUnderscore ('_':_) = True
startsWithUnderscore _ = False
splitOn :: Eq a => a -> [a] -> [[a]]
splitOn c cs =
let (next, rest) = break (==c) cs
in case rest of
[] -> [next]
(_:rs) -> next : splitOn c rs
-- | Returns path portion of URI, without initial @\/@.
-- Consecutive spaces are collapsed. We don't want to distinguish
-- @Hi There@ and @Hi There@.
uriPath :: String -> String
uriPath = unwords . words . drop 1 . takeWhile (/='?')
isPage :: String -> Bool
isPage "" = False
isPage ('_':_) = False
isPage s = all (`notElem` "*?") s && not (".." `isInfixOf` s) && not ("/_" `isInfixOf` s)
-- for now, we disallow @*@ and @?@ in page names, because git filestore
-- does not deal with them properly, and darcs filestore disallows them.
isPageFile :: FilePath -> Bool
isPageFile f = takeExtension f == ".page"
isDiscussPage :: String -> Bool
isDiscussPage ('@':xs) = isPage xs
isDiscussPage _ = False
isDiscussPageFile :: FilePath -> Bool
isDiscussPageFile ('@':xs) = isPageFile xs
isDiscussPageFile _ = False
isSourceCode :: String -> Bool
isSourceCode path' =
let langs = languagesByFilename $ takeFileName path'
ext = takeExtension path'
in not (null langs || ext == ".svg" || ext == ".eps")
-- allow svg or eps to be served as image
-- | Returns encoded URL path for the page with the given name, relative to
-- the wiki base.
urlForPage :: String -> String
urlForPage page = '/' : encString False isUnescapedInURI page
-- | Returns the filestore path of the file containing the page's source.
pathForPage :: String -> FilePath
pathForPage page = page <.> "page"
-- | Retrieves a mime type based on file extension.
getMimeTypeForExtension :: String -> GititServerPart String
getMimeTypeForExtension ext = do
mimes <- liftM mimeMap getConfig
return $ fromMaybe "application/octet-stream"
(M.lookup (dropWhile (== '.') $ map toLower ext) mimes)
-- | Simple helper for validation of forms.
validate :: [(Bool, String)] -- ^ list of conditions and error messages
-> [String] -- ^ list of error messages
validate = foldl go []
where go errs (condition, msg) = if condition then msg:errs else errs
guardCommand :: String -> GititServerPart ()
guardCommand command = withData $ \(com :: Command) ->
case com of
Command (Just c) | c == command -> return ()
_ -> mzero
guardPath :: (String -> Bool) -> GititServerPart ()
guardPath pred' = guardRq (pred' . rqUri)
-- | Succeeds if path is an index path: e.g. @\/foo\/bar/@.
guardIndex :: GititServerPart ()
guardIndex = do
base <- getWikiBase
uri' <- liftM rqUri askRq
let localpath = drop (length base) uri'
unless (length localpath > 1 && lastNote "guardIndex" uri' == '/')
mzero
-- Guard against a path like @\/wiki@ when the wiki is being
-- served at @\/wiki@.
guardBareBase :: GititServerPart ()
guardBareBase = do
base' <- getWikiBase
uri' <- liftM rqUri askRq
unless (not (null base') && base' == uri')
mzero
-- | Runs a server monad in a local context after setting
-- the "message" request header.
withMessages :: ServerMonad m => [String] -> m a -> m a
withMessages messages handler = do
req <- askRq
let inps = filter (\(n,_) -> n /= "message") $ rqInputsQuery req
let newInp msg = ("message", Input {
inputValue = Right
$ LazyUTF8.fromString msg
, inputFilename = Nothing
, inputContentType = ContentType {
ctType = "text"
, ctSubtype = "plain"
, ctParameters = [] }
})
localRq (\rq -> rq{ rqInputsQuery = map newInp messages ++ inps }) handler
-- | Returns a filestore object derived from the
-- repository path and filestore type specified in configuration.
filestoreFromConfig :: Config -> FileStore
filestoreFromConfig conf =
case repositoryType conf of
Git -> gitFileStore $ repositoryPath conf
Darcs -> darcsFileStore $ repositoryPath conf
Mercurial -> mercurialFileStore $ repositoryPath conf
|
imuli/gitit
|
Network/Gitit/Framework.hs
|
gpl-2.0
| 13,870
| 0
| 20
| 4,314
| 2,877
| 1,494
| 1,383
| 247
| 4
|
module FooSpec (main, spec) where
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "reverse" $ do
it "reverses a list" $ do
reverse [1 :: Int, 2, 3] `shouldBe` [3, 2, 1]
|
hspec/hspec
|
hspec-discover/integration-test/with-io-formatter/FooSpec.hs
|
mit
| 228
| 0
| 15
| 66
| 98
| 54
| 44
| 9
| 1
|
module Main where
data Foo = Bar Int Float | Baz String
main = print foo
bar = Bar 5 2.1
foo = case bar of
Bar x f -> show x
Baz s -> s
|
beni55/hermit
|
examples/casereduce/Main.hs
|
bsd-2-clause
| 155
| 0
| 8
| 55
| 70
| 36
| 34
| 7
| 2
|
f = foo (\x -> \x -> foo x x)
|
bitemyapp/apply-refact
|
tests/examples/Lambda19.hs
|
bsd-3-clause
| 29
| 0
| 9
| 9
| 27
| 14
| 13
| 1
| 1
|
{-# OPTIONS -Wall #-}
-----------------------------------------------------------------------------
-- |
-- Module : CEquiv.hs (Executable)
-- Copyright : (c) 2008 Benedikt Huber
-- License : BSD-style
-- Maintainer : benedikt.huber@gmail.com
--
-- This module is invoked just like gcc. It preprocesses the two C source files given in the arguments
-- and parses them. Then it compares the ASTs. If CTEST_NON_EQUIV is set, the comparison is expected to fail,
-- otherwise it is expected that the ASTs are equal.
--
-- Tests are logged, and serialized into a result file.
-- If the CEquiv finishes without runtime error, it always returns ExitSuccess.
--
-- see 'TestEnvironment'.
-----------------------------------------------------------------------------
module Main (main) where
import Control.Monad.State
import System.FilePath (takeBaseName)
import Text.PrettyPrint
import Language.C.Data
import Language.C.Test.Environment
import Language.C.Test.Framework
import Language.C.Test.ParseTests
import Language.C.Test.TestMonad
nonEquivEnvVar :: String
nonEquivEnvVar = "CTEST_NON_EQUIV"
main :: IO ()
main = defaultMain usage theEquivTest
usage :: Doc
usage = text "./Equiv [gcc-opts] file.1.(c|hc|i) file.2.(c|hc|i)"
$$ nest 4 (text "Test Driver: Parses two files and compares the ASTs")
$$ envHelpDoc [ (nonEquivEnvVar, ("expected that the ASTs aren't equal",Just "False")) ]
theEquivTest :: [String] -> TestMonad ()
theEquivTest args =
case mungeCcArgs args of
Ignore -> errorOnInit args $ "No C source file found in argument list: `cc " ++ unwords args ++ "'"
Unknown err -> errorOnInit args $ "Could not munge CC args: " ++ err ++ " in `cc "++ unwords args ++ "'"
Groked [f1,f2] gccArgs -> theEquivTest' f1 f2 gccArgs
Groked cFiles _ -> errorOnInit args $ "Expected two C source files, but found " ++ unwords cFiles
theEquivTest' :: FilePath -> FilePath -> [String] -> TestMonad ()
theEquivTest' f1 f2 gccArgs = do
dbgMsg $ "Comparing the ASTs of " ++ f1 ++ " and " ++ f2
expectNonEquiv <- liftIO$ getEnvFlag nonEquivEnvVar
dbgMsg $ "Expecting that the ASTs " ++ (if expectNonEquiv then " don't match" else "match") ++ ".\n"
modify $ setTmpTemplate (takeBaseName f1)
(cFile1, preFile1) <- runCPP f1 gccArgs
modify $ setTmpTemplate (takeBaseName f2)
(cFile2, preFile2) <- runCPP f2 gccArgs
modify $ setTestRunResults (emptyTestResults (takeBaseName (f1 ++ " == " ++ f2)) [cFile1,cFile2])
let parseTest1 = initializeTestResult (parseTestTemplate { testName = "01-parse" }) [f1]
let parseTest2 = initializeTestResult (parseTestTemplate { testName = "02-parse" }) [f2]
modify $ setTmpTemplate (takeBaseName f1)
parseResult1 <- runParseTest preFile1 (initPos cFile1)
addTestM $
setTestStatus parseTest1 $
either (uncurry testFailWithReport) (testOkNoReport . snd) parseResult1
ast1 <- either (const exitTest) (return . fst) parseResult1
modify $ setTmpTemplate (takeBaseName f2)
parseResult2 <- runParseTest preFile2 (initPos cFile2)
addTestM $
setTestStatus parseTest2 $
either (uncurry testFailWithReport) (testOkNoReport . snd) parseResult2
ast2 <- either (const exitTest) (return . fst) parseResult2
-- check equiv
modify $ setTmpTemplate (takeBaseName f1 ++ "_eq_" ++ takeBaseName f2)
equivResult <- runEquivTest ast1 ast2
case expectNonEquiv of
False ->
let equivTest = initializeTestResult (equivTestTemplate { testName = "03-equiv" }) [] in
addTestM . setTestStatus equivTest $
either (uncurry testFailure) testOkNoReport equivResult
True ->
let equivTest = initializeTestResult (equivTestTemplate { testName = "03-non-equiv" }) [] in
addTestM . setTestStatus equivTest $
either (\(_,mReport) -> testOkUntimed mReport)
(\_ -> testFailNoReport "ASTs are equivalent") equivResult
|
vincenthz/language-c
|
test/src/CEquiv.hs
|
bsd-3-clause
| 3,995
| 0
| 17
| 814
| 942
| 481
| 461
| 61
| 4
|
{-
types:
A__a :: (*, data)
A__b :: (*, data)
Pair :: (*, data)
values:
f :: (A__a, A__b) -> Pair
g :: Pair -> A__a
A__a :: A__a
A__b :: A__b
Pair :: (A__a, A__b) -> Pair
scope:
Prelude.A__a |-> Prelude.A__a, Type [A__a] []
Prelude.A__a |-> Prelude.A__a, con of A__a
Prelude.A__b |-> Prelude.A__b, Type [A__b] []
Prelude.A__b |-> Prelude.A__b, con of A__b
Prelude.Pair |-> Prelude.Pair, Type [Pair] []
Prelude.Pair |-> Prelude.Pair, con of Pair
Prelude.f |-> Prelude.f, Value
Prelude.g |-> Prelude.g, Value
A__a |-> Prelude.A__a, Type [A__a] []
A__a |-> Prelude.A__a, con of A__a
A__b |-> Prelude.A__b, Type [A__b] []
A__b |-> Prelude.A__b, con of A__b
Pair |-> Prelude.Pair, Type [Pair] []
Pair |-> Prelude.Pair, con of Pair
f |-> Prelude.f, Value
g |-> Prelude.g, Value
-}
module Dummy where
data A__a = A__a
data A__b = A__b
f :: (A__a, A__b) -> Pair
g :: Pair -> A__a
data Pair = Pair !(A__a, A__b)
f (a, b) = Pair (a, b)
g (Pair (a, b)) = a
|
keithodulaigh/Hets
|
ToHaskell/test/Pair.hascasl.hs
|
gpl-2.0
| 949
| 0
| 8
| 172
| 102
| 59
| 43
| 10
| 1
|
{-# OPTIONS -XNoImplicitPrelude #-}
-- This one crashed GHC 6.6 in lookupDeprec
-- See #1128
-- and Note [Used names with interface not loaded]
-- in RnNames
module ShouldCompile where
import Prelude
foo :: Int -> Float
foo x = 3.0
|
sdiehl/ghc
|
testsuite/tests/rename/should_compile/rn051.hs
|
bsd-3-clause
| 236
| 0
| 5
| 45
| 29
| 19
| 10
| 5
| 1
|
{-# LANGUAGE ForeignFunctionInterface, BangPatterns, ScopedTypeVariables, TupleSections,
RecordWildCards, NoMonomorphismRestriction #-}
module Main where
import AI.SVM.Simple
import qualified Data.Vector.Storable as V
import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
import Diagrams.Backend.Cairo
import System.Random.MWC
import Control.Applicative
import Control.Monad
scaledN g = (+0.5) . (/10) <$> normal g
main = do
pts ::[(Double,Double)]
<- withSystemRandom $ \g -> zip <$> replicateM 30 (scaledN g :: IO Double)
<*> replicateM 30 (scaledN g :: IO Double)
let (msg, svm2) = trainOneClass 0.01 (RBF 1) pts
putStrLn msg
let plot =
foldl (atop) (circle # scale 0.025)
[circle # scale 0.022 # translate (x,y) # fc green
| (x,y) <- pts ]
`atop`
foldl (atop) (circle # scale 0.025)
[circle # scale 0.012 # translate (x,y) # fc (color svm2 (x,y))
| x <- [0,0.025..1], y <- [0,0.025..1]]
fst $ renderDia Cairo (CairoOptions ("test.png") (PNG (400,400))) (plot # lineWidth 0.002)
where
color svm pt = case inSet svm pt of
In -> red
Out -> black
between a x b = a <= x && x <= b
|
openbrainsrc/Simple-SVM
|
Examples/PlotOneClass.hs
|
bsd-3-clause
| 1,335
| 0
| 17
| 415
| 471
| 251
| 220
| 31
| 2
|
{-# OPTIONS_GHC -fwarn-unused-matches #-}
-- #17
module Temp (foo, bar, quux) where
top :: Int
top = 1
foo :: ()
foo = let True = True in ()
bar :: Int -> Int
bar match = 1
quux :: Int
quux = let local = True
in 2
|
sdiehl/ghc
|
testsuite/tests/rename/should_compile/T17d.hs
|
bsd-3-clause
| 227
| 0
| 8
| 62
| 91
| 51
| 40
| 11
| 1
|
module Distribution.Simple.HaskellSuite where
import Control.Monad
import Data.Maybe
import Data.Version
import qualified Data.Map as M (empty)
import Distribution.Simple.Program
import Distribution.Simple.Compiler as Compiler
import Distribution.Simple.Utils
import Distribution.Simple.BuildPaths
import Distribution.Verbosity
import Distribution.Text
import Distribution.Package
import Distribution.InstalledPackageInfo hiding (includeDirs)
import Distribution.Simple.PackageIndex as PackageIndex
import Distribution.PackageDescription
import Distribution.Simple.LocalBuildInfo
import Distribution.System (Platform)
import Distribution.Compat.Exception
import Language.Haskell.Extension
import Distribution.Simple.Program.Builtin
configure
:: Verbosity -> Maybe FilePath -> Maybe FilePath
-> ProgramConfiguration -> IO (Compiler, Maybe Platform, ProgramConfiguration)
configure verbosity mbHcPath hcPkgPath conf0 = do
-- We have no idea how a haskell-suite tool is named, so we require at
-- least some information from the user.
hcPath <-
let msg = "You have to provide name or path of a haskell-suite tool (-w PATH)"
in maybe (die msg) return mbHcPath
when (isJust hcPkgPath) $
warn verbosity "--with-hc-pkg option is ignored for haskell-suite"
(comp, confdCompiler, conf1) <- configureCompiler hcPath conf0
-- Update our pkg tool. It uses the same executable as the compiler, but
-- all command start with "pkg"
(confdPkg, _) <- requireProgram verbosity haskellSuitePkgProgram conf1
let conf2 =
updateProgram
confdPkg
{ programLocation = programLocation confdCompiler
, programDefaultArgs = ["pkg"]
}
conf1
return (comp, Nothing, conf2)
where
configureCompiler hcPath conf0' = do
let
haskellSuiteProgram' =
haskellSuiteProgram
{ programFindLocation = \v p -> findProgramOnSearchPath v p hcPath }
-- NB: cannot call requireProgram right away — it'd think that
-- the program is already configured and won't reconfigure it again.
-- Instead, call configureProgram directly first.
conf1 <- configureProgram verbosity haskellSuiteProgram' conf0'
(confdCompiler, conf2) <- requireProgram verbosity haskellSuiteProgram' conf1
extensions <- getExtensions verbosity confdCompiler
languages <- getLanguages verbosity confdCompiler
(compName, compVersion) <-
getCompilerVersion verbosity confdCompiler
let
comp = Compiler {
compilerId = CompilerId (HaskellSuite compName) compVersion,
compilerAbiTag = Compiler.NoAbiTag,
compilerCompat = [],
compilerLanguages = languages,
compilerExtensions = extensions,
compilerProperties = M.empty
}
return (comp, confdCompiler, conf2)
hstoolVersion :: Verbosity -> FilePath -> IO (Maybe Version)
hstoolVersion = findProgramVersion "--hspkg-version" id
numericVersion :: Verbosity -> FilePath -> IO (Maybe Version)
numericVersion = findProgramVersion "--compiler-version" (last . words)
getCompilerVersion :: Verbosity -> ConfiguredProgram -> IO (String, Version)
getCompilerVersion verbosity prog = do
output <- rawSystemStdout verbosity (programPath prog) ["--compiler-version"]
let
parts = words output
name = concat $ init parts -- there shouldn't be any spaces in the name anyway
versionStr = last parts
version <-
maybe (die "haskell-suite: couldn't determine compiler version") return $
simpleParse versionStr
return (name, version)
getExtensions :: Verbosity -> ConfiguredProgram -> IO [(Extension, Compiler.Flag)]
getExtensions verbosity prog = do
extStrs <-
lines `fmap`
rawSystemStdout verbosity (programPath prog) ["--supported-extensions"]
return
[ (ext, "-X" ++ display ext) | Just ext <- map simpleParse extStrs ]
getLanguages :: Verbosity -> ConfiguredProgram -> IO [(Language, Compiler.Flag)]
getLanguages verbosity prog = do
langStrs <-
lines `fmap`
rawSystemStdout verbosity (programPath prog) ["--supported-languages"]
return
[ (ext, "-G" ++ display ext) | Just ext <- map simpleParse langStrs ]
-- Other compilers do some kind of a packagedb stack check here. Not sure
-- if we need something like that as well.
getInstalledPackages :: Verbosity -> PackageDBStack -> ProgramConfiguration
-> IO InstalledPackageIndex
getInstalledPackages verbosity packagedbs conf =
liftM (PackageIndex.fromList . concat) $ forM packagedbs $ \packagedb ->
do str <-
getDbProgramOutput verbosity haskellSuitePkgProgram conf
["dump", packageDbOpt packagedb]
`catchExit` \_ -> die $ "pkg dump failed"
case parsePackages str of
Right ok -> return ok
_ -> die "failed to parse output of 'pkg dump'"
where
parsePackages str =
let parsed = map parseInstalledPackageInfo (splitPkgs str)
in case [ msg | ParseFailed msg <- parsed ] of
[] -> Right [ pkg | ParseOk _ pkg <- parsed ]
msgs -> Left msgs
splitPkgs :: String -> [String]
splitPkgs = map unlines . splitWith ("---" ==) . lines
where
splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith p xs = ys : case zs of
[] -> []
_:ws -> splitWith p ws
where (ys,zs) = break p xs
buildLib
:: Verbosity -> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO ()
buildLib verbosity pkg_descr lbi lib clbi = do
-- In future, there should be a mechanism for the compiler to request any
-- number of the above parameters (or their parts) — in particular,
-- pieces of PackageDescription.
--
-- For now, we only pass those that we know are used.
let odir = buildDir lbi
bi = libBuildInfo lib
srcDirs = hsSourceDirs bi ++ [odir]
dbStack = withPackageDB lbi
language = fromMaybe Haskell98 (defaultLanguage bi)
conf = withPrograms lbi
pkgid = packageId pkg_descr
runDbProgram verbosity haskellSuiteProgram conf $
[ "compile", "--build-dir", odir ] ++
concat [ ["-i", d] | d <- srcDirs ] ++
concat [ ["-I", d] | d <- [autogenModulesDir lbi clbi, odir] ++ includeDirs bi ] ++
[ packageDbOpt pkgDb | pkgDb <- dbStack ] ++
[ "--package-name", display pkgid ] ++
concat [ ["--package-id", display ipkgid ]
| (ipkgid, _) <- componentPackageDeps clbi ] ++
["-G", display language] ++
concat [ ["-X", display ex] | ex <- usedExtensions bi ] ++
cppOptions (libBuildInfo lib) ++
[ display modu | modu <- libModules lib ]
installLib
:: Verbosity
-> LocalBuildInfo
-> FilePath -- ^install location
-> FilePath -- ^install location for dynamic libraries
-> FilePath -- ^Build location
-> PackageDescription
-> Library
-> ComponentLocalBuildInfo
-> IO ()
installLib verbosity lbi targetDir dynlibTargetDir builtDir pkg lib _clbi = do
let conf = withPrograms lbi
runDbProgram verbosity haskellSuitePkgProgram conf $
[ "install-library"
, "--build-dir", builtDir
, "--target-dir", targetDir
, "--dynlib-target-dir", dynlibTargetDir
, "--package-id", display $ packageId pkg
] ++ map display (libModules lib)
registerPackage
:: Verbosity
-> ProgramConfiguration
-> PackageDBStack
-> InstalledPackageInfo
-> IO ()
registerPackage verbosity progdb packageDbs installedPkgInfo = do
(hspkg, _) <- requireProgram verbosity haskellSuitePkgProgram progdb
runProgramInvocation verbosity $
(programInvocation hspkg
["update", packageDbOpt $ last packageDbs])
{ progInvokeInput = Just $ showInstalledPackageInfo installedPkgInfo }
initPackageDB :: Verbosity -> ProgramConfiguration -> FilePath -> IO ()
initPackageDB verbosity conf dbPath =
runDbProgram verbosity haskellSuitePkgProgram conf
["init", dbPath]
packageDbOpt :: PackageDB -> String
packageDbOpt GlobalPackageDB = "--global"
packageDbOpt UserPackageDB = "--user"
packageDbOpt (SpecificPackageDB db) = "--package-db=" ++ db
|
thomie/cabal
|
Cabal/Distribution/Simple/HaskellSuite.hs
|
bsd-3-clause
| 8,212
| 0
| 21
| 1,850
| 1,988
| 1,033
| 955
| 172
| 4
|
{-# LANGUAGE Safe #-}
-- This module deliberately declares orphan instances:
{-# OPTIONS_GHC -Wno-orphans #-}
-----------------------------------------------------------------------------
-- |
-- Module : Text.Show.Functions
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Optional instance of 'Text.Show.Show' for functions:
--
-- > instance Show (a -> b) where
-- > showsPrec _ _ = showString \"\<function\>\"
--
-----------------------------------------------------------------------------
module Text.Show.Functions () where
instance Show (a -> b) where
showsPrec _ _ = showString "<function>"
|
tolysz/prepare-ghcjs
|
spec-lts8/base/Text/Show/Functions.hs
|
bsd-3-clause
| 796
| 0
| 7
| 130
| 57
| 40
| 17
| 5
| 0
|
-- |
-- Module : Data.Text.Encoding.Utf32
-- Copyright : (c) 2008, 2009 Tom Harper,
-- (c) 2009, 2010 Bryan O'Sullivan,
-- (c) 2009 Duncan Coutts
--
-- License : BSD-style
-- Maintainer : bos@serpentine.com, rtomharper@googlemail.com,
-- duncan@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Basic UTF-32 validation.
module Data.Text.Encoding.Utf32
(
validate
) where
import Data.Word (Word32)
validate :: Word32 -> Bool
validate x1 = x1 < 0xD800 || (x1 > 0xDFFF && x1 <= 0x10FFFF)
{-# INLINE validate #-}
|
mightymoose/liquidhaskell
|
benchmarks/text-0.11.2.3/Data/Text/Encoding/Utf32.hs
|
bsd-3-clause
| 606
| 0
| 9
| 157
| 77
| 50
| 27
| 7
| 1
|
{-# LANGUAGE TypeFamilies #-}
module A where
type family F a
type instance F Int = Bool
|
ezyang/ghc
|
testsuite/tests/driver/recomp016/A.hs
|
bsd-3-clause
| 88
| 0
| 4
| 17
| 21
| 14
| 7
| 4
| 0
|
{-# OPTIONS_GHC -fwarn-unused-top-binds #-}
-- Trac #17
module Temp (foo, bar, quux) where
top :: Int
top = 1
foo :: ()
foo = let True = True in ()
bar :: Int -> Int
bar match = 1
quux :: Int
quux = let local = True
in 2
|
oldmanmike/ghc
|
testsuite/tests/rename/should_compile/T17a.hs
|
bsd-3-clause
| 234
| 0
| 8
| 63
| 91
| 51
| 40
| 11
| 1
|
-- re-export all of T
module Mod117_B (T(..)) where
import Mod117_A ( T(T,m1),m2 )
|
olsner/ghc
|
testsuite/tests/module/Mod117_B.hs
|
bsd-3-clause
| 84
| 0
| 6
| 15
| 31
| 22
| 9
| 2
| 0
|
{-# LANGUAGE TupleSections #-}
module Main where
import Control.Monad.Except ( MonadError(..) )
-- import Control.Bifunctor
import qualified Data.List as List
import Lexer (alexScanTokens)
import qualified Parser as HappyParser
import qualified Concrete as C
import qualified Abstract as A
-- import qualified Stream -- NOT USED
import TheMonad
import qualified Scoping
import qualified ScopeMonad as Scoping
-- import ErrorExpected
-- Engines
import qualified OrderedCom2 as Ordered
import qualified Closures
import qualified Monolith
import qualified HerBruijn
import qualified NamedExplSubst
import qualified TGChecker
import System.Exit
import System.Environment (getArgs)
import System.IO (stdout, hSetBuffering, BufferMode(..))
import System.Console.GetOpt
( getOpt, usageInfo, ArgOrder(Permute,ReturnInOrder)
, OptDescr(..), ArgDescr(..)
)
data Engine = Closures | Ordered | HerBruijn | Monolith | TGChecker
deriving (Eq,Show,Enum,Bounded,Read)
engines :: [Engine]
engines = [minBound..maxBound]
defaultEngine = Closures
{-
data Options = Options
{ optEngine :: Engine
-- , optInputFile :: Maybe FilePath
}
defaultOptions :: Options
defaultOptions = Options
{ optEngine = defaultEngine
-- , optInputFile = Nothing
}
{- | @f :: Flag opts@ is an action on the option record that results from
parsing an option. @f opts@ produces either an error message or an
updated options record
-}
type Flag opts = opts -> opts -- Either String opts
-}
{-
inputFlag :: FilePath -> Flag Options
inputFlag f o =
case optInputFile o of
Nothing -> return $ o { optInputFile = Just f }
Just _ -> throwError "only one input file allowed"
-}
data Flag = Engine Engine
deriving Show
engineFlag :: String -> Flag
engineFlag arg =
let engine :: Engine
engine = read arg
in Engine engine
options :: [OptDescr Flag]
options =
[ Option ['e'] ["engine"] (ReqArg engineFlag "ENGINE")
("set lambda engine (default = " ++ show defaultEngine ++ "), possible values: " ++ show engines)
]
{-
engineFlag :: String -> Flag Options
engineFlag arg o =
let engine :: Engine
engine = read arg
in o { optEngine = engine }
options :: [OptDescr (Flag Options)]
options =
[ Option ['e'] ["engine"] (ReqArg engineFlag "ENGINE")
("set lambda engine (default = " ++ show defaultEngine ++ "), possible values: " ++ show engines)
]
-- | Don't export
parseOptions' ::
[String] -> [OptDescr (Flag opts)] -> (String -> Flag opts) -> Flag opts
parseOptions' argv opts = \defaults ->
case getOpt (Permute) opts argv of
(o,_,[]) -> foldl (>>=) (return defaults) o
(_,_,errs) -> throwError $ concat errs
-- | Parse the standard options.
parseOptions :: [String] -> Either String Options
parseOptions argv =
-- checkOpts =<<
parseOptions' argv options inputFlag defaultOptions
-}
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
putStrLn $ "HELF - Haskell implementation of the Edinburgh Logical Framework"
putStrLn $ "(C) Andreas Abel and Nicolai Kraus"
args <- getArgs
(o,files) <- case getOpt Permute options args of
(o,files,[]) -> return (o,files)
(_,_,errs) -> do
putStrLn ("error during parsing commandline:" ++ show errs)
exitFailure
let isEngine Engine{} = True
-- isEngine _ = False -- currently every flag is Engine
let engine = case List.find isEngine o of
Nothing -> defaultEngine
Just (Engine e) -> e
mapM_ (mainFile engine) files
mainFile :: Engine -> String -> IO ()
mainFile engine fileName = do
putStrLn $ "%%% opening " ++ show fileName ++ " %%%"
file <- readFile fileName
-- putStrLn "%%% lexing %%%"
let t = alexScanTokens file
-- putStrLn (show t)
putStrLn $ "%%% parsing %%%"
let cdecls = HappyParser.parse t
{-
putStrLn (show cdecls)
-}
putStrLn $ "%%% scope checking %%%"
(adecls, st) <- doScopeCheck cdecls
{-
-- cdecls <- doUnparse adecls st
cdecls <- return $ runSRM (Scoping.unparse adecls) st
putStrLn . show $ cdecls
-}
putStrLn $ "%%% type checking with engine " ++ show engine ++ " %%%"
doTypeCheck engine st adecls
putStrLn $ "%%% closing " ++ show fileName ++ " %%%"
runCheckDecls Closures = Closures.runCheckDecls
runCheckDecls Ordered = Ordered.runCheckDecls
runCheckDecls HerBruijn = HerBruijn.runCheckDecls
runCheckDecls Monolith = Monolith.runCheckDecls
runCheckDecls TGChecker = TGChecker.runCheckDecls
doTypeCheck :: Engine -> Scoping.ScopeState -> A.Declarations -> IO ()
doTypeCheck engine st decls = do
res <- runCheckDecls engine decls
case res of
Left err -> do
putStrLn $ "error during typechecking:\n" ++ err
exitFailure
Right () -> return ()
{-
Right (edecls, st) ->
return (edecls, signature st)
-}
doScopeCheck :: C.Declarations -> IO (A.Declarations, TheState)
doScopeCheck cdecls = case runTCM (Scoping.parse cdecls) initState of
Left err -> do
putStrLn $ "scope check error: " ++ show err
exitFailure
Right (adecls, st) -> return (adecls, st)
{- an unfinished attempt to use streams
data StList s e a
= Fail e
| Done s
| Cons a (StList s e a)
build :: (s -> Either e (Either s' (a, s))) -> s -> StList s' e a
build f s = loop (f s) where
loop result = case result of
Left err -> Fail err
Right (Left s') -> Done s'
Right (Right (a, s)) -> Cons a (loop (f s))
scopeCheck :: C.Declarations -> StList TheState Scoping.ParseError [A.Declaration]
scopeCheck (C.Declarations cdecls) = build step (cdecls, initState) where
step :: ([C.Declaration], TheState) -> Either Scoping.ParseError (Either TheState ([A.Declaration], ([C.Declaration], TheState)))
step ([] , st) = Right $ Left st
step (d:ds, st) = bimap id (Right . bimap id (ds,)) $ runTCM (Scoping.parse d) st
-}
{-
scopeCheckStream ::
scopeCheckStream cdecls = foldr
(\ cdecl (adecls, st) ->
let (ds, st') = runTCM (Scoping.parse cdecl) st
in (ds
-}
{-
scopeCheckStream :: C.Declarations -> Stream TCM A.Declaration
scopeCheckStream (C.Declarations cdecls) = loop cdecls initState where
loop [] st = Stream.empty
loop (cdec:cdecls) =
-}
{-
doUnparse :: A.Declarations -> TheState -> IO C.Declarations
doUnparse adecls st = case runTCM (Scoping.unparse adecls) st of
Left err -> do
putStrLn $ "error during unparsing: " ++ show err
exitFailure
Right (cdecls, _) -> return cdecls
-}
|
andreasabel/helf
|
src/Main.hs
|
mit
| 6,549
| 0
| 16
| 1,461
| 961
| 516
| 445
| 86
| 3
|
{-# LANGUAGE BangPatterns #-}
module Main where
import Control.Arrow ((&&&))
import Data.Bifunctor (bimap)
import Data.Bool (bool)
import Data.Foldable (foldl', maximumBy, traverse_)
import Data.Ix (range)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Ord (comparing)
import Linear.V2 (V2 (..))
type Cell = V2 Int
type Table = Map Cell Int
rangeC :: (Int, Int) -> [Cell]
rangeC = range . bimap pure pure
{-# INLINE rangeC #-}
main :: IO ()
main = do
let t = makeTable 6878
traverse_ (putStrLn . ($ t)) [part1, part2]
part1 :: Table -> String
part1 table = show x <> "," <> show y
where (V2 x y) = fst . argMax $ summedAreaTable 3 table
part2 :: Table -> String
part2 table = show x <> "," <> show y <> "," <> show size
where
(V2 x y, size) =
fst . maximumBy (comparing snd) . fmap best $ range (1, 300)
best s =
let (c, p) = argMax $ summedAreaTable s table in ((c, s), p)
makeTable :: Int -> Table
makeTable serial =
foldl' add M.empty . fmap (id &&& power serial) $ rangeC (1, 300)
where
add table (c, p) = M.insert c (p + q) table
where
!q = sum [f a, f b, -f d]
!a = c - V2 1 0
!b = c - V2 0 1
!d = c - V2 1 1
f = flip (M.findWithDefault 0) table
{-# INLINE f #-}
power :: Int -> Cell -> Int
power serial (V2 x y) = h - 5
where
!rackID = x + 10
!h = (((rackID * y + serial) * rackID) `div` 100) `mod` 10
{-# INLINE power #-}
summedAreaTable :: Int -> Table -> Table
summedAreaTable size table =
M.fromList . fmap (id &&& subCellPower) $ rangeC (1, 301 - size)
where
subCellPower :: Cell -> Int
subCellPower cell = sum [f c, f a, -f b, -f d]
where
!c = cell - pure 1
!a = c + pure size
!b = c + V2 0 size
!d = c + V2 size 0
f = flip (M.findWithDefault 0) table
{-# INLINE f #-}
argMax :: Ord b => M.Map a b -> (a, b)
argMax m = M.foldrWithKey' f (M.findMin m) m
where
f k v (k', v') = bool (k', v') (k, v) (v > v')
{-# INLINE f #-}
|
genos/online_problems
|
advent_of_code_2018/day11/src/Main.hs
|
mit
| 2,145
| 3
| 14
| 673
| 973
| 510
| 463
| 59
| 1
|
-- | This module re-exports asset loading from asset sub-modules.
module FRP.Jalapeno.Assets ( module FRP.Jalapeno.Assets.Shader
) where
-------------
-- Imports --
import FRP.Jalapeno.Assets.Shader
----------
-- Code --
|
crockeo/jalapeno
|
src/lib/FRP/Jalapeno/Assets.hs
|
mit
| 250
| 0
| 5
| 56
| 29
| 22
| 7
| 2
| 0
|
-- Generated by protobuf-simple. DO NOT EDIT!
module Types.Fixed32List where
import Control.Applicative ((<$>))
import Prelude ()
import qualified Data.ProtoBufInt as PB
newtype Fixed32List = Fixed32List
{ value :: PB.Seq PB.Word32
} deriving (PB.Show, PB.Eq, PB.Ord)
instance PB.Default Fixed32List where
defaultVal = Fixed32List
{ value = PB.defaultVal
}
instance PB.Mergeable Fixed32List where
merge a b = Fixed32List
{ value = PB.merge (value a) (value b)
}
instance PB.Required Fixed32List where
reqTags _ = PB.fromList []
instance PB.WireMessage Fixed32List where
fieldToValue (PB.WireTag 1 PB.Bit32) self = (\v -> self{value = PB.append (value self) v}) <$> PB.getFixed32
fieldToValue tag self = PB.getUnknown tag self
messageToFields self = do
PB.putFixed32List (PB.WireTag 1 PB.Bit32) (value self)
|
sru-systems/protobuf-simple
|
test/Types/Fixed32List.hs
|
mit
| 852
| 0
| 13
| 156
| 291
| 156
| 135
| 20
| 0
|
-- This module defines the expression languages and fundamental expression
-- algorithms.
module Expressions(
Expr(..),
QType(..),
CType(..),
ExprName(..),
TypeName(..),
TlExpr(..),
substExpr,
substExprs,
areStructurallyEqualExpr,
areStructurallyEqualCType,
areStructurallyEqualQType ) where
import Util.DebugOr ( DebugOr )
import Data.List ( intercalate )
import Data.Int ( Int32 )
-- | Symbols.
newtype ExprName = ExprName String deriving (Show, Eq)
newtype TypeName = TypeName String deriving (Show, Eq)
-- | Expression syntax for type checking.
data Expr =
ELitBool Bool
| ELitInt Int32
| EVar ExprName QType
| EAbs [(ExprName, CType)] Expr
| EApp Expr [Expr]
| EIf Expr Expr Expr
-- FIXME: Need a better technique for IDing intrinsics.
| EUnBuiltin String String (Expr -> DebugOr Expr)
| EBinBuiltin String String ((Expr, Expr) -> DebugOr Expr)
-- | A top-level expression.
data TlExpr =
TlDef String QType Expr |
TlFuncDef String [(String, CType)] CType Expr
deriving ( Show )
-- | A printer instance for expressions.
instance Show Expr where
show e = case e of
ELitBool b -> show b
ELitInt n -> show n
EVar (ExprName x) t -> x ++ "_{" ++ show t ++ "}"
EAbs bs e1 -> "\\(" ++ intercalate ", " (map show bs) ++ ") -> " ++ show e1
EApp e1 es -> "(" ++ show e1 ++ ")" ++ "(" ++ intercalate ", " (map show es) ++ ")"
EIf e1 e2 e3 -> "if " ++ show e1 ++ " then " ++ show e2 ++ " else " ++ show e3
EUnBuiltin _ x _ -> x
EBinBuiltin _ x _ -> x
-- | Proposition syntax
data Prop = PTrue deriving (Show)
-- | Quantified type level syntax.
data QType =
Quantified [TypeName] Prop CType
| Unquantified CType
deriving (Show)
-- | Ground type syntax.
data CType =
CTBool
| CTI32
| CTArrow [CType] CType
| CTVar TypeName
deriving (Show)
-- | Variable level substitution of variables.
substExpr :: ExprName -> QType -> Expr -> Expr -> Expr
substExpr x t v e =
let
subst_on = substExpr x t v -- subst on, wayne! subst on, garth!
in case e of
ELitBool _ -> e
ELitInt _ -> e
EVar y t' -> if (x == y) && areStructurallyEqualQType t t' then v else e
EAbs params body -> if any is_x_t params
then e
else EAbs params $ subst_on body
where
is_x_t (y,t') = (x == y) && (areStructurallyEqualQType t $ Unquantified t')
EApp e1 args -> EApp (subst_on e1) (map subst_on args)
EIf c e1 e2 -> EIf (subst_on c) (subst_on e1) (subst_on e2)
e1 -> e1
substExprs :: [((ExprName, QType), Expr)] -> Expr -> Expr
substExprs param_map = foldr (.) id subst_ons
where
subst_ons = map (uncurry $ uncurry substExpr) param_map
--------------------------------------------------------------------------------
-- Unification systems.
--
-- Systems for unifying types and terms.
-- Type equality on quantified types.
areStructurallyEqualQType :: QType -> QType -> Bool
areStructurallyEqualQType t1 t2 = case (t1,t2) of
(Unquantified t1', Unquantified t2') -> areStructurallyEqualCType t1' t2'
_ -> False
-- Type equality on unquantified types.
areStructurallyEqualCType :: CType -> CType -> Bool
areStructurallyEqualCType t1 t2 = case (t1,t2) of
(CTBool, CTBool) -> True
(CTI32, CTI32) -> True
(CTArrow src_t1 tgt_t1, CTArrow src_t2 tgt_t2) ->
let
same_lengths = length src_t1 == length src_t2
sources_eq = all (uncurry areStructurallyEqualCType) (zip src_t1 src_t2)
targets_eq = areStructurallyEqualCType tgt_t1 tgt_t2
in same_lengths && sources_eq && targets_eq
(CTVar (TypeName x1), CTVar (TypeName x2)) -> x1 == x2
_ -> False
-- Structural equality on expressions.
-- Note: This does not compute alpha equivalence.
areStructurallyEqualExpr :: Expr -> Expr -> Bool
areStructurallyEqualExpr x y = let
are_bindings_eq (ExprName z, t) (ExprName z', t') = z == z' && areStructurallyEqualCType t t'
are_list_bindings_eq bs bs' = (length bs == length bs') && all (uncurry are_bindings_eq) (zip bs bs')
in case (x,y) of
(ELitBool b, ELitBool b') -> b == b'
(ELitInt n, ELitInt n') -> n == n'
(EVar z t, EVar z' t') -> z == z' && areStructurallyEqualQType t t'
(EAbs bs e, EAbs bs' e') ->
are_list_bindings_eq bs bs' && areStructurallyEqualExpr e e'
(EApp e es, EApp e' es') ->
areStructurallyEqualExpr e e' && (length es == length es') &&
all (uncurry areStructurallyEqualExpr) (zip es es')
(EIf e1 e2 e3, EIf e1' e2' e3') ->
areStructurallyEqualExpr e1 e1' &&
areStructurallyEqualExpr e2 e2' &&
areStructurallyEqualExpr e3 e3'
_ -> False
|
m-lopez/jack
|
src/Expressions.hs
|
mit
| 4,774
| 0
| 15
| 1,200
| 1,527
| 798
| 729
| 103
| 9
|
module Skill where
import Data.List
import Control.Monad
import System.Random
import Probability
import Quality
data SkillGroup = Generic | Rhetoric | Athletic | Arcane | Academic | Economic | Natural | Clandestine | Religious | Performance
deriving (Eq, Show, Read, Bounded, Enum)
--data SkillDegree = Novice | Adept | Adequate | Expert | Master
--data SkillRestrictionStatistic = SkillRestriction Statistic
--data SkillRestrictionClass = SkillRestriction Profession
--data Skill
data SkillType = SkillType String SkillGroup --[SkillRestriction]
deriving (Eq, Show, Read)
tactics = SkillType "tactics" Generic
strategy = SkillType "strategy" Generic
lore = SkillType "lore" Generic
conversation = SkillType "conversation" Generic
athletics = SkillType "athletics" Athletic
brawl = SkillType "brawling" Athletic
climb = SkillType "climbing" Athletic
ride = SkillType "riding" Athletic
swim = SkillType "swimming" Athletic
bluff = SkillType "deception" Clandestine
crypto = SkillType "cryptography" Clandestine
disableTraps = SkillType "disabling traps" Clandestine
pickpocket = SkillType "pickpocketing" Clandestine
surveil = SkillType "surveillance" Clandestine
occultLore = SkillType "occult lore" Arcane
astrology = SkillType "astrology" Arcane
enchant = SkillType "enchanting" Arcane
alchemy = SkillType "alchemy" Arcane
botany = SkillType "botany" Academic
maths = SkillType "mathematics" Academic
theology = SkillType "theology" Religious
persuade = SkillType "persuasion" Rhetoric
generalSkills = [ strategy, athletics ]
athleticSkills = [ athletics, brawl, climb, ride ]
clandestineSkills = [ bluff, crypto, disableTraps, pickpocket, surveil ]
arcaneSkills = [ occultLore, astrology, enchant, alchemy ]
academicSkills = [ botany, maths ]
religiousSkills = [ theology ]
rhetoricSkills = [ persuade ]
allSkills = generalSkills ++ athleticSkills ++ clandestineSkills ++ arcaneSkills ++ academicSkills ++ religiousSkills ++ rhetoricSkills
--sneakySkills = [ deception, bluffing ]
data Skill = Skill SkillType Integer --Will | Athletics | Acrobatics | Gymnastics | Brawling | Swimming | Climbing | Shooting | Ride | Focus | Lore | Astrology | Botany | Mechanics | Logic | Mathematics | Philosophy | Theology | Law | FirstAid | Medicine | Bartering | Bluffing | Appraising | Pandering | Economics | Leatherworking | Blacksmithing | Armory | Brewing | Farming | Fletching | Energy | Alchemy | AnimalRapport | Spellcraft | Enchanting | Mindreading | Creativity | Aesthetics | Sculpture | Singing | Acting | Performance | Prestidigitation | Speech | Conversation | Rhetoric | Reading | Writing | Speaking | Storytelling | Observation | Persuasion | Provocation | Administration | Intimidation | Inspiration | Arbitrartion | Perception | Survival | Tactics | DisablingTraps | CreatureLore | Herbalism | Deception | Stealing | Surveillance | Sneaking | Cryptography | Spirit | Healing | Blessing | Prayer | OccultLore | Patience
deriving (Eq, Show, Read) --, Bounded, Enum)
--data Skill = Skill { kind :: SkillType, level :: SkillDegree }
--judgeSkill sk = judge sk
humanizeSkill (Skill (SkillType n g) v) = show (judge v) ++ " " ++ n -- (skType sk)
humanizedSkills :: [Skill] -> String
humanizedSkills sks = intercalate ", " (map humanizeSkill sks)
--guessSkillsFromJob job
-- | job == Thief = [ Sneaking, Surveillance, Stealing ]
-- | job == Archer = [ Shooting ]
-- | otherwise = []
rollSkill ofType = do
wVal <- 1 `d` 20
return (Skill ofType (head wVal))
genSkill = do
skType <- pickFrom allSkills -- randomIO :: IO SkillType
val <- 1 `d` 20
--sk <- rollSkill skType
--val <- 1 `d` 20
return (Skill skType (head val)) --(rollSkill skType $) --Skill skType val
--rollSkill sk = do
-- val <- 1 `d` 20
-- return Skill sk val
genSkills n = do
sks <- replicate n genSkill --map rollSkill baseSkills
return sks
--map rollSkill baseSkills --replicateM n genSkill --(randomIO :: IO Skill)
|
jweissman/heroes
|
src/Skill.hs
|
mit
| 4,290
| 2
| 11
| 994
| 690
| 378
| 312
| 55
| 1
|
module Syntax.Lexer where
import Text.Parsec.String
import qualified Text.Parsec.Token as T
import Control.Monad
import Text.Parsec.Language
import Text.Parsec.Combinator
import Text.Parsec.Prim
import Text.Parsec.Char
language
= emptyDef { T.commentStart = "/*"
, T.commentEnd = "*/"
, T.commentLine = "//"
, T.identStart = letter <|> char '_'
, T.identLetter = alphaNum <|> char '_'
, T.reservedNames = [ "if"
, "else"
, "for"
, "lambda"
, "func"
, "open"
, "return"
, "let"
, "true"
, "false"
, "ffi"
, "module"
, "var"
, "match"
]
, T.reservedOpNames = [ "+", "-", "*", "/"
, "=", "<", ">", "&&"
, "||", "!", "~", "λ"
, "÷", "×", "::"
, ">=", "<=", "$"
, "->" ]
, T.nestedComments = True
, T.caseSensitive = True
}
lexer = T.makeTokenParser language
identifier = T.identifier lexer
reserved = T.reserved lexer
operator = T.operator lexer
reservedOp = T.reservedOp lexer
charLiteral = T.charLiteral lexer
stringLiteral = T.stringLiteral lexer
natOrFloat = T.naturalOrFloat lexer
symbol = T.symbol lexer
lexeme = T.lexeme lexer
parens = T.parens lexer
braces = T.braces lexer
squares = T.brackets lexer
angles = T.angles lexer
semi = T.semi lexer
colon = T.colon lexer
comma = T.comma lexer
dot = T.dot lexer
semiSep = T.semiSep lexer
commaSep = T.commaSep lexer
semiSep1 = T.semiSep1 lexer
commaSep1 = T.commaSep1 lexer
contents :: Parser a -> Parser a
contents p = do
T.whiteSpace lexer
r <- p
eof
return r
|
demhydraz/ligand
|
src/Syntax/Lexer.hs
|
mit
| 2,239
| 0
| 8
| 1,051
| 509
| 285
| 224
| 64
| 1
|
{-# LANGUAGE TemplateHaskell #-}
module Control.Process.Show(
showP,
putStrLnP
) where
import Types
import Control.Process.Class
import Control.Monad.Trans
import Control.Monad.Trans.State
import Control.Lens
import Control.Monad
import Control.Monad.Trans.Free
import qualified Data.Map as M
makeLenses ''GameState
makeLenses ''Player
makeLenses ''Room
-- | Print a string with a prompt token prefix
putStrLnP = putStrLn . (token++)
where token = ">> "
-- process handling showing user commands
showP :: Process
showP (Pure _) = return ()
showP (Free End) = return ()
showP (Free (Move d x)) =
liftIO $ putStrLnP $ "You move " ++ show d
showP (Free (MoveTo e x)) =
liftIO $ putStrLnP $
"You move to the "
++ (showRelativeDirection . fromVector3) e
-- TODO: Make sure we can actually pick up the things we're picking up...
showP (Free (Pickup a x)) = case a of
Just e -> liftIO $ putStrLnP $ "You pick up a " ++ show e
_ -> do
loc <- use $ player.loc
hdg <- use $ player.holding
ents <- use $ room._2.entities -- stuff in the current room
case M.lookup loc ents of
Just x -> liftIO $ putStrLnP $
case hdg of
Just h -> "You drop your " ++ show h ++ " and pick up " ++ show x ++ "."
_ -> "You pick up " ++ show x ++ "."
Nothing -> liftIO $ putStrLnP "There is nothing to pick up."
showP (Free (DropItem x)) = do
itm <- use $ player.holding
liftIO $ putStrLnP $ case itm of
Just e -> "You drop your " ++ show e
Nothing -> "You have nothing to drop."
showP (Free (Jump a x)) = case a of
Just e -> liftIO $ putStrLnP $ "You jump on a " ++ show e
Nothing -> liftIO $ putStrLnP $ "You jump in the air."
showP (Free (Attack a x)) = case a of
Just e -> liftIO $ putStrLnP $ "You jump on a " ++ show e
Nothing -> liftIO $ putStrLnP $ "You jump in the air."
showP (Free (ShootD d x)) =
liftIO $ putStrLnP $ "You shoot " ++ show d
showP (Free (ShootE e x)) =
liftIO $ putStrLnP $ "You shoot a " ++ show e
showP (Free (ShootSelf x)) =
liftIO $ putStrLnP $ "You kill yourself."
showP (Free (Throw d x)) =
liftIO $ putStrLnP $ "You throw your item " ++ show d
showP (Free (Rope x)) = do
rps <- use $ player.ropes
if rps > 0
then liftIO $ putStrLnP "You toss a rope up."
else liftIO $ putStrLnP "You don't have any ropes!"
-- | TODO: Can place bomb "near the middle wall" right now...
showP (Free (Bomb a x)) = do
plr <- use player
let str = case a of
Just d -> case d of
U -> if Paste `elem` (plr^.items)
then "You place a bomb on the ceiling."
else "You find yourself unable to get the bomb "
++ "to stay on the ceiling..."
D -> "You place a bomb on the floor."
w -> "You place a bomb near the " ++ show w ++ " wall."
Nothing -> "You place a bomb at your feet."
liftIO $ putStrLn $ if plr^.bombs > 0
then str
else "You don't have any bombs!"
-- still need to validate if Gold Chest is even in the room.
showP (Free (OpenGoldChest x)) = do
hdg <- use $ player.holding
ents <- liftM M.elems $ use $ room._2.entities
unless (GroundItem' GoldChest `notElem` ents) $
liftIO $ putStrLnP $
case hdg of
Just (GroundItem' Key) ->
"You open the gold chest! Something shiny pops out."
_ ->
"It's locked! There may be a key laying around here somewhere..."
showP (Free (OpenChest x)) =
liftIO $ putStrLnP $ "You open a chest."
showP (Free (ExitLevel x)) = do
dbg <- use debug
roomType <- use $ room._2.rType
liftIO $ putStrLnP $
if (dbg || roomType == LevelExit)
then "You exit the level!"
else "You haven't found the exit yet."
showP (Free (DropDown x)) =
liftIO $ putStrLnP $ "You drop down to the next level."
showP (Free (Look d x)) = do
let show' U = "above you"
show' D = "below you"
show' x = "to your " ++ show x
liftIO $ putStrLnP $ "You look in the room " ++ show' d
showP (Free (Walls x)) = do
rm <- use $ room._2
liftIO $ putStrLnP $ "You see the following walls:\n"
liftIO $ putStrLn $ showWalls rm
showP (Free (ShowEntities x)) = do
rm <- use $ room._2
liftIO $ putStrLnP $ "You see the following things:\n"
liftIO $ putStrLn $ showEntitiesWithIds rm
showP (Free (ShowFull x)) = do
rm <- use $ room._2
liftIO $ putStrLnP $ "You see:\n"
liftIO $ putStrLn $ show rm
showP (Free (ShowMe x)) = do
plr <- use player
liftIO $ putStrLnP $ show plr
showP (Free (YOLO x)) = do
liftIO $ putStrLnP $ concat $
[ "You start flailing your arms in the air,",
" wailing \"YOLO\" at the top of your lungs.",
" You throw your remaining bombs and ropes around the room ",
" in a fit of joy. YOLO, right?"
]
|
5outh/textlunky
|
src/Control/Process/Show.hs
|
mit
| 4,939
| 0
| 21
| 1,429
| 1,557
| 767
| 790
| 123
| 17
|
{-# LANGUAGE PackageImports #-}
module GLFWHelpers ( withWindow
, GLFWEvent(..)
, highDPIScaleFactor
) where
import Control.Exception
import Control.Concurrent.STM
import qualified "GLFW-b" Graphics.UI.GLFW as GLFW -- Be explicit, we need the newer GLFW-b
-- Various utility functions related to GLFW
withWindow :: Int -> Int -> String -> TQueue GLFWEvent -> (GLFW.Window -> IO ()) -> IO ()
withWindow w h title tq =
bracket
( do
GLFW.setErrorCallback . Just $ errorCallback tq
True <- GLFW.init
GLFW.windowHint $ GLFW.WindowHint'Resizable True
-- GLFW.windowHint $ GLFW.WindowHint'Samples 4 -- 4x anti-aliasing
GLFW.windowHint $ GLFW.WindowHint'Decorated False
modernOpenGL
Just window <- GLFW.createWindow w h title Nothing Nothing
(x, _) <- GLFW.getWindowPos window
GLFW.setWindowPos window x 22 -- TODO: Height of OS menu bar, window would be under
-- it otherwise
registerCallbacks window tq
GLFW.makeContextCurrent $ Just window
return window
)
( \window -> do GLFW.destroyWindow window
GLFW.terminate
)
-- >2.1, no backwards compatibility on OS X
-- http://www.glfw.org/faq.html#how-do-i-create-an-opengl-30-context
modernOpenGL :: IO ()
modernOpenGL = do
GLFW.windowHint $ GLFW.WindowHint'OpenGLProfile GLFW.OpenGLProfile'Core
GLFW.windowHint $ GLFW.WindowHint'OpenGLForwardCompat True
GLFW.windowHint $ GLFW.WindowHint'ContextVersionMajor 3
GLFW.windowHint $ GLFW.WindowHint'ContextVersionMinor 3
highDPIScaleFactor :: GLFW.Window -> IO Double
highDPIScaleFactor win = do
(scWdh, _) <- GLFW.getWindowSize win
(pxWdh, _) <- GLFW.getFramebufferSize win
return $ fromIntegral pxWdh / fromIntegral scWdh
-- Convert GLFW callbacks into events delivered to a queue
data GLFWEvent = GLFWEventError
GLFW.Error
String
| GLFWEventKey
GLFW.Window
GLFW.Key
Int
GLFW.KeyState
GLFW.ModifierKeys
| GLFWEventWindowSize
GLFW.Window
Int
Int
| GLFWEventFramebufferSize
GLFW.Window
Int
Int
| GLFWEventMouseButton
GLFW.Window
GLFW.MouseButton
GLFW.MouseButtonState
GLFW.ModifierKeys
| GLFWEventCursorPos
GLFW.Window
Double
Double
| GLFWEventScroll
GLFW.Window
Double
Double
errorCallback :: TQueue GLFWEvent -> GLFW.Error -> String -> IO ()
errorCallback tq e s = atomically . writeTQueue tq $ GLFWEventError e s
keyCallback :: TQueue GLFWEvent
-> GLFW.Window
-> GLFW.Key
-> Int
-> GLFW.KeyState
-> GLFW.ModifierKeys -> IO ()
keyCallback tq win k sc ka mk = atomically . writeTQueue tq $ GLFWEventKey win k sc ka mk
windowSizeCallback :: TQueue GLFWEvent -> GLFW.Window -> Int -> Int -> IO ()
windowSizeCallback tq win w h = atomically . writeTQueue tq $ GLFWEventWindowSize win w h
framebufferSizeCallback :: TQueue GLFWEvent -> GLFW.Window -> Int -> Int -> IO ()
framebufferSizeCallback tq win w h =
atomically . writeTQueue tq $ GLFWEventFramebufferSize win w h
mouseButtonCallback :: TQueue GLFWEvent
-> GLFW.Window
-> GLFW.MouseButton
-> GLFW.MouseButtonState
-> GLFW.ModifierKeys
-> IO ()
mouseButtonCallback tq win bttn st mk =
atomically . writeTQueue tq $ GLFWEventMouseButton win bttn st mk
cursorPosCallback :: TQueue GLFWEvent -> GLFW.Window -> Double -> Double -> IO ()
cursorPosCallback tq win x y = atomically . writeTQueue tq $ GLFWEventCursorPos win x y
scrollCallback :: TQueue GLFWEvent -> GLFW.Window -> Double -> Double -> IO ()
scrollCallback tq win x y = atomically . writeTQueue tq $ GLFWEventScroll win x y
registerCallbacks :: GLFW.Window -> TQueue GLFWEvent -> IO ()
registerCallbacks window tq = do
GLFW.setKeyCallback window . Just $ keyCallback tq
GLFW.setWindowSizeCallback window . Just $ windowSizeCallback tq
GLFW.setFramebufferSizeCallback window . Just $ framebufferSizeCallback tq
GLFW.setMouseButtonCallback window . Just $ mouseButtonCallback tq
GLFW.setCursorPosCallback window . Just $ cursorPosCallback tq
GLFW.setScrollCallback window . Just $ scrollCallback tq
|
blitzcode/jacky
|
src/GLFWHelpers.hs
|
mit
| 5,003
| 0
| 13
| 1,721
| 1,135
| 548
| 587
| 99
| 1
|
module Test.MinStack where
import Test.QuickCheck
import Test.Hspec
import Questions.MinStack
import qualified Data.Stack as S
exStack = push 1 (push 7 (push 2 (push 6 (mkMinStack 9))))
testMinStack :: SpecWith ()
testMinStack =
describe "MinStack" $ do
describe "mkMinStack" $ do
it "should create a MinStack" $ do
(MinStack (S.mkStack 1) (S.mkStack 1) :: MinStack Int) `shouldBe` (mkMinStack 1)
describe "smin" $ do
it "should return the current min" $ do
smin exStack `shouldBe` (Just 1 :: Maybe Int)
describe "push and pop" $ do
it "should maintain min" $ do
smin (push 0 exStack) `shouldBe` (Just 0 :: Maybe Int)
smin (pop exStack) `shouldBe` (Just 2 :: Maybe Int)
|
Kiandr/CrackingCodingInterview
|
Haskell/src/chapter-3/Test/MinStack.hs
|
mit
| 739
| 0
| 19
| 178
| 282
| 140
| 142
| 19
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( makeFoundation
, waiApp
) where
import Data.IORef
import qualified Data.Traversable as T
import Data.Tuple
import Foundation
import Handler.About
import Handler.Root
import Random
import Settings
import WordList
import Yesod.Core
mkYesodDispatch "App" resourcesApp
makeFoundation :: AppSettings -> IO (Either String [Int]) -> IO App
makeFoundation settings refill = do
ref <- newIORef []
pure $ App settings $ \size -> do
ints <- atomicModifyIORef ref $ swap . splitAt size
if length ints >= size
then pure $ Right ints
else do
result <- refill
T.forM result $ \ints' -> do
let (first, rest) = splitAt size ints'
writeIORef ref rest
pure first
waiApp :: IO Application
waiApp = do
settings <- loadAppSettings
foundation <- makeFoundation settings $ requestInts
(appRandomApiKey settings)
(appRandomRequestSize settings)
keyRange
toWaiApp foundation
|
pbrisbin/passphrase.me
|
src/Application.hs
|
mit
| 1,172
| 0
| 21
| 335
| 303
| 151
| 152
| 38
| 2
|
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
import Options.Applicative
import RIO
import RIO.List as L
import RIO.Text as T
import Stackage.Database.Cron
import Stackage.Database.Github
readText :: ReadM T.Text
readText = T.pack <$> str
readLogLevel :: ReadM LogLevel
readLogLevel =
maybeReader $ \case
"debug" -> Just LevelDebug
"info" -> Just LevelInfo
"warn" -> Just LevelWarn
"error" -> Just LevelError
_ -> Nothing
readGithubRepo :: ReadM GithubRepo
readGithubRepo =
maybeReader $ \str' ->
case L.span (/= '/') str' of
(grAccount, '/':grName)
| not (L.null grName) -> Just GithubRepo {..}
_ -> Nothing
optsParser :: Parser StackageCronOptions
optsParser =
StackageCronOptions <$>
switch
(long "force-update" <> short 'f' <>
help
"Initiate a force update, where all snapshots will be updated regardless if \
\their yaml files from stackage-snapshots repo have been updated or not.") <*>
option
readText
(long "download-bucket" <> value haddockBucketName <> metavar "DOWNLOAD_BUCKET" <>
help
("S3 Bucket name where things like haddock and current hoogle files should \
\be downloaded from. Default is: " <>
T.unpack haddockBucketName)) <*>
option
readText
(long "upload-bucket" <> value haddockBucketName <> metavar "UPLOAD_BUCKET" <>
help
("S3 Bucket where hoogle db and snapshots.json file will be uploaded to. Default is: " <>
T.unpack haddockBucketName)) <*>
switch
(long "do-not-upload" <>
help "Stop from hoogle db and snapshots.json from being generated and uploaded") <*>
option
readLogLevel
(long "log-level" <> metavar "LOG_LEVEL" <> short 'l' <> value LevelInfo <>
help "Verbosity level (debug|info|warn|error). Default level is 'info'.") <*>
option
readGithubRepo
(long "snapshots-repo" <> metavar "SNAPSHOTS_REPO" <>
value (GithubRepo repoAccount repoName) <>
help
("Github repository with snapshot files. Default level is '" ++
repoAccount ++ "/" ++ repoName ++ "'.")) <*>
switch (long "report-progress" <> help "Report how many packages has been loaded.") <*>
switch
(long "cache-cabal-files" <>
help
("Improve performance by caching parsed cabal files" ++
" at expense of higher memory consumption"))
where
repoAccount = "commercialhaskell"
repoName = "stackage-snapshots"
main :: IO ()
main = do
hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering
opts <-
execParser $
info
(optsParser <*
abortOption ShowHelpText (long "help" <> short 'h' <> help "Display this message."))
(header "stackage-cron - Keep stackage.org up to date" <>
progDesc
"Uses github.com/commercialhaskell/stackage-snapshots repository as a source \
\for keeping stackage.org up to date. Amongst other things are: update of hoogle db\
\and it's upload to S3 bucket, use stackage-content for global-hints" <>
fullDesc)
stackageServerCron opts
|
fpco/stackage-server
|
app/stackage-server-cron.hs
|
mit
| 3,403
| 0
| 19
| 991
| 627
| 305
| 322
| 84
| 5
|
{-# LANGUAGE PatternGuards, ScopedTypeVariables #-}
{-
Find bindings within a let, and lists of statements
If you have n the same, error out
<TEST>
main = do a; a; a; a
main = do a; a; a; a; a; a -- ???
main = do a; a; a; a; a; a; a -- ???
main = do (do b; a; a; a); do (do c; a; a; a) -- ???
main = do a; a; a; b; a; a; a -- ???
main = do a; a; a; b; a; a
foo = a where {a = 1; b = 2; c = 3}; bar = a where {a = 1; b = 2; c = 3} -- ???
</TEST>
-}
module Hint.Duplicate(duplicateHint) where
import Hint.Type
import Control.Arrow
import Data.List hiding (find)
import qualified Data.Map as Map
duplicateHint :: CrossHint
duplicateHint ms =
dupes [y | Do _ y :: Exp S <- universeBi modu] ++
dupes [y | BDecls l y :: Binds S <- universeBi modu]
where modu = map snd ms
dupes ys =
[rawIdea
(if length xs >= 5 then Error else Warning)
"Reduce duplication" p1
(unlines $ map (prettyPrint . fmap (const p1)) xs)
("Combine with " ++ showSrcLoc p2) ""
| (p1,p2,xs) <- duplicateOrdered 3 $ map (map (toSrcLoc . ann &&& dropAnn)) ys]
---------------------------------------------------------------------
-- DUPLICATE FINDING
-- | The position to return if we match at this point, and the map of where to go next
-- If two runs have the same vals, always use the first pos you find
data Dupe pos val = Dupe pos (Map.Map val (Dupe pos val))
find :: Ord val => [val] -> Dupe pos val -> (pos, Int)
find (v:vs) (Dupe p mp) | Just d <- Map.lookup v mp = second (+1) $ find vs d
find _ (Dupe p mp) = (p, 0)
add :: Ord val => pos -> [val] -> Dupe pos val -> Dupe pos val
add pos [] d = d
add pos (v:vs) (Dupe p mp) = Dupe p $ Map.insertWith f v (add pos vs $ Dupe pos Map.empty) mp
where f new old = add pos vs old
duplicateOrdered :: Ord val => Int -> [[(SrcLoc,val)]] -> [(SrcLoc,SrcLoc,[val])]
duplicateOrdered threshold xs = concat $ concat $ snd $ mapAccumL f (Dupe nullSrcLoc Map.empty) xs
where
f d xs = second overlaps $ mapAccumL (g pos) d $ takeWhile ((>= threshold) . length) $ tails xs
where pos = Map.fromList $ zip (map fst xs) [0..]
g pos d xs = (d2, res)
where
res = [(p,pme,take mx vs) | i >= threshold
,let mx = maybe i (\x -> min i $ (pos Map.! pme) - x) $ Map.lookup p pos
,mx >= threshold]
vs = map snd xs
(p,i) = find vs d
pme = fst $ head xs
d2 = add pme vs d
overlaps (x@((_,_,n):_):xs) = x : overlaps (drop (length n - 1) xs)
overlaps (x:xs) = x : overlaps xs
overlaps [] = []
|
alphaHeavy/hlint
|
src/Hint/Duplicate.hs
|
gpl-2.0
| 2,653
| 0
| 21
| 774
| 969
| 503
| 466
| -1
| -1
|
module Handler.GruppeAnlegen where
import Import
import Handler.Gruppe (gruppeForm)
getGruppeAnlegenR :: VorlesungId -> Handler Html
getGruppeAnlegenR = postGruppeAnlegenR
postGruppeAnlegenR :: VorlesungId -> Handler Html
postGruppeAnlegenR vorlesungId = do
((result, formWidget), formEnctype) <- runFormPost $ gruppeForm vorlesungId Nothing
case result of
FormMissing -> return ()
FormFailure _ -> return ()
FormSuccess gruppe -> do
gruppeId <- runDB $ insert gruppe
_ <- setMessageI MsgGruppeAngelegt
redirect $ GruppeR gruppeId
defaultLayout $
formToWidget (GruppeAnlegenR vorlesungId) Nothing formEnctype formWidget
|
marcellussiegburg/autotool
|
yesod/Handler/GruppeAnlegen.hs
|
gpl-2.0
| 663
| 0
| 14
| 117
| 181
| 88
| 93
| 17
| 3
|
{-# LANGUAGE DeriveGeneric, OverloadedStrings, TypeFamilies #-}
module Kraken.Request.Depth
(
Depth(..)
) where
import qualified Kraken.Result.Depth as R
import Kraken.Request
import Kraken.Tools.ToURLEncoded
import GHC.Generics
data Depth = Depth
{ pair :: String
, count :: Maybe Integer } deriving Generic
instance ToURLEncoded Depth
instance Request Depth where
type Result Depth = R.Depth
urlPart _ = "Depth"
|
laugh-at-me/kraken-api
|
src/Kraken/Request/Depth.hs
|
gpl-3.0
| 450
| 0
| 9
| 91
| 103
| 62
| 41
| 15
| 0
|
module Solver.SComponent
(checkSComponentSat)
where
import Data.SBV
import Data.List (partition)
import qualified Data.Map as M
import Util
import PetriNet
import Solver
checkPrePostPlaces :: PetriNet -> SIMap Place -> SIMap Transition ->
SBool
checkPrePostPlaces net p' t' =
bAnd $ map checkPrePostPlace $ places net
where checkPrePostPlace p =
let incoming = map (positiveVal t') $ pre net p
outgoing = map (positiveVal t') $ post net p
pVal = positiveVal p' p
in pVal ==> bAnd incoming &&& bAnd outgoing
checkPrePostTransitions :: PetriNet -> SIMap Place -> SIMap Transition ->
SBool
checkPrePostTransitions net p' t' =
bAnd $ map checkPrePostTransition $ transitions net
where checkPrePostTransition t =
let incoming = mval p' $ pre net t
outgoing = mval p' $ post net t
tVal = positiveVal t' t
in tVal ==> sum incoming .== 1 &&& sum outgoing .== 1
checkSubsetTransitions :: FiringVector ->
SIMap Transition -> SIMap Transition -> SBool
checkSubsetTransitions x t' y =
let ySubset = map checkTransition $ elems x
in bAnd ySubset &&& sumVal y .< sum (mval t' (elems x))
where checkTransition t = positiveVal y t ==> positiveVal t' t
checkNotEmpty :: SIMap Transition -> SBool
checkNotEmpty y = (.>0) $ sumVal y
checkClosed :: PetriNet -> FiringVector -> SIMap Place ->
SIMap Transition -> SBool
checkClosed net x p' y =
bAnd $ map checkPlaceClosed $ places net
where checkPlaceClosed p =
let pVal = positiveVal p' p
postVal = bAnd $ map checkTransition
[(t,t') | t <- pre net p, t' <- post net p,
val x t > 0, val x t' > 0 ]
in pVal ==> postVal
checkTransition (t,t') = val y t .== val y t'
checkTokens :: PetriNet -> SIMap Place -> SBool
checkTokens net p' =
sum (map addPlace $ linitials net) .== 1
where addPlace (p,i) = literal i * val p' p
checkBinary :: SIMap Place -> SIMap Transition ->
SIMap Transition -> SBool
checkBinary p' t' y =
checkBins p' &&&
checkBins t' &&&
checkBins y
where checkBins xs = bAnd $ map (\x -> x .== 0 ||| x .== 1) $ vals xs
checkSizeLimit :: SIMap Place -> SIMap Transition -> Maybe (Int, Integer) -> SBool
checkSizeLimit _ _ Nothing = true
checkSizeLimit p' _ (Just (_, curSize)) = (.< literal curSize) $ sumVal p'
checkSComponent :: PetriNet -> FiringVector -> Maybe (Int, Integer) -> SIMap Place ->
SIMap Transition -> SIMap Transition -> SBool
checkSComponent net x sizeLimit p' t' y =
checkPrePostPlaces net p' t' &&&
checkPrePostTransitions net p' t' &&&
checkSubsetTransitions x t' y &&&
checkNotEmpty y &&&
checkSizeLimit p' t' sizeLimit &&&
checkClosed net x p' y &&&
checkTokens net p' &&&
checkBinary p' t' y
checkSComponentSat :: PetriNet -> FiringVector -> Maybe (Int, Integer) ->
ConstraintProblem Integer (Cut, Integer)
checkSComponentSat net x sizeLimit =
let fired = elems x
p' = makeVarMap $ places net
t' = makeVarMap $ transitions net
y = makeVarMapWith prime fired
in ("S-component constraints", "cut",
getNames p' ++ getNames t' ++ getNames y,
\fm -> checkSComponent net x sizeLimit (fmap fm p') (fmap fm t') (fmap fm y),
\fm -> cutFromAssignment net x (fmap fm p') (fmap fm t') (fmap fm y))
cutFromAssignment :: PetriNet -> FiringVector -> IMap Place ->
IMap Transition -> IMap Transition -> (Cut, Integer)
cutFromAssignment net x p' t' y =
let ts = filter (\t -> val x t > 0) $ elems $ M.filter (> 0) t'
(t1, t2) = partition (\t -> val y t > 0) ts
s1 = filter (\p -> val p' p > 0) $ mpost net t1
s2 = filter (\p -> val p' p > 0) $ mpost net t2
curSize = fromIntegral $ M.size $ M.filter (> 0) p'
in (constructCut net x [s1,s2], curSize)
|
cryptica/slapnet
|
src/Solver/SComponent.hs
|
gpl-3.0
| 4,273
| 0
| 16
| 1,404
| 1,503
| 740
| 763
| 90
| 1
|
size_list [] = 0
size_list (x:xs) = 1 + size_list xs
|
Gleuton/curso-haskell
|
size_list.hs
|
gpl-3.0
| 53
| 0
| 7
| 11
| 33
| 16
| 17
| 2
| 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.GroupsSettings.Groups.Update
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates an existing resource.
--
-- /See:/ <https://developers.google.com/google-apps/groups-settings/get_started Groups Settings API Reference> for @groupsSettings.groups.update@.
module Network.Google.Resource.GroupsSettings.Groups.Update
(
-- * REST Resource
GroupsUpdateResource
-- * Creating a Request
, groupsUpdate
, GroupsUpdate
-- * Request Lenses
, guPayload
, guGroupUniqueId
) where
import Network.Google.GroupsSettings.Types
import Network.Google.Prelude
-- | A resource alias for @groupsSettings.groups.update@ method which the
-- 'GroupsUpdate' request conforms to.
type GroupsUpdateResource =
"groups" :>
"v1" :>
"groups" :>
Capture "groupUniqueId" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Groups :> Put '[JSON] Groups
-- | Updates an existing resource.
--
-- /See:/ 'groupsUpdate' smart constructor.
data GroupsUpdate = GroupsUpdate'
{ _guPayload :: !Groups
, _guGroupUniqueId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'GroupsUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'guPayload'
--
-- * 'guGroupUniqueId'
groupsUpdate
:: Groups -- ^ 'guPayload'
-> Text -- ^ 'guGroupUniqueId'
-> GroupsUpdate
groupsUpdate pGuPayload_ pGuGroupUniqueId_ =
GroupsUpdate'
{ _guPayload = pGuPayload_
, _guGroupUniqueId = pGuGroupUniqueId_
}
-- | Multipart request metadata.
guPayload :: Lens' GroupsUpdate Groups
guPayload
= lens _guPayload (\ s a -> s{_guPayload = a})
-- | The resource ID
guGroupUniqueId :: Lens' GroupsUpdate Text
guGroupUniqueId
= lens _guGroupUniqueId
(\ s a -> s{_guGroupUniqueId = a})
instance GoogleRequest GroupsUpdate where
type Rs GroupsUpdate = Groups
type Scopes GroupsUpdate =
'["https://www.googleapis.com/auth/apps.groups.settings"]
requestClient GroupsUpdate'{..}
= go _guGroupUniqueId (Just AltJSON) _guPayload
groupsSettingsService
where go
= buildClient (Proxy :: Proxy GroupsUpdateResource)
mempty
|
rueshyna/gogol
|
gogol-groups-settings/gen/Network/Google/Resource/GroupsSettings/Groups/Update.hs
|
mpl-2.0
| 3,051
| 0
| 13
| 690
| 382
| 230
| 152
| 61
| 1
|
module IQManager (iqManager) where
import Prelude ()
import BasicPrelude
import Control.Concurrent.STM (
STM, TMVar, TVar, modifyTVar', newEmptyTMVar, newTVar, orElse,
readTVar, takeTMVar, tryPutTMVar, writeTVar
)
import Control.Concurrent.STM.Delay (newDelay, waitDelay)
import UnexceptionalIO.Trans (Unexceptional)
import qualified Data.Map.Strict as Map
import qualified Network.Protocol.XMPP as XMPP
import qualified Data.UUID as UUID
import qualified Data.UUID.V4 as UUID
import Util
type ResponseMap = Map.Map (Maybe Text) (TMVar XMPP.IQ)
iqSendTimeoutMicroseconds :: Int
iqSendTimeoutMicroseconds = 20 * 1000000
iqDefaultID :: (Unexceptional m) => XMPP.IQ -> m XMPP.IQ
iqDefaultID iq@XMPP.IQ { XMPP.iqID = Just _ } = return iq
iqDefaultID iq = do
uuid <- fromIO_ UUID.nextRandom
return $ iq {
XMPP.iqID = Just $ UUID.toText uuid
}
iqSenderUnexceptional :: (Unexceptional m) =>
(XMPP.IQ -> m ())
-> TVar ResponseMap
-> XMPP.IQ
-> m (STM (Maybe XMPP.IQ))
iqSenderUnexceptional sender responseMapVar iq = do
iqToSend <- iqDefaultID iq
timeout <- fromIO_ $ newDelay iqSendTimeoutMicroseconds
iqResponseVar <- atomicUIO newEmptyTMVar
atomicUIO $ modifyTVar' responseMapVar $
Map.insert (XMPP.iqID iqToSend) iqResponseVar
sender iqToSend
return (
(waitDelay timeout *> pure Nothing)
`orElse`
fmap Just (takeTMVar iqResponseVar)
)
iqReceiver :: (Unexceptional m) => TVar ResponseMap -> XMPP.IQ -> m ()
iqReceiver responseMapVar receivedIQ
| XMPP.iqType receivedIQ `elem` [XMPP.IQResult, XMPP.IQError] = do
maybeIqResponseVar <- atomicUIO $ do
responseMap <- readTVar responseMapVar
let (maybeIqResponseVar, responseMap') =
Map.updateLookupWithKey
(const $ const Nothing)
(XMPP.iqID receivedIQ) responseMap
writeTVar responseMapVar $! responseMap'
return maybeIqResponseVar
forM_ maybeIqResponseVar $ \iqResponseVar ->
atomicUIO $ tryPutTMVar iqResponseVar receivedIQ
| otherwise = return () -- TODO: log or otherwise signal error?
iqManager :: (Unexceptional m1, Unexceptional m2, Unexceptional m3) =>
(XMPP.IQ -> m2 ()) ->
m1 (XMPP.IQ -> m2 (STM (Maybe XMPP.IQ)), XMPP.IQ -> m3 ())
iqManager sender = do
responseMapVar <- atomicUIO $ newTVar Map.empty
return (
iqSenderUnexceptional sender responseMapVar,
iqReceiver responseMapVar
)
|
singpolyma/cheogram
|
IQManager.hs
|
agpl-3.0
| 2,364
| 103
| 12
| 415
| 771
| 429
| 342
| 60
| 1
|
module VReplace where
import CLaSH.Prelude
topEntity :: (Integer,Unsigned 4,Vec 8 (Unsigned 4)) -> Vec 8 (Vec 8 (Unsigned 4))
topEntity (i,j,as) = zipWith (replace as) (iterateI (+1) i) ((iterateI (subtract 1) j))
testInput :: Signal (Integer,Unsigned 4,Vec 8 (Unsigned 4))
testInput = stimuliGenerator $(v ([ (0,8,replicate d8 0)
]::[(Integer,Unsigned 4,Vec 8 (Unsigned 4))]))
|
christiaanb/clash-compiler
|
tests/shouldwork/Vector/VReplace.hs
|
bsd-2-clause
| 415
| 0
| 14
| 90
| 214
| 115
| 99
| -1
| -1
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QWidget.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:30
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QWidget (
QqWidget(..)
,activateWindow
,addActions
,autoFillBackground
,backgroundRole
,qbaseSize, baseSize
,QchildAt(..), qchildAt
,qchildrenRect, childrenRect
,childrenRegion
,clearMask
,contextMenuPolicy
,createWinId
,ensurePolished
,qWidgetFind
,focusPolicy
,focusProxy
,focusWidget
,foregroundRole
,qframeGeometry, frameGeometry
,qframeSize, frameSize
,grabKeyboard
,QgrabMouse(..)
,QgrabShortcut(..)
,hasMouseTracking
,insertAction
,insertActions
,internalWinId
,isActiveWindow
,isEnabledTo
,isEnabledToTLW
,isFullScreen
,isLeftToRight
,isMaximized
,isMinimized
,isModal
,isRightToLeft
,isTopLevel
,isVisibleTo
,isWindow
,isWindowModified
,qWidgetKeyboardGrabber
,lower
,mapFrom, qmapFrom
,mapFromGlobal, qmapFromGlobal
,mapTo, qmapTo
,mapToGlobal, qmapToGlobal
,maximumHeight
,minimumHeight
,qWidgetMouseGrabber
,nextInFocusChain
,qnormalGeometry, normalGeometry
,overrideWindowFlags
,overrideWindowState
,raise
,releaseKeyboard
,releaseMouse
,releaseShortcut
,qrepaint
,restoreGeometry
,saveGeometry
,Qscroll(..), qscroll
,QsetAttribute(..)
,setAutoFillBackground
,setBackgroundRole
,QsetBaseSize(..), qsetBaseSize
,setContextMenuPolicy
,setFixedHeight
,QsetFixedSize(..), qsetFixedSize
,setFixedWidth
,setFocusPolicy
,setFocusProxy
,setForegroundRole
,setLayout
,setMaximumHeight
,QsetMaximumSize(..), qsetMaximumSize
,setMaximumWidth
,setMinimumHeight
,QsetMinimumSize(..), qsetMinimumSize
,setMinimumWidth
,QsetParent(..)
,QsetShortcutAutoRepeat(..)
,QsetShortcutEnabled(..)
,setShown
,QsetSizeIncrement(..), qsetSizeIncrement
,QsetSizePolicy(..)
,qWidgetSetTabOrder
,setUpdatesEnabled
,setWindowFlags
,setWindowIcon
,setWindowIconText
,setWindowModified
,setWindowOpacity
,setWindowRole
,setWindowState
,showFullScreen
,showMaximized
,showMinimized
,showNormal
,qsizeIncrement, sizeIncrement
,sizePolicy
,stackUnder
,testAttribute
,topLevelWidget
,underMouse
,unsetLayoutDirection
,unsetLocale
,updateGeometry
,updatesEnabled
,visibleRegion
,winId
,windowFlags
,windowIcon
,windowIconText
,windowModality
,windowOpacity
,windowRole
,windowState
,windowTitle
,windowType
,qWidget_delete
,qWidget_deleteLater
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPalette
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QSizePolicy
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
instance QuserMethod (QWidget ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QWidget_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QWidget_userMethod" qtc_QWidget_userMethod :: Ptr (TQWidget a) -> CInt -> IO ()
instance QuserMethod (QWidgetSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QWidget_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QWidget ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QWidget_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QWidget_userMethodVariant" qtc_QWidget_userMethodVariant :: Ptr (TQWidget a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QWidgetSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QWidget_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqWidget x1 where
qWidget :: x1 -> IO (QWidget ())
instance QqWidget (()) where
qWidget ()
= withQWidgetResult $
qtc_QWidget
foreign import ccall "qtc_QWidget" qtc_QWidget :: IO (Ptr (TQWidget ()))
instance QqWidget ((QWidget t1)) where
qWidget (x1)
= withQWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget1 cobj_x1
foreign import ccall "qtc_QWidget1" qtc_QWidget1 :: Ptr (TQWidget t1) -> IO (Ptr (TQWidget ()))
instance QqWidget ((QWidget t1, WindowFlags)) where
qWidget (x1, x2)
= withQWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget2 cobj_x1 (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QWidget2" qtc_QWidget2 :: Ptr (TQWidget t1) -> CLong -> IO (Ptr (TQWidget ()))
instance QacceptDrops (QWidget a) (()) where
acceptDrops x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_acceptDrops cobj_x0
foreign import ccall "qtc_QWidget_acceptDrops" qtc_QWidget_acceptDrops :: Ptr (TQWidget a) -> IO CBool
instance QactionEvent (QWidget ()) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_actionEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_actionEvent_h" qtc_QWidget_actionEvent_h :: Ptr (TQWidget a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent (QWidgetSc a) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_actionEvent_h cobj_x0 cobj_x1
instance Qactions (QWidget a) (()) where
actions x0 ()
= withQListQActionResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_actions cobj_x0 arr
foreign import ccall "qtc_QWidget_actions" qtc_QWidget_actions :: Ptr (TQWidget a) -> Ptr (Ptr (TQAction ())) -> IO CInt
activateWindow :: QWidget a -> (()) -> IO ()
activateWindow x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_activateWindow cobj_x0
foreign import ccall "qtc_QWidget_activateWindow" qtc_QWidget_activateWindow :: Ptr (TQWidget a) -> IO ()
instance QaddAction (QWidget ()) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_addAction cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_addAction" qtc_QWidget_addAction :: Ptr (TQWidget a) -> Ptr (TQAction t1) -> IO ()
instance QaddAction (QWidgetSc a) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_addAction cobj_x0 cobj_x1
addActions :: QWidget a -> (([QAction t1])) -> IO ()
addActions x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withQListObject x1 $ \cqlistlen_x1 cqlistobj_x1 ->
qtc_QWidget_addActions cobj_x0 cqlistlen_x1 cqlistobj_x1
foreign import ccall "qtc_QWidget_addActions" qtc_QWidget_addActions :: Ptr (TQWidget a) -> CInt -> Ptr (Ptr (TQAction t1)) -> IO ()
instance QadjustSize (QWidget a) (()) where
adjustSize x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_adjustSize cobj_x0
foreign import ccall "qtc_QWidget_adjustSize" qtc_QWidget_adjustSize :: Ptr (TQWidget a) -> IO ()
autoFillBackground :: QWidget a -> (()) -> IO (Bool)
autoFillBackground x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_autoFillBackground cobj_x0
foreign import ccall "qtc_QWidget_autoFillBackground" qtc_QWidget_autoFillBackground :: Ptr (TQWidget a) -> IO CBool
backgroundRole :: QWidget a -> (()) -> IO (ColorRole)
backgroundRole x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_backgroundRole cobj_x0
foreign import ccall "qtc_QWidget_backgroundRole" qtc_QWidget_backgroundRole :: Ptr (TQWidget a) -> IO CLong
qbaseSize :: QWidget a -> (()) -> IO (QSize ())
qbaseSize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_baseSize cobj_x0
foreign import ccall "qtc_QWidget_baseSize" qtc_QWidget_baseSize :: Ptr (TQWidget a) -> IO (Ptr (TQSize ()))
baseSize :: QWidget a -> (()) -> IO (Size)
baseSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_baseSize_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QWidget_baseSize_qth" qtc_QWidget_baseSize_qth :: Ptr (TQWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QchangeEvent (QWidget ()) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_changeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_changeEvent_h" qtc_QWidget_changeEvent_h :: Ptr (TQWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent (QWidgetSc a) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_changeEvent_h cobj_x0 cobj_x1
class QchildAt x1 where
childAt :: QWidget a -> x1 -> IO (QWidget ())
instance QchildAt ((Int, Int)) where
childAt x0 (x1, x2)
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_childAt1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QWidget_childAt1" qtc_QWidget_childAt1 :: Ptr (TQWidget a) -> CInt -> CInt -> IO (Ptr (TQWidget ()))
instance QchildAt ((Point)) where
childAt x0 (x1)
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QWidget_childAt_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QWidget_childAt_qth" qtc_QWidget_childAt_qth :: Ptr (TQWidget a) -> CInt -> CInt -> IO (Ptr (TQWidget ()))
qchildAt :: QWidget a -> ((QPoint t1)) -> IO (QWidget ())
qchildAt x0 (x1)
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_childAt cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_childAt" qtc_QWidget_childAt :: Ptr (TQWidget a) -> Ptr (TQPoint t1) -> IO (Ptr (TQWidget ()))
qchildrenRect :: QWidget a -> (()) -> IO (QRect ())
qchildrenRect x0 ()
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_childrenRect cobj_x0
foreign import ccall "qtc_QWidget_childrenRect" qtc_QWidget_childrenRect :: Ptr (TQWidget a) -> IO (Ptr (TQRect ()))
childrenRect :: QWidget a -> (()) -> IO (Rect)
childrenRect x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_childrenRect_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QWidget_childrenRect_qth" qtc_QWidget_childrenRect_qth :: Ptr (TQWidget a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
childrenRegion :: QWidget a -> (()) -> IO (QRegion ())
childrenRegion x0 ()
= withQRegionResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_childrenRegion cobj_x0
foreign import ccall "qtc_QWidget_childrenRegion" qtc_QWidget_childrenRegion :: Ptr (TQWidget a) -> IO (Ptr (TQRegion ()))
instance QclearFocus (QWidget a) (()) where
clearFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_clearFocus cobj_x0
foreign import ccall "qtc_QWidget_clearFocus" qtc_QWidget_clearFocus :: Ptr (TQWidget a) -> IO ()
clearMask :: QWidget a -> (()) -> IO ()
clearMask x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_clearMask cobj_x0
foreign import ccall "qtc_QWidget_clearMask" qtc_QWidget_clearMask :: Ptr (TQWidget a) -> IO ()
instance Qclose (QWidget a) (()) (IO (Bool)) where
close x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_close cobj_x0
foreign import ccall "qtc_QWidget_close" qtc_QWidget_close :: Ptr (TQWidget a) -> IO CBool
instance QcloseEvent (QWidget ()) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_closeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_closeEvent_h" qtc_QWidget_closeEvent_h :: Ptr (TQWidget a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent (QWidgetSc a) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_closeEvent_h cobj_x0 cobj_x1
instance QqcontentsRect (QWidget a) (()) where
qcontentsRect x0 ()
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_contentsRect cobj_x0
foreign import ccall "qtc_QWidget_contentsRect" qtc_QWidget_contentsRect :: Ptr (TQWidget a) -> IO (Ptr (TQRect ()))
instance QcontentsRect (QWidget a) (()) where
contentsRect x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_contentsRect_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QWidget_contentsRect_qth" qtc_QWidget_contentsRect_qth :: Ptr (TQWidget a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance QcontextMenuEvent (QWidget ()) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_contextMenuEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_contextMenuEvent_h" qtc_QWidget_contextMenuEvent_h :: Ptr (TQWidget a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent (QWidgetSc a) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_contextMenuEvent_h cobj_x0 cobj_x1
contextMenuPolicy :: QWidget a -> (()) -> IO (ContextMenuPolicy)
contextMenuPolicy x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_contextMenuPolicy cobj_x0
foreign import ccall "qtc_QWidget_contextMenuPolicy" qtc_QWidget_contextMenuPolicy :: Ptr (TQWidget a) -> IO CLong
instance Qcreate (QWidget ()) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_create cobj_x0
foreign import ccall "qtc_QWidget_create" qtc_QWidget_create :: Ptr (TQWidget a) -> IO ()
instance Qcreate (QWidgetSc a) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_create cobj_x0
instance Qcreate (QWidget ()) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_create1 cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_create1" qtc_QWidget_create1 :: Ptr (TQWidget a) -> Ptr (TQVoid t1) -> IO ()
instance Qcreate (QWidgetSc a) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_create1 cobj_x0 cobj_x1
instance Qcreate (QWidget ()) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_create2 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QWidget_create2" qtc_QWidget_create2 :: Ptr (TQWidget a) -> Ptr (TQVoid t1) -> CBool -> IO ()
instance Qcreate (QWidgetSc a) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_create2 cobj_x0 cobj_x1 (toCBool x2)
instance Qcreate (QWidget ()) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
foreign import ccall "qtc_QWidget_create3" qtc_QWidget_create3 :: Ptr (TQWidget a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO ()
instance Qcreate (QWidgetSc a) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
createWinId :: QWidget a -> (()) -> IO ()
createWinId x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_createWinId cobj_x0
foreign import ccall "qtc_QWidget_createWinId" qtc_QWidget_createWinId :: Ptr (TQWidget a) -> IO ()
instance Qcursor (QWidget a) (()) where
cursor x0 ()
= withQCursorResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_cursor cobj_x0
foreign import ccall "qtc_QWidget_cursor" qtc_QWidget_cursor :: Ptr (TQWidget a) -> IO (Ptr (TQCursor ()))
instance Qdestroy (QWidget ()) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_destroy cobj_x0
foreign import ccall "qtc_QWidget_destroy" qtc_QWidget_destroy :: Ptr (TQWidget a) -> IO ()
instance Qdestroy (QWidgetSc a) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_destroy cobj_x0
instance Qdestroy (QWidget ()) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_destroy1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QWidget_destroy1" qtc_QWidget_destroy1 :: Ptr (TQWidget a) -> CBool -> IO ()
instance Qdestroy (QWidgetSc a) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_destroy1 cobj_x0 (toCBool x1)
instance Qdestroy (QWidget ()) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
foreign import ccall "qtc_QWidget_destroy2" qtc_QWidget_destroy2 :: Ptr (TQWidget a) -> CBool -> CBool -> IO ()
instance Qdestroy (QWidgetSc a) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
instance QdevType (QWidget ()) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_devType_h cobj_x0
foreign import ccall "qtc_QWidget_devType_h" qtc_QWidget_devType_h :: Ptr (TQWidget a) -> IO CInt
instance QdevType (QWidgetSc a) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_devType_h cobj_x0
instance QdragEnterEvent (QWidget ()) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_dragEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_dragEnterEvent_h" qtc_QWidget_dragEnterEvent_h :: Ptr (TQWidget a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent (QWidgetSc a) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_dragEnterEvent_h cobj_x0 cobj_x1
instance QdragLeaveEvent (QWidget ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_dragLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_dragLeaveEvent_h" qtc_QWidget_dragLeaveEvent_h :: Ptr (TQWidget a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent (QWidgetSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_dragLeaveEvent_h cobj_x0 cobj_x1
instance QdragMoveEvent (QWidget ()) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_dragMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_dragMoveEvent_h" qtc_QWidget_dragMoveEvent_h :: Ptr (TQWidget a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent (QWidgetSc a) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_dragMoveEvent_h cobj_x0 cobj_x1
instance QdropEvent (QWidget ()) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_dropEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_dropEvent_h" qtc_QWidget_dropEvent_h :: Ptr (TQWidget a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent (QWidgetSc a) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_dropEvent_h cobj_x0 cobj_x1
instance QenabledChange (QWidget ()) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_enabledChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QWidget_enabledChange" qtc_QWidget_enabledChange :: Ptr (TQWidget a) -> CBool -> IO ()
instance QenabledChange (QWidgetSc a) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_enabledChange cobj_x0 (toCBool x1)
ensurePolished :: QWidget a -> (()) -> IO ()
ensurePolished x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_ensurePolished cobj_x0
foreign import ccall "qtc_QWidget_ensurePolished" qtc_QWidget_ensurePolished :: Ptr (TQWidget a) -> IO ()
instance QenterEvent (QWidget ()) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_enterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_enterEvent_h" qtc_QWidget_enterEvent_h :: Ptr (TQWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent (QWidgetSc a) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_enterEvent_h cobj_x0 cobj_x1
instance Qevent (QWidget ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_event_h" qtc_QWidget_event_h :: Ptr (TQWidget a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QWidgetSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_event_h cobj_x0 cobj_x1
qWidgetFind :: ((QVoid t1)) -> IO (QWidget ())
qWidgetFind (x1)
= withQWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_find cobj_x1
foreign import ccall "qtc_QWidget_find" qtc_QWidget_find :: Ptr (TQVoid t1) -> IO (Ptr (TQWidget ()))
instance QfocusInEvent (QWidget ()) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_focusInEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_focusInEvent_h" qtc_QWidget_focusInEvent_h :: Ptr (TQWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent (QWidgetSc a) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_focusInEvent_h cobj_x0 cobj_x1
instance QfocusNextChild (QWidget ()) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_focusNextChild cobj_x0
foreign import ccall "qtc_QWidget_focusNextChild" qtc_QWidget_focusNextChild :: Ptr (TQWidget a) -> IO CBool
instance QfocusNextChild (QWidgetSc a) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_focusNextChild cobj_x0
instance QfocusNextPrevChild (QWidget ()) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_focusNextPrevChild cobj_x0 (toCBool x1)
foreign import ccall "qtc_QWidget_focusNextPrevChild" qtc_QWidget_focusNextPrevChild :: Ptr (TQWidget a) -> CBool -> IO CBool
instance QfocusNextPrevChild (QWidgetSc a) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_focusNextPrevChild cobj_x0 (toCBool x1)
instance QfocusOutEvent (QWidget ()) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_focusOutEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_focusOutEvent_h" qtc_QWidget_focusOutEvent_h :: Ptr (TQWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent (QWidgetSc a) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_focusOutEvent_h cobj_x0 cobj_x1
focusPolicy :: QWidget a -> (()) -> IO (FocusPolicy)
focusPolicy x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_focusPolicy cobj_x0
foreign import ccall "qtc_QWidget_focusPolicy" qtc_QWidget_focusPolicy :: Ptr (TQWidget a) -> IO CLong
instance QfocusPreviousChild (QWidget ()) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_focusPreviousChild cobj_x0
foreign import ccall "qtc_QWidget_focusPreviousChild" qtc_QWidget_focusPreviousChild :: Ptr (TQWidget a) -> IO CBool
instance QfocusPreviousChild (QWidgetSc a) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_focusPreviousChild cobj_x0
focusProxy :: QWidget a -> (()) -> IO (QWidget ())
focusProxy x0 ()
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_focusProxy cobj_x0
foreign import ccall "qtc_QWidget_focusProxy" qtc_QWidget_focusProxy :: Ptr (TQWidget a) -> IO (Ptr (TQWidget ()))
focusWidget :: QWidget a -> (()) -> IO (QWidget ())
focusWidget x0 ()
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_focusWidget cobj_x0
foreign import ccall "qtc_QWidget_focusWidget" qtc_QWidget_focusWidget :: Ptr (TQWidget a) -> IO (Ptr (TQWidget ()))
instance Qfont (QWidget a) (()) where
font x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_font cobj_x0
foreign import ccall "qtc_QWidget_font" qtc_QWidget_font :: Ptr (TQWidget a) -> IO (Ptr (TQFont ()))
instance QfontChange (QWidget ()) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_fontChange cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_fontChange" qtc_QWidget_fontChange :: Ptr (TQWidget a) -> Ptr (TQFont t1) -> IO ()
instance QfontChange (QWidgetSc a) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_fontChange cobj_x0 cobj_x1
instance QfontInfo (QWidget a) (()) where
fontInfo x0 ()
= withQFontInfoResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_fontInfo cobj_x0
foreign import ccall "qtc_QWidget_fontInfo" qtc_QWidget_fontInfo :: Ptr (TQWidget a) -> IO (Ptr (TQFontInfo ()))
instance QfontMetrics (QWidget a) (()) where
fontMetrics x0 ()
= withQFontMetricsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_fontMetrics cobj_x0
foreign import ccall "qtc_QWidget_fontMetrics" qtc_QWidget_fontMetrics :: Ptr (TQWidget a) -> IO (Ptr (TQFontMetrics ()))
foregroundRole :: QWidget a -> (()) -> IO (ColorRole)
foregroundRole x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_foregroundRole cobj_x0
foreign import ccall "qtc_QWidget_foregroundRole" qtc_QWidget_foregroundRole :: Ptr (TQWidget a) -> IO CLong
qframeGeometry :: QWidget a -> (()) -> IO (QRect ())
qframeGeometry x0 ()
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_frameGeometry cobj_x0
foreign import ccall "qtc_QWidget_frameGeometry" qtc_QWidget_frameGeometry :: Ptr (TQWidget a) -> IO (Ptr (TQRect ()))
frameGeometry :: QWidget a -> (()) -> IO (Rect)
frameGeometry x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_frameGeometry_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QWidget_frameGeometry_qth" qtc_QWidget_frameGeometry_qth :: Ptr (TQWidget a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
qframeSize :: QWidget a -> (()) -> IO (QSize ())
qframeSize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_frameSize cobj_x0
foreign import ccall "qtc_QWidget_frameSize" qtc_QWidget_frameSize :: Ptr (TQWidget a) -> IO (Ptr (TQSize ()))
frameSize :: QWidget a -> (()) -> IO (Size)
frameSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_frameSize_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QWidget_frameSize_qth" qtc_QWidget_frameSize_qth :: Ptr (TQWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance Qqgeometry (QWidget a) (()) where
qgeometry x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_geometry cobj_x0
foreign import ccall "qtc_QWidget_geometry" qtc_QWidget_geometry :: Ptr (TQWidget a) -> IO (Ptr (TQRect ()))
instance Qgeometry (QWidget a) (()) where
geometry x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_geometry_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QWidget_geometry_qth" qtc_QWidget_geometry_qth :: Ptr (TQWidget a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
grabKeyboard :: QWidget a -> (()) -> IO ()
grabKeyboard x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_grabKeyboard cobj_x0
foreign import ccall "qtc_QWidget_grabKeyboard" qtc_QWidget_grabKeyboard :: Ptr (TQWidget a) -> IO ()
class QgrabMouse x1 where
grabMouse :: QWidget a -> x1 -> IO ()
instance QgrabMouse (()) where
grabMouse x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_grabMouse cobj_x0
foreign import ccall "qtc_QWidget_grabMouse" qtc_QWidget_grabMouse :: Ptr (TQWidget a) -> IO ()
instance QgrabMouse ((QCursor t1)) where
grabMouse x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_grabMouse1 cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_grabMouse1" qtc_QWidget_grabMouse1 :: Ptr (TQWidget a) -> Ptr (TQCursor t1) -> IO ()
class QgrabShortcut x1 where
grabShortcut :: QWidget a -> x1 -> IO (Int)
instance QgrabShortcut ((QKeySequence t1)) where
grabShortcut x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_grabShortcut cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_grabShortcut" qtc_QWidget_grabShortcut :: Ptr (TQWidget a) -> Ptr (TQKeySequence t1) -> IO CInt
instance QgrabShortcut ((QKeySequence t1, ShortcutContext)) where
grabShortcut x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_grabShortcut1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QWidget_grabShortcut1" qtc_QWidget_grabShortcut1 :: Ptr (TQWidget a) -> Ptr (TQKeySequence t1) -> CLong -> IO CInt
instance QhasFocus (QWidget a) (()) where
hasFocus x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_hasFocus cobj_x0
foreign import ccall "qtc_QWidget_hasFocus" qtc_QWidget_hasFocus :: Ptr (TQWidget a) -> IO CBool
hasMouseTracking :: QWidget a -> (()) -> IO (Bool)
hasMouseTracking x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_hasMouseTracking cobj_x0
foreign import ccall "qtc_QWidget_hasMouseTracking" qtc_QWidget_hasMouseTracking :: Ptr (TQWidget a) -> IO CBool
instance Qqheight (QWidget a) (()) (IO (Int)) where
qheight x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_height cobj_x0
foreign import ccall "qtc_QWidget_height" qtc_QWidget_height :: Ptr (TQWidget a) -> IO CInt
instance QheightForWidth (QWidget ()) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_heightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QWidget_heightForWidth_h" qtc_QWidget_heightForWidth_h :: Ptr (TQWidget a) -> CInt -> IO CInt
instance QheightForWidth (QWidgetSc a) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_heightForWidth_h cobj_x0 (toCInt x1)
instance Qhide (QWidget a) (()) where
hide x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_hide cobj_x0
foreign import ccall "qtc_QWidget_hide" qtc_QWidget_hide :: Ptr (TQWidget a) -> IO ()
instance QhideEvent (QWidget ()) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_hideEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_hideEvent_h" qtc_QWidget_hideEvent_h :: Ptr (TQWidget a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent (QWidgetSc a) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_hideEvent_h cobj_x0 cobj_x1
instance QinputContext (QWidget a) (()) where
inputContext x0 ()
= withQInputContextResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_inputContext cobj_x0
foreign import ccall "qtc_QWidget_inputContext" qtc_QWidget_inputContext :: Ptr (TQWidget a) -> IO (Ptr (TQInputContext ()))
instance QinputMethodEvent (QWidget ()) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_inputMethodEvent" qtc_QWidget_inputMethodEvent :: Ptr (TQWidget a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent (QWidgetSc a) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_inputMethodEvent cobj_x0 cobj_x1
instance QinputMethodQuery (QWidget ()) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QWidget_inputMethodQuery_h" qtc_QWidget_inputMethodQuery_h :: Ptr (TQWidget a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery (QWidgetSc a) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
insertAction :: QWidget a -> ((QAction t1, QAction t2)) -> IO ()
insertAction x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QWidget_insertAction cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QWidget_insertAction" qtc_QWidget_insertAction :: Ptr (TQWidget a) -> Ptr (TQAction t1) -> Ptr (TQAction t2) -> IO ()
insertActions :: QWidget a -> ((QAction t1, [QAction t2])) -> IO ()
insertActions x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withQListObject x2 $ \cqlistlen_x2 cqlistobj_x2 ->
qtc_QWidget_insertActions cobj_x0 cobj_x1 cqlistlen_x2 cqlistobj_x2
foreign import ccall "qtc_QWidget_insertActions" qtc_QWidget_insertActions :: Ptr (TQWidget a) -> Ptr (TQAction t1) -> CInt -> Ptr (Ptr (TQAction t2)) -> IO ()
internalWinId :: QWidget a -> (()) -> IO (QVoid ())
internalWinId x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_internalWinId cobj_x0
foreign import ccall "qtc_QWidget_internalWinId" qtc_QWidget_internalWinId :: Ptr (TQWidget a) -> IO (Ptr (TQVoid ()))
isActiveWindow :: QWidget a -> (()) -> IO (Bool)
isActiveWindow x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_isActiveWindow cobj_x0
foreign import ccall "qtc_QWidget_isActiveWindow" qtc_QWidget_isActiveWindow :: Ptr (TQWidget a) -> IO CBool
instance QisAncestorOf (QWidget a) ((QWidget t1)) where
isAncestorOf x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_isAncestorOf cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_isAncestorOf" qtc_QWidget_isAncestorOf :: Ptr (TQWidget a) -> Ptr (TQWidget t1) -> IO CBool
instance QisEnabled (QWidget a) (()) where
isEnabled x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_isEnabled cobj_x0
foreign import ccall "qtc_QWidget_isEnabled" qtc_QWidget_isEnabled :: Ptr (TQWidget a) -> IO CBool
isEnabledTo :: QWidget a -> ((QWidget t1)) -> IO (Bool)
isEnabledTo x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_isEnabledTo cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_isEnabledTo" qtc_QWidget_isEnabledTo :: Ptr (TQWidget a) -> Ptr (TQWidget t1) -> IO CBool
isEnabledToTLW :: QWidget a -> (()) -> IO (Bool)
isEnabledToTLW x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_isEnabledToTLW cobj_x0
foreign import ccall "qtc_QWidget_isEnabledToTLW" qtc_QWidget_isEnabledToTLW :: Ptr (TQWidget a) -> IO CBool
isFullScreen :: QWidget a -> (()) -> IO (Bool)
isFullScreen x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_isFullScreen cobj_x0
foreign import ccall "qtc_QWidget_isFullScreen" qtc_QWidget_isFullScreen :: Ptr (TQWidget a) -> IO CBool
instance QisHidden (QWidget a) (()) where
isHidden x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_isHidden cobj_x0
foreign import ccall "qtc_QWidget_isHidden" qtc_QWidget_isHidden :: Ptr (TQWidget a) -> IO CBool
isLeftToRight :: QWidget a -> (()) -> IO (Bool)
isLeftToRight x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_isLeftToRight cobj_x0
foreign import ccall "qtc_QWidget_isLeftToRight" qtc_QWidget_isLeftToRight :: Ptr (TQWidget a) -> IO CBool
isMaximized :: QWidget a -> (()) -> IO (Bool)
isMaximized x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_isMaximized cobj_x0
foreign import ccall "qtc_QWidget_isMaximized" qtc_QWidget_isMaximized :: Ptr (TQWidget a) -> IO CBool
isMinimized :: QWidget a -> (()) -> IO (Bool)
isMinimized x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_isMinimized cobj_x0
foreign import ccall "qtc_QWidget_isMinimized" qtc_QWidget_isMinimized :: Ptr (TQWidget a) -> IO CBool
isModal :: QWidget a -> (()) -> IO (Bool)
isModal x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_isModal cobj_x0
foreign import ccall "qtc_QWidget_isModal" qtc_QWidget_isModal :: Ptr (TQWidget a) -> IO CBool
isRightToLeft :: QWidget a -> (()) -> IO (Bool)
isRightToLeft x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_isRightToLeft cobj_x0
foreign import ccall "qtc_QWidget_isRightToLeft" qtc_QWidget_isRightToLeft :: Ptr (TQWidget a) -> IO CBool
isTopLevel :: QWidget a -> (()) -> IO (Bool)
isTopLevel x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_isTopLevel cobj_x0
foreign import ccall "qtc_QWidget_isTopLevel" qtc_QWidget_isTopLevel :: Ptr (TQWidget a) -> IO CBool
instance QisVisible (QWidget a) (()) where
isVisible x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_isVisible cobj_x0
foreign import ccall "qtc_QWidget_isVisible" qtc_QWidget_isVisible :: Ptr (TQWidget a) -> IO CBool
isVisibleTo :: QWidget a -> ((QWidget t1)) -> IO (Bool)
isVisibleTo x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_isVisibleTo cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_isVisibleTo" qtc_QWidget_isVisibleTo :: Ptr (TQWidget a) -> Ptr (TQWidget t1) -> IO CBool
isWindow :: QWidget a -> (()) -> IO (Bool)
isWindow x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_isWindow cobj_x0
foreign import ccall "qtc_QWidget_isWindow" qtc_QWidget_isWindow :: Ptr (TQWidget a) -> IO CBool
isWindowModified :: QWidget a -> (()) -> IO (Bool)
isWindowModified x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_isWindowModified cobj_x0
foreign import ccall "qtc_QWidget_isWindowModified" qtc_QWidget_isWindowModified :: Ptr (TQWidget a) -> IO CBool
instance QkeyPressEvent (QWidget ()) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_keyPressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_keyPressEvent_h" qtc_QWidget_keyPressEvent_h :: Ptr (TQWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent (QWidgetSc a) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_keyPressEvent_h cobj_x0 cobj_x1
instance QkeyReleaseEvent (QWidget ()) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_keyReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_keyReleaseEvent_h" qtc_QWidget_keyReleaseEvent_h :: Ptr (TQWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent (QWidgetSc a) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_keyReleaseEvent_h cobj_x0 cobj_x1
qWidgetKeyboardGrabber :: (()) -> IO (QWidget ())
qWidgetKeyboardGrabber ()
= withQWidgetResult $
qtc_QWidget_keyboardGrabber
foreign import ccall "qtc_QWidget_keyboardGrabber" qtc_QWidget_keyboardGrabber :: IO (Ptr (TQWidget ()))
instance QlanguageChange (QWidget ()) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_languageChange cobj_x0
foreign import ccall "qtc_QWidget_languageChange" qtc_QWidget_languageChange :: Ptr (TQWidget a) -> IO ()
instance QlanguageChange (QWidgetSc a) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_languageChange cobj_x0
instance Qlayout (QWidget a) (()) (IO (QLayout ())) where
layout x0 ()
= withQLayoutResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_layout cobj_x0
foreign import ccall "qtc_QWidget_layout" qtc_QWidget_layout :: Ptr (TQWidget a) -> IO (Ptr (TQLayout ()))
instance QlayoutDirection (QWidget a) (()) where
layoutDirection x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_layoutDirection cobj_x0
foreign import ccall "qtc_QWidget_layoutDirection" qtc_QWidget_layoutDirection :: Ptr (TQWidget a) -> IO CLong
instance QleaveEvent (QWidget ()) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_leaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_leaveEvent_h" qtc_QWidget_leaveEvent_h :: Ptr (TQWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent (QWidgetSc a) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_leaveEvent_h cobj_x0 cobj_x1
instance Qlocale (QWidget a) (()) where
locale x0 ()
= withQLocaleResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_locale cobj_x0
foreign import ccall "qtc_QWidget_locale" qtc_QWidget_locale :: Ptr (TQWidget a) -> IO (Ptr (TQLocale ()))
lower :: QWidget a -> (()) -> IO ()
lower x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_lower cobj_x0
foreign import ccall "qtc_QWidget_lower" qtc_QWidget_lower :: Ptr (TQWidget a) -> IO ()
mapFrom :: QWidget a -> ((QWidget t1, Point)) -> IO (Point)
mapFrom x0 (x1, x2)
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPoint x2 $ \cpoint_x2_x cpoint_x2_y ->
qtc_QWidget_mapFrom_qth cobj_x0 cobj_x1 cpoint_x2_x cpoint_x2_y cpoint_ret_x cpoint_ret_y
foreign import ccall "qtc_QWidget_mapFrom_qth" qtc_QWidget_mapFrom_qth :: Ptr (TQWidget a) -> Ptr (TQWidget t1) -> CInt -> CInt -> Ptr CInt -> Ptr CInt -> IO ()
qmapFrom :: QWidget a -> ((QWidget t1, QPoint t2)) -> IO (QPoint ())
qmapFrom x0 (x1, x2)
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QWidget_mapFrom cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QWidget_mapFrom" qtc_QWidget_mapFrom :: Ptr (TQWidget a) -> Ptr (TQWidget t1) -> Ptr (TQPoint t2) -> IO (Ptr (TQPoint ()))
mapFromGlobal :: QWidget a -> ((Point)) -> IO (Point)
mapFromGlobal x0 (x1)
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QWidget_mapFromGlobal_qth cobj_x0 cpoint_x1_x cpoint_x1_y cpoint_ret_x cpoint_ret_y
foreign import ccall "qtc_QWidget_mapFromGlobal_qth" qtc_QWidget_mapFromGlobal_qth :: Ptr (TQWidget a) -> CInt -> CInt -> Ptr CInt -> Ptr CInt -> IO ()
qmapFromGlobal :: QWidget a -> ((QPoint t1)) -> IO (QPoint ())
qmapFromGlobal x0 (x1)
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_mapFromGlobal cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_mapFromGlobal" qtc_QWidget_mapFromGlobal :: Ptr (TQWidget a) -> Ptr (TQPoint t1) -> IO (Ptr (TQPoint ()))
instance QmapFromParent (QWidget a) ((Point)) (IO (Point)) where
mapFromParent x0 (x1)
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QWidget_mapFromParent_qth cobj_x0 cpoint_x1_x cpoint_x1_y cpoint_ret_x cpoint_ret_y
foreign import ccall "qtc_QWidget_mapFromParent_qth" qtc_QWidget_mapFromParent_qth :: Ptr (TQWidget a) -> CInt -> CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance QqmapFromParent (QWidget a) ((QPoint t1)) (IO (QPoint ())) where
qmapFromParent x0 (x1)
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_mapFromParent cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_mapFromParent" qtc_QWidget_mapFromParent :: Ptr (TQWidget a) -> Ptr (TQPoint t1) -> IO (Ptr (TQPoint ()))
mapTo :: QWidget a -> ((QWidget t1, Point)) -> IO (Point)
mapTo x0 (x1, x2)
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPoint x2 $ \cpoint_x2_x cpoint_x2_y ->
qtc_QWidget_mapTo_qth cobj_x0 cobj_x1 cpoint_x2_x cpoint_x2_y cpoint_ret_x cpoint_ret_y
foreign import ccall "qtc_QWidget_mapTo_qth" qtc_QWidget_mapTo_qth :: Ptr (TQWidget a) -> Ptr (TQWidget t1) -> CInt -> CInt -> Ptr CInt -> Ptr CInt -> IO ()
qmapTo :: QWidget a -> ((QWidget t1, QPoint t2)) -> IO (QPoint ())
qmapTo x0 (x1, x2)
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QWidget_mapTo cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QWidget_mapTo" qtc_QWidget_mapTo :: Ptr (TQWidget a) -> Ptr (TQWidget t1) -> Ptr (TQPoint t2) -> IO (Ptr (TQPoint ()))
mapToGlobal :: QWidget a -> ((Point)) -> IO (Point)
mapToGlobal x0 (x1)
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QWidget_mapToGlobal_qth cobj_x0 cpoint_x1_x cpoint_x1_y cpoint_ret_x cpoint_ret_y
foreign import ccall "qtc_QWidget_mapToGlobal_qth" qtc_QWidget_mapToGlobal_qth :: Ptr (TQWidget a) -> CInt -> CInt -> Ptr CInt -> Ptr CInt -> IO ()
qmapToGlobal :: QWidget a -> ((QPoint t1)) -> IO (QPoint ())
qmapToGlobal x0 (x1)
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_mapToGlobal cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_mapToGlobal" qtc_QWidget_mapToGlobal :: Ptr (TQWidget a) -> Ptr (TQPoint t1) -> IO (Ptr (TQPoint ()))
instance QmapToParent (QWidget a) ((Point)) (IO (Point)) where
mapToParent x0 (x1)
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QWidget_mapToParent_qth cobj_x0 cpoint_x1_x cpoint_x1_y cpoint_ret_x cpoint_ret_y
foreign import ccall "qtc_QWidget_mapToParent_qth" qtc_QWidget_mapToParent_qth :: Ptr (TQWidget a) -> CInt -> CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance QqmapToParent (QWidget a) ((QPoint t1)) (IO (QPoint ())) where
qmapToParent x0 (x1)
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_mapToParent cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_mapToParent" qtc_QWidget_mapToParent :: Ptr (TQWidget a) -> Ptr (TQPoint t1) -> IO (Ptr (TQPoint ()))
instance Qmask (QWidget a) (()) (IO (QRegion ())) where
mask x0 ()
= withQRegionResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_mask cobj_x0
foreign import ccall "qtc_QWidget_mask" qtc_QWidget_mask :: Ptr (TQWidget a) -> IO (Ptr (TQRegion ()))
instance Qmask_nf (QWidget a) (()) (IO (QRegion ())) where
mask_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_mask cobj_x0
maximumHeight :: QWidget a -> (()) -> IO (Int)
maximumHeight x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_maximumHeight cobj_x0
foreign import ccall "qtc_QWidget_maximumHeight" qtc_QWidget_maximumHeight :: Ptr (TQWidget a) -> IO CInt
instance QqmaximumSize (QWidget a) (()) where
qmaximumSize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_maximumSize cobj_x0
foreign import ccall "qtc_QWidget_maximumSize" qtc_QWidget_maximumSize :: Ptr (TQWidget a) -> IO (Ptr (TQSize ()))
instance QmaximumSize (QWidget a) (()) where
maximumSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_maximumSize_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QWidget_maximumSize_qth" qtc_QWidget_maximumSize_qth :: Ptr (TQWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QmaximumWidth (QWidget a) (()) (IO (Int)) where
maximumWidth x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_maximumWidth cobj_x0
foreign import ccall "qtc_QWidget_maximumWidth" qtc_QWidget_maximumWidth :: Ptr (TQWidget a) -> IO CInt
instance Qmetric (QWidget ()) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_metric cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QWidget_metric" qtc_QWidget_metric :: Ptr (TQWidget a) -> CLong -> IO CInt
instance Qmetric (QWidgetSc a) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_metric cobj_x0 (toCLong $ qEnum_toInt x1)
minimumHeight :: QWidget a -> (()) -> IO (Int)
minimumHeight x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_minimumHeight cobj_x0
foreign import ccall "qtc_QWidget_minimumHeight" qtc_QWidget_minimumHeight :: Ptr (TQWidget a) -> IO CInt
instance QqminimumSize (QWidget a) (()) where
qminimumSize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_minimumSize cobj_x0
foreign import ccall "qtc_QWidget_minimumSize" qtc_QWidget_minimumSize :: Ptr (TQWidget a) -> IO (Ptr (TQSize ()))
instance QminimumSize (QWidget a) (()) where
minimumSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_minimumSize_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QWidget_minimumSize_qth" qtc_QWidget_minimumSize_qth :: Ptr (TQWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QqminimumSizeHint (QWidget ()) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_minimumSizeHint_h cobj_x0
foreign import ccall "qtc_QWidget_minimumSizeHint_h" qtc_QWidget_minimumSizeHint_h :: Ptr (TQWidget a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint (QWidgetSc a) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_minimumSizeHint_h cobj_x0
instance QminimumSizeHint (QWidget ()) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QWidget_minimumSizeHint_qth_h" qtc_QWidget_minimumSizeHint_qth_h :: Ptr (TQWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint (QWidgetSc a) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QminimumWidth (QWidget a) (()) (IO (Int)) where
minimumWidth x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_minimumWidth cobj_x0
foreign import ccall "qtc_QWidget_minimumWidth" qtc_QWidget_minimumWidth :: Ptr (TQWidget a) -> IO CInt
instance QmouseDoubleClickEvent (QWidget ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_mouseDoubleClickEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_mouseDoubleClickEvent_h" qtc_QWidget_mouseDoubleClickEvent_h :: Ptr (TQWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent (QWidgetSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_mouseDoubleClickEvent_h cobj_x0 cobj_x1
qWidgetMouseGrabber :: (()) -> IO (QWidget ())
qWidgetMouseGrabber ()
= withQWidgetResult $
qtc_QWidget_mouseGrabber
foreign import ccall "qtc_QWidget_mouseGrabber" qtc_QWidget_mouseGrabber :: IO (Ptr (TQWidget ()))
instance QmouseMoveEvent (QWidget ()) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_mouseMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_mouseMoveEvent_h" qtc_QWidget_mouseMoveEvent_h :: Ptr (TQWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent (QWidgetSc a) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_mouseMoveEvent_h cobj_x0 cobj_x1
instance QmousePressEvent (QWidget ()) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_mousePressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_mousePressEvent_h" qtc_QWidget_mousePressEvent_h :: Ptr (TQWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent (QWidgetSc a) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_mousePressEvent_h cobj_x0 cobj_x1
instance QmouseReleaseEvent (QWidget ()) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_mouseReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_mouseReleaseEvent_h" qtc_QWidget_mouseReleaseEvent_h :: Ptr (TQWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent (QWidgetSc a) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_mouseReleaseEvent_h cobj_x0 cobj_x1
instance Qmove (QWidget ()) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_move1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QWidget_move1" qtc_QWidget_move1 :: Ptr (TQWidget a) -> CInt -> CInt -> IO ()
instance Qmove (QWidgetSc a) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_move1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qmove (QWidget ()) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QWidget_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QWidget_move_qth" qtc_QWidget_move_qth :: Ptr (TQWidget a) -> CInt -> CInt -> IO ()
instance Qmove (QWidgetSc a) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QWidget_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance Qqmove (QWidget ()) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_move cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_move" qtc_QWidget_move :: Ptr (TQWidget a) -> Ptr (TQPoint t1) -> IO ()
instance Qqmove (QWidgetSc a) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_move cobj_x0 cobj_x1
instance QmoveEvent (QWidget ()) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_moveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_moveEvent_h" qtc_QWidget_moveEvent_h :: Ptr (TQWidget a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent (QWidgetSc a) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_moveEvent_h cobj_x0 cobj_x1
nextInFocusChain :: QWidget a -> (()) -> IO (QWidget ())
nextInFocusChain x0 ()
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_nextInFocusChain cobj_x0
foreign import ccall "qtc_QWidget_nextInFocusChain" qtc_QWidget_nextInFocusChain :: Ptr (TQWidget a) -> IO (Ptr (TQWidget ()))
qnormalGeometry :: QWidget a -> (()) -> IO (QRect ())
qnormalGeometry x0 ()
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_normalGeometry cobj_x0
foreign import ccall "qtc_QWidget_normalGeometry" qtc_QWidget_normalGeometry :: Ptr (TQWidget a) -> IO (Ptr (TQRect ()))
normalGeometry :: QWidget a -> (()) -> IO (Rect)
normalGeometry x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_normalGeometry_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QWidget_normalGeometry_qth" qtc_QWidget_normalGeometry_qth :: Ptr (TQWidget a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
overrideWindowFlags :: QWidget a -> ((WindowFlags)) -> IO ()
overrideWindowFlags x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_overrideWindowFlags cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QWidget_overrideWindowFlags" qtc_QWidget_overrideWindowFlags :: Ptr (TQWidget a) -> CLong -> IO ()
overrideWindowState :: QWidget a -> ((WindowStates)) -> IO ()
overrideWindowState x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_overrideWindowState cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QWidget_overrideWindowState" qtc_QWidget_overrideWindowState :: Ptr (TQWidget a) -> CLong -> IO ()
instance QpaintEngine (QWidget ()) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_paintEngine_h cobj_x0
foreign import ccall "qtc_QWidget_paintEngine_h" qtc_QWidget_paintEngine_h :: Ptr (TQWidget a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine (QWidgetSc a) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_paintEngine_h cobj_x0
instance QpaintEvent (QWidget ()) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_paintEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_paintEvent_h" qtc_QWidget_paintEvent_h :: Ptr (TQWidget a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent (QWidgetSc a) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_paintEvent_h cobj_x0 cobj_x1
instance Qpalette (QWidget a) (()) where
palette x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_palette cobj_x0
foreign import ccall "qtc_QWidget_palette" qtc_QWidget_palette :: Ptr (TQWidget a) -> IO (Ptr (TQPalette ()))
instance QpaletteChange (QWidget ()) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_paletteChange cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_paletteChange" qtc_QWidget_paletteChange :: Ptr (TQWidget a) -> Ptr (TQPalette t1) -> IO ()
instance QpaletteChange (QWidgetSc a) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_paletteChange cobj_x0 cobj_x1
instance QparentWidget (QWidget a) (()) where
parentWidget x0 ()
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_parentWidget cobj_x0
foreign import ccall "qtc_QWidget_parentWidget" qtc_QWidget_parentWidget :: Ptr (TQWidget a) -> IO (Ptr (TQWidget ()))
instance Qpos (QWidget a) (()) (IO (Point)) where
pos x0 ()
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_pos_qth cobj_x0 cpoint_ret_x cpoint_ret_y
foreign import ccall "qtc_QWidget_pos_qth" qtc_QWidget_pos_qth :: Ptr (TQWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance Qqpos (QWidget a) (()) (IO (QPoint ())) where
qpos x0 ()
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_pos cobj_x0
foreign import ccall "qtc_QWidget_pos" qtc_QWidget_pos :: Ptr (TQWidget a) -> IO (Ptr (TQPoint ()))
raise :: QWidget a -> (()) -> IO ()
raise x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_raise cobj_x0
foreign import ccall "qtc_QWidget_raise" qtc_QWidget_raise :: Ptr (TQWidget a) -> IO ()
instance Qqqrect (QWidget a) (()) (IO (QRect ())) where
qqrect x0 ()
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_rect cobj_x0
foreign import ccall "qtc_QWidget_rect" qtc_QWidget_rect :: Ptr (TQWidget a) -> IO (Ptr (TQRect ()))
instance Qqrect (QWidget a) (()) (IO (Rect)) where
qrect x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_rect_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QWidget_rect_qth" qtc_QWidget_rect_qth :: Ptr (TQWidget a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
releaseKeyboard :: QWidget a -> (()) -> IO ()
releaseKeyboard x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_releaseKeyboard cobj_x0
foreign import ccall "qtc_QWidget_releaseKeyboard" qtc_QWidget_releaseKeyboard :: Ptr (TQWidget a) -> IO ()
releaseMouse :: QWidget a -> (()) -> IO ()
releaseMouse x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_releaseMouse cobj_x0
foreign import ccall "qtc_QWidget_releaseMouse" qtc_QWidget_releaseMouse :: Ptr (TQWidget a) -> IO ()
releaseShortcut :: QWidget a -> ((Int)) -> IO ()
releaseShortcut x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_releaseShortcut cobj_x0 (toCInt x1)
foreign import ccall "qtc_QWidget_releaseShortcut" qtc_QWidget_releaseShortcut :: Ptr (TQWidget a) -> CInt -> IO ()
instance QremoveAction (QWidget a) ((QAction t1)) where
removeAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_removeAction cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_removeAction" qtc_QWidget_removeAction :: Ptr (TQWidget a) -> Ptr (TQAction t1) -> IO ()
instance Qrender (QWidget a) ((QPaintDevice t1)) where
render x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_render cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_render" qtc_QWidget_render :: Ptr (TQWidget a) -> Ptr (TQPaintDevice t1) -> IO ()
instance Qrender (QWidget a) ((QPaintDevice t1, Point)) where
render x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPoint x2 $ \cpoint_x2_x cpoint_x2_y ->
qtc_QWidget_render1_qth cobj_x0 cobj_x1 cpoint_x2_x cpoint_x2_y
foreign import ccall "qtc_QWidget_render1_qth" qtc_QWidget_render1_qth :: Ptr (TQWidget a) -> Ptr (TQPaintDevice t1) -> CInt -> CInt -> IO ()
instance Qrender (QWidget a) ((QPaintDevice t1, Point, QRegion t3)) where
render x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPoint x2 $ \cpoint_x2_x cpoint_x2_y ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QWidget_render2_qth cobj_x0 cobj_x1 cpoint_x2_x cpoint_x2_y cobj_x3
foreign import ccall "qtc_QWidget_render2_qth" qtc_QWidget_render2_qth :: Ptr (TQWidget a) -> Ptr (TQPaintDevice t1) -> CInt -> CInt -> Ptr (TQRegion t3) -> IO ()
instance Qqrender (QWidget a) ((QPaintDevice t1, QPoint t2)) where
qrender x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QWidget_render1 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QWidget_render1" qtc_QWidget_render1 :: Ptr (TQWidget a) -> Ptr (TQPaintDevice t1) -> Ptr (TQPoint t2) -> IO ()
instance Qqrender (QWidget a) ((QPaintDevice t1, QPoint t2, QRegion t3)) where
qrender x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QWidget_render2 cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QWidget_render2" qtc_QWidget_render2 :: Ptr (TQWidget a) -> Ptr (TQPaintDevice t1) -> Ptr (TQPoint t2) -> Ptr (TQRegion t3) -> IO ()
instance Qrender (QWidget a) ((QWidget t1)) where
render x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_render_widget cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_render_widget" qtc_QWidget_render_widget :: Ptr (TQWidget a) -> Ptr (TQWidget t1) -> IO ()
instance Qrender (QWidget a) ((QWidget t1, Point)) where
render x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPoint x2 $ \cpoint_x2_x cpoint_x2_y ->
qtc_QWidget_render1_widget_qth cobj_x0 cobj_x1 cpoint_x2_x cpoint_x2_y
foreign import ccall "qtc_QWidget_render1_widget_qth" qtc_QWidget_render1_widget_qth :: Ptr (TQWidget a) -> Ptr (TQWidget t1) -> CInt -> CInt -> IO ()
instance Qrender (QWidget a) ((QWidget t1, Point, QRegion t3)) where
render x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPoint x2 $ \cpoint_x2_x cpoint_x2_y ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QWidget_render2_widget_qth cobj_x0 cobj_x1 cpoint_x2_x cpoint_x2_y cobj_x3
foreign import ccall "qtc_QWidget_render2_widget_qth" qtc_QWidget_render2_widget_qth :: Ptr (TQWidget a) -> Ptr (TQWidget t1) -> CInt -> CInt -> Ptr (TQRegion t3) -> IO ()
instance Qqrender (QWidget a) ((QWidget t1, QPoint t2)) where
qrender x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QWidget_render1_widget cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QWidget_render1_widget" qtc_QWidget_render1_widget :: Ptr (TQWidget a) -> Ptr (TQWidget t1) -> Ptr (TQPoint t2) -> IO ()
instance Qqrender (QWidget a) ((QWidget t1, QPoint t2, QRegion t3)) where
qrender x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QWidget_render2_widget cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QWidget_render2_widget" qtc_QWidget_render2_widget :: Ptr (TQWidget a) -> Ptr (TQWidget t1) -> Ptr (TQPoint t2) -> Ptr (TQRegion t3) -> IO ()
instance Qrepaint (QWidget ()) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_repaint cobj_x0
foreign import ccall "qtc_QWidget_repaint" qtc_QWidget_repaint :: Ptr (TQWidget a) -> IO ()
instance Qrepaint (QWidgetSc a) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_repaint cobj_x0
instance Qrepaint (QWidget ()) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_repaint3 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QWidget_repaint3" qtc_QWidget_repaint3 :: Ptr (TQWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qrepaint (QWidgetSc a) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_repaint3 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
qrepaint :: QWidget a -> ((QRect t1)) -> IO ()
qrepaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_repaint2 cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_repaint2" qtc_QWidget_repaint2 :: Ptr (TQWidget a) -> Ptr (TQRect t1) -> IO ()
instance Qrepaint (QWidget ()) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_repaint1 cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_repaint1" qtc_QWidget_repaint1 :: Ptr (TQWidget a) -> Ptr (TQRegion t1) -> IO ()
instance Qrepaint (QWidgetSc a) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_repaint1 cobj_x0 cobj_x1
instance Qrepaint (QWidget ()) ((Rect)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QWidget_repaint2_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QWidget_repaint2_qth" qtc_QWidget_repaint2_qth :: Ptr (TQWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qrepaint (QWidgetSc a) ((Rect)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QWidget_repaint2_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance QresetInputContext (QWidget ()) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_resetInputContext cobj_x0
foreign import ccall "qtc_QWidget_resetInputContext" qtc_QWidget_resetInputContext :: Ptr (TQWidget a) -> IO ()
instance QresetInputContext (QWidgetSc a) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_resetInputContext cobj_x0
instance Qresize (QWidget ()) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_resize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QWidget_resize1" qtc_QWidget_resize1 :: Ptr (TQWidget a) -> CInt -> CInt -> IO ()
instance Qresize (QWidgetSc a) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_resize1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qqresize (QWidget ()) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_resize cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_resize" qtc_QWidget_resize :: Ptr (TQWidget a) -> Ptr (TQSize t1) -> IO ()
instance Qqresize (QWidgetSc a) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_resize cobj_x0 cobj_x1
instance Qresize (QWidget ()) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QWidget_resize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QWidget_resize_qth" qtc_QWidget_resize_qth :: Ptr (TQWidget a) -> CInt -> CInt -> IO ()
instance Qresize (QWidgetSc a) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QWidget_resize_qth cobj_x0 csize_x1_w csize_x1_h
instance QresizeEvent (QWidget ()) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_resizeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_resizeEvent_h" qtc_QWidget_resizeEvent_h :: Ptr (TQWidget a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent (QWidgetSc a) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_resizeEvent_h cobj_x0 cobj_x1
restoreGeometry :: QWidget a -> ((QByteArray ())) -> IO (Bool)
restoreGeometry x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_restoreGeometry cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_restoreGeometry" qtc_QWidget_restoreGeometry :: Ptr (TQWidget a) -> Ptr (TQByteArray ()) -> IO CBool
saveGeometry :: QWidget a -> (()) -> IO (QByteArray ())
saveGeometry x0 ()
= withQByteArrayResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_saveGeometry cobj_x0
foreign import ccall "qtc_QWidget_saveGeometry" qtc_QWidget_saveGeometry :: Ptr (TQWidget a) -> IO (Ptr (TQByteArray ()))
class Qscroll x1 where
scroll :: QWidget a -> x1 -> IO ()
instance Qscroll ((Int, Int)) where
scroll x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_scroll cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QWidget_scroll" qtc_QWidget_scroll :: Ptr (TQWidget a) -> CInt -> CInt -> IO ()
qscroll :: QWidget a -> ((Int, Int, QRect t3)) -> IO ()
qscroll x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QWidget_scroll1 cobj_x0 (toCInt x1) (toCInt x2) cobj_x3
foreign import ccall "qtc_QWidget_scroll1" qtc_QWidget_scroll1 :: Ptr (TQWidget a) -> CInt -> CInt -> Ptr (TQRect t3) -> IO ()
instance Qscroll ((Int, Int, Rect)) where
scroll x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x3 $ \crect_x3_x crect_x3_y crect_x3_w crect_x3_h ->
qtc_QWidget_scroll1_qth cobj_x0 (toCInt x1) (toCInt x2) crect_x3_x crect_x3_y crect_x3_w crect_x3_h
foreign import ccall "qtc_QWidget_scroll1_qth" qtc_QWidget_scroll1_qth :: Ptr (TQWidget a) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetAcceptDrops (QWidget a) ((Bool)) where
setAcceptDrops x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setAcceptDrops cobj_x0 (toCBool x1)
foreign import ccall "qtc_QWidget_setAcceptDrops" qtc_QWidget_setAcceptDrops :: Ptr (TQWidget a) -> CBool -> IO ()
class QsetAttribute x1 where
setAttribute :: QWidget a -> x1 -> IO ()
instance QsetAttribute ((WidgetAttribute)) where
setAttribute x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setAttribute cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QWidget_setAttribute" qtc_QWidget_setAttribute :: Ptr (TQWidget a) -> CLong -> IO ()
instance QsetAttribute ((WidgetAttribute, Bool)) where
setAttribute x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setAttribute1 cobj_x0 (toCLong $ qEnum_toInt x1) (toCBool x2)
foreign import ccall "qtc_QWidget_setAttribute1" qtc_QWidget_setAttribute1 :: Ptr (TQWidget a) -> CLong -> CBool -> IO ()
setAutoFillBackground :: QWidget a -> ((Bool)) -> IO ()
setAutoFillBackground x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setAutoFillBackground cobj_x0 (toCBool x1)
foreign import ccall "qtc_QWidget_setAutoFillBackground" qtc_QWidget_setAutoFillBackground :: Ptr (TQWidget a) -> CBool -> IO ()
setBackgroundRole :: QWidget a -> ((ColorRole)) -> IO ()
setBackgroundRole x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setBackgroundRole cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QWidget_setBackgroundRole" qtc_QWidget_setBackgroundRole :: Ptr (TQWidget a) -> CLong -> IO ()
class QsetBaseSize x1 where
setBaseSize :: QWidget a -> x1 -> IO ()
instance QsetBaseSize ((Int, Int)) where
setBaseSize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setBaseSize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QWidget_setBaseSize1" qtc_QWidget_setBaseSize1 :: Ptr (TQWidget a) -> CInt -> CInt -> IO ()
qsetBaseSize :: QWidget a -> ((QSize t1)) -> IO ()
qsetBaseSize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setBaseSize cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setBaseSize" qtc_QWidget_setBaseSize :: Ptr (TQWidget a) -> Ptr (TQSize t1) -> IO ()
instance QsetBaseSize ((Size)) where
setBaseSize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QWidget_setBaseSize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QWidget_setBaseSize_qth" qtc_QWidget_setBaseSize_qth :: Ptr (TQWidget a) -> CInt -> CInt -> IO ()
instance QsetContentsMargins (QWidget a) ((Int, Int, Int, Int)) where
setContentsMargins x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setContentsMargins cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QWidget_setContentsMargins" qtc_QWidget_setContentsMargins :: Ptr (TQWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
setContextMenuPolicy :: QWidget a -> ((ContextMenuPolicy)) -> IO ()
setContextMenuPolicy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setContextMenuPolicy cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QWidget_setContextMenuPolicy" qtc_QWidget_setContextMenuPolicy :: Ptr (TQWidget a) -> CLong -> IO ()
instance QsetCursor (QWidget a) ((QCursor t1)) where
setCursor x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setCursor cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setCursor" qtc_QWidget_setCursor :: Ptr (TQWidget a) -> Ptr (TQCursor t1) -> IO ()
instance QsetDisabled (QWidget a) ((Bool)) where
setDisabled x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setDisabled cobj_x0 (toCBool x1)
foreign import ccall "qtc_QWidget_setDisabled" qtc_QWidget_setDisabled :: Ptr (TQWidget a) -> CBool -> IO ()
instance QsetEnabled (QWidget a) ((Bool)) where
setEnabled x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setEnabled cobj_x0 (toCBool x1)
foreign import ccall "qtc_QWidget_setEnabled" qtc_QWidget_setEnabled :: Ptr (TQWidget a) -> CBool -> IO ()
setFixedHeight :: QWidget a -> ((Int)) -> IO ()
setFixedHeight x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setFixedHeight cobj_x0 (toCInt x1)
foreign import ccall "qtc_QWidget_setFixedHeight" qtc_QWidget_setFixedHeight :: Ptr (TQWidget a) -> CInt -> IO ()
class QsetFixedSize x1 where
setFixedSize :: QWidget a -> x1 -> IO ()
instance QsetFixedSize ((Int, Int)) where
setFixedSize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setFixedSize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QWidget_setFixedSize1" qtc_QWidget_setFixedSize1 :: Ptr (TQWidget a) -> CInt -> CInt -> IO ()
qsetFixedSize :: QWidget a -> ((QSize t1)) -> IO ()
qsetFixedSize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setFixedSize cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setFixedSize" qtc_QWidget_setFixedSize :: Ptr (TQWidget a) -> Ptr (TQSize t1) -> IO ()
instance QsetFixedSize ((Size)) where
setFixedSize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QWidget_setFixedSize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QWidget_setFixedSize_qth" qtc_QWidget_setFixedSize_qth :: Ptr (TQWidget a) -> CInt -> CInt -> IO ()
setFixedWidth :: QWidget a -> ((Int)) -> IO ()
setFixedWidth x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setFixedWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QWidget_setFixedWidth" qtc_QWidget_setFixedWidth :: Ptr (TQWidget a) -> CInt -> IO ()
instance QsetFocus (QWidget a) (()) where
setFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setFocus cobj_x0
foreign import ccall "qtc_QWidget_setFocus" qtc_QWidget_setFocus :: Ptr (TQWidget a) -> IO ()
instance QsetFocus (QWidget a) ((FocusReason)) where
setFocus x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setFocus1 cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QWidget_setFocus1" qtc_QWidget_setFocus1 :: Ptr (TQWidget a) -> CLong -> IO ()
setFocusPolicy :: QWidget a -> ((FocusPolicy)) -> IO ()
setFocusPolicy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setFocusPolicy cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QWidget_setFocusPolicy" qtc_QWidget_setFocusPolicy :: Ptr (TQWidget a) -> CLong -> IO ()
setFocusProxy :: QWidget a -> ((QWidget t1)) -> IO ()
setFocusProxy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setFocusProxy cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setFocusProxy" qtc_QWidget_setFocusProxy :: Ptr (TQWidget a) -> Ptr (TQWidget t1) -> IO ()
instance QsetFont (QWidget a) ((QFont t1)) where
setFont x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setFont cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setFont" qtc_QWidget_setFont :: Ptr (TQWidget a) -> Ptr (TQFont t1) -> IO ()
setForegroundRole :: QWidget a -> ((ColorRole)) -> IO ()
setForegroundRole x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setForegroundRole cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QWidget_setForegroundRole" qtc_QWidget_setForegroundRole :: Ptr (TQWidget a) -> CLong -> IO ()
instance QsetGeometry (QWidget ()) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QWidget_setGeometry1" qtc_QWidget_setGeometry1 :: Ptr (TQWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QWidgetSc a) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance QqsetGeometry (QWidget ()) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setGeometry cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setGeometry" qtc_QWidget_setGeometry :: Ptr (TQWidget a) -> Ptr (TQRect t1) -> IO ()
instance QqsetGeometry (QWidgetSc a) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setGeometry cobj_x0 cobj_x1
instance QsetGeometry (QWidget ()) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QWidget_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QWidget_setGeometry_qth" qtc_QWidget_setGeometry_qth :: Ptr (TQWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QWidgetSc a) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QWidget_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance QsetHidden (QWidget a) ((Bool)) where
setHidden x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setHidden cobj_x0 (toCBool x1)
foreign import ccall "qtc_QWidget_setHidden" qtc_QWidget_setHidden :: Ptr (TQWidget a) -> CBool -> IO ()
instance QsetInputContext (QWidget a) ((QInputContext t1)) where
setInputContext x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setInputContext cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setInputContext" qtc_QWidget_setInputContext :: Ptr (TQWidget a) -> Ptr (TQInputContext t1) -> IO ()
setLayout :: QWidget a -> ((QLayout t1)) -> IO ()
setLayout x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setLayout cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setLayout" qtc_QWidget_setLayout :: Ptr (TQWidget a) -> Ptr (TQLayout t1) -> IO ()
instance QsetLayoutDirection (QWidget a) ((LayoutDirection)) where
setLayoutDirection x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setLayoutDirection cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QWidget_setLayoutDirection" qtc_QWidget_setLayoutDirection :: Ptr (TQWidget a) -> CLong -> IO ()
instance QsetLocale (QWidget a) ((QLocale t1)) where
setLocale x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setLocale cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setLocale" qtc_QWidget_setLocale :: Ptr (TQWidget a) -> Ptr (TQLocale t1) -> IO ()
instance QsetMask (QWidget a) ((QBitmap t1)) where
setMask x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setMask cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setMask" qtc_QWidget_setMask :: Ptr (TQWidget a) -> Ptr (TQBitmap t1) -> IO ()
instance QsetMask (QWidget a) ((QRegion t1)) where
setMask x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setMask1 cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setMask1" qtc_QWidget_setMask1 :: Ptr (TQWidget a) -> Ptr (TQRegion t1) -> IO ()
setMaximumHeight :: QWidget a -> ((Int)) -> IO ()
setMaximumHeight x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setMaximumHeight cobj_x0 (toCInt x1)
foreign import ccall "qtc_QWidget_setMaximumHeight" qtc_QWidget_setMaximumHeight :: Ptr (TQWidget a) -> CInt -> IO ()
class QsetMaximumSize x1 where
setMaximumSize :: QWidget a -> x1 -> IO ()
instance QsetMaximumSize ((Int, Int)) where
setMaximumSize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setMaximumSize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QWidget_setMaximumSize1" qtc_QWidget_setMaximumSize1 :: Ptr (TQWidget a) -> CInt -> CInt -> IO ()
qsetMaximumSize :: QWidget a -> ((QSize t1)) -> IO ()
qsetMaximumSize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setMaximumSize cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setMaximumSize" qtc_QWidget_setMaximumSize :: Ptr (TQWidget a) -> Ptr (TQSize t1) -> IO ()
instance QsetMaximumSize ((Size)) where
setMaximumSize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QWidget_setMaximumSize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QWidget_setMaximumSize_qth" qtc_QWidget_setMaximumSize_qth :: Ptr (TQWidget a) -> CInt -> CInt -> IO ()
setMaximumWidth :: QWidget a -> ((Int)) -> IO ()
setMaximumWidth x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setMaximumWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QWidget_setMaximumWidth" qtc_QWidget_setMaximumWidth :: Ptr (TQWidget a) -> CInt -> IO ()
setMinimumHeight :: QWidget a -> ((Int)) -> IO ()
setMinimumHeight x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setMinimumHeight cobj_x0 (toCInt x1)
foreign import ccall "qtc_QWidget_setMinimumHeight" qtc_QWidget_setMinimumHeight :: Ptr (TQWidget a) -> CInt -> IO ()
class QsetMinimumSize x1 where
setMinimumSize :: QWidget a -> x1 -> IO ()
instance QsetMinimumSize ((Int, Int)) where
setMinimumSize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setMinimumSize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QWidget_setMinimumSize1" qtc_QWidget_setMinimumSize1 :: Ptr (TQWidget a) -> CInt -> CInt -> IO ()
qsetMinimumSize :: QWidget a -> ((QSize t1)) -> IO ()
qsetMinimumSize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setMinimumSize cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setMinimumSize" qtc_QWidget_setMinimumSize :: Ptr (TQWidget a) -> Ptr (TQSize t1) -> IO ()
instance QsetMinimumSize ((Size)) where
setMinimumSize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QWidget_setMinimumSize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QWidget_setMinimumSize_qth" qtc_QWidget_setMinimumSize_qth :: Ptr (TQWidget a) -> CInt -> CInt -> IO ()
setMinimumWidth :: QWidget a -> ((Int)) -> IO ()
setMinimumWidth x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setMinimumWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QWidget_setMinimumWidth" qtc_QWidget_setMinimumWidth :: Ptr (TQWidget a) -> CInt -> IO ()
instance QsetMouseTracking (QWidget ()) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setMouseTracking cobj_x0 (toCBool x1)
foreign import ccall "qtc_QWidget_setMouseTracking" qtc_QWidget_setMouseTracking :: Ptr (TQWidget a) -> CBool -> IO ()
instance QsetMouseTracking (QWidgetSc a) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setMouseTracking cobj_x0 (toCBool x1)
instance QsetPalette (QWidget a) ((QPalette t1)) where
setPalette x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setPalette cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setPalette" qtc_QWidget_setPalette :: Ptr (TQWidget a) -> Ptr (TQPalette t1) -> IO ()
class QsetParent x1 where
setParent :: QWidget a -> x1 -> IO ()
instance QsetParent ((QWidget t1)) where
setParent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setParent cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setParent" qtc_QWidget_setParent :: Ptr (TQWidget a) -> Ptr (TQWidget t1) -> IO ()
instance QsetParent ((QWidget t1, WindowFlags)) where
setParent x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setParent1 cobj_x0 cobj_x1 (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QWidget_setParent1" qtc_QWidget_setParent1 :: Ptr (TQWidget a) -> Ptr (TQWidget t1) -> CLong -> IO ()
class QsetShortcutAutoRepeat x1 where
setShortcutAutoRepeat :: QWidget a -> x1 -> IO ()
instance QsetShortcutAutoRepeat ((Int)) where
setShortcutAutoRepeat x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setShortcutAutoRepeat cobj_x0 (toCInt x1)
foreign import ccall "qtc_QWidget_setShortcutAutoRepeat" qtc_QWidget_setShortcutAutoRepeat :: Ptr (TQWidget a) -> CInt -> IO ()
instance QsetShortcutAutoRepeat ((Int, Bool)) where
setShortcutAutoRepeat x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setShortcutAutoRepeat1 cobj_x0 (toCInt x1) (toCBool x2)
foreign import ccall "qtc_QWidget_setShortcutAutoRepeat1" qtc_QWidget_setShortcutAutoRepeat1 :: Ptr (TQWidget a) -> CInt -> CBool -> IO ()
class QsetShortcutEnabled x1 where
setShortcutEnabled :: QWidget a -> x1 -> IO ()
instance QsetShortcutEnabled ((Int)) where
setShortcutEnabled x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setShortcutEnabled cobj_x0 (toCInt x1)
foreign import ccall "qtc_QWidget_setShortcutEnabled" qtc_QWidget_setShortcutEnabled :: Ptr (TQWidget a) -> CInt -> IO ()
instance QsetShortcutEnabled ((Int, Bool)) where
setShortcutEnabled x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setShortcutEnabled1 cobj_x0 (toCInt x1) (toCBool x2)
foreign import ccall "qtc_QWidget_setShortcutEnabled1" qtc_QWidget_setShortcutEnabled1 :: Ptr (TQWidget a) -> CInt -> CBool -> IO ()
setShown :: QWidget a -> ((Bool)) -> IO ()
setShown x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setShown cobj_x0 (toCBool x1)
foreign import ccall "qtc_QWidget_setShown" qtc_QWidget_setShown :: Ptr (TQWidget a) -> CBool -> IO ()
class QsetSizeIncrement x1 where
setSizeIncrement :: QWidget a -> x1 -> IO ()
instance QsetSizeIncrement ((Int, Int)) where
setSizeIncrement x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setSizeIncrement1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QWidget_setSizeIncrement1" qtc_QWidget_setSizeIncrement1 :: Ptr (TQWidget a) -> CInt -> CInt -> IO ()
qsetSizeIncrement :: QWidget a -> ((QSize t1)) -> IO ()
qsetSizeIncrement x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setSizeIncrement cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setSizeIncrement" qtc_QWidget_setSizeIncrement :: Ptr (TQWidget a) -> Ptr (TQSize t1) -> IO ()
instance QsetSizeIncrement ((Size)) where
setSizeIncrement x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QWidget_setSizeIncrement_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QWidget_setSizeIncrement_qth" qtc_QWidget_setSizeIncrement_qth :: Ptr (TQWidget a) -> CInt -> CInt -> IO ()
class QsetSizePolicy x1 where
setSizePolicy :: QWidget a -> x1 -> IO ()
instance QsetSizePolicy ((Policy, Policy)) where
setSizePolicy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setSizePolicy1 cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QWidget_setSizePolicy1" qtc_QWidget_setSizePolicy1 :: Ptr (TQWidget a) -> CLong -> CLong -> IO ()
instance QsetSizePolicy ((QSizePolicy t1)) where
setSizePolicy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setSizePolicy cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setSizePolicy" qtc_QWidget_setSizePolicy :: Ptr (TQWidget a) -> Ptr (TQSizePolicy t1) -> IO ()
instance QsetStatusTip (QWidget a) ((String)) where
setStatusTip x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QWidget_setStatusTip cobj_x0 cstr_x1
foreign import ccall "qtc_QWidget_setStatusTip" qtc_QWidget_setStatusTip :: Ptr (TQWidget a) -> CWString -> IO ()
instance QsetStyle (QWidget a) ((QStyle t1)) where
setStyle x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setStyle cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setStyle" qtc_QWidget_setStyle :: Ptr (TQWidget a) -> Ptr (TQStyle t1) -> IO ()
instance QsetStyleSheet (QWidget a) ((String)) where
setStyleSheet x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QWidget_setStyleSheet cobj_x0 cstr_x1
foreign import ccall "qtc_QWidget_setStyleSheet" qtc_QWidget_setStyleSheet :: Ptr (TQWidget a) -> CWString -> IO ()
qWidgetSetTabOrder :: ((QWidget t1, QWidget t2)) -> IO ()
qWidgetSetTabOrder (x1, x2)
= withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QWidget_setTabOrder cobj_x1 cobj_x2
foreign import ccall "qtc_QWidget_setTabOrder" qtc_QWidget_setTabOrder :: Ptr (TQWidget t1) -> Ptr (TQWidget t2) -> IO ()
instance QsetToolTip (QWidget a) ((String)) where
setToolTip x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QWidget_setToolTip cobj_x0 cstr_x1
foreign import ccall "qtc_QWidget_setToolTip" qtc_QWidget_setToolTip :: Ptr (TQWidget a) -> CWString -> IO ()
setUpdatesEnabled :: QWidget a -> ((Bool)) -> IO ()
setUpdatesEnabled x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setUpdatesEnabled cobj_x0 (toCBool x1)
foreign import ccall "qtc_QWidget_setUpdatesEnabled" qtc_QWidget_setUpdatesEnabled :: Ptr (TQWidget a) -> CBool -> IO ()
instance QsetVisible (QWidget ()) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setVisible_h cobj_x0 (toCBool x1)
foreign import ccall "qtc_QWidget_setVisible_h" qtc_QWidget_setVisible_h :: Ptr (TQWidget a) -> CBool -> IO ()
instance QsetVisible (QWidgetSc a) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setVisible_h cobj_x0 (toCBool x1)
instance QsetWhatsThis (QWidget a) ((String)) where
setWhatsThis x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QWidget_setWhatsThis cobj_x0 cstr_x1
foreign import ccall "qtc_QWidget_setWhatsThis" qtc_QWidget_setWhatsThis :: Ptr (TQWidget a) -> CWString -> IO ()
setWindowFlags :: QWidget a -> ((WindowFlags)) -> IO ()
setWindowFlags x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setWindowFlags cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QWidget_setWindowFlags" qtc_QWidget_setWindowFlags :: Ptr (TQWidget a) -> CLong -> IO ()
setWindowIcon :: QWidget a -> ((QIcon t1)) -> IO ()
setWindowIcon x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_setWindowIcon cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_setWindowIcon" qtc_QWidget_setWindowIcon :: Ptr (TQWidget a) -> Ptr (TQIcon t1) -> IO ()
setWindowIconText :: QWidget a -> ((String)) -> IO ()
setWindowIconText x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QWidget_setWindowIconText cobj_x0 cstr_x1
foreign import ccall "qtc_QWidget_setWindowIconText" qtc_QWidget_setWindowIconText :: Ptr (TQWidget a) -> CWString -> IO ()
instance QsetWindowModality (QWidget ()) ((WindowModality)) where
setWindowModality x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setWindowModality cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QWidget_setWindowModality" qtc_QWidget_setWindowModality :: Ptr (TQWidget a) -> CLong -> IO ()
setWindowModified :: QWidget a -> ((Bool)) -> IO ()
setWindowModified x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setWindowModified cobj_x0 (toCBool x1)
foreign import ccall "qtc_QWidget_setWindowModified" qtc_QWidget_setWindowModified :: Ptr (TQWidget a) -> CBool -> IO ()
setWindowOpacity :: QWidget a -> ((Double)) -> IO ()
setWindowOpacity x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setWindowOpacity cobj_x0 (toCDouble x1)
foreign import ccall "qtc_QWidget_setWindowOpacity" qtc_QWidget_setWindowOpacity :: Ptr (TQWidget a) -> CDouble -> IO ()
setWindowRole :: QWidget a -> ((String)) -> IO ()
setWindowRole x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QWidget_setWindowRole cobj_x0 cstr_x1
foreign import ccall "qtc_QWidget_setWindowRole" qtc_QWidget_setWindowRole :: Ptr (TQWidget a) -> CWString -> IO ()
setWindowState :: QWidget a -> ((WindowStates)) -> IO ()
setWindowState x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_setWindowState cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QWidget_setWindowState" qtc_QWidget_setWindowState :: Ptr (TQWidget a) -> CLong -> IO ()
instance QsetWindowTitle (QWidget a) ((String)) where
setWindowTitle x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QWidget_setWindowTitle cobj_x0 cstr_x1
foreign import ccall "qtc_QWidget_setWindowTitle" qtc_QWidget_setWindowTitle :: Ptr (TQWidget a) -> CWString -> IO ()
instance Qqshow (QWidget a) (()) where
qshow x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_show cobj_x0
foreign import ccall "qtc_QWidget_show" qtc_QWidget_show :: Ptr (TQWidget a) -> IO ()
instance QshowEvent (QWidget ()) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_showEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_showEvent_h" qtc_QWidget_showEvent_h :: Ptr (TQWidget a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent (QWidgetSc a) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_showEvent_h cobj_x0 cobj_x1
showFullScreen :: QWidget a -> (()) -> IO ()
showFullScreen x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_showFullScreen cobj_x0
foreign import ccall "qtc_QWidget_showFullScreen" qtc_QWidget_showFullScreen :: Ptr (TQWidget a) -> IO ()
showMaximized :: QWidget a -> (()) -> IO ()
showMaximized x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_showMaximized cobj_x0
foreign import ccall "qtc_QWidget_showMaximized" qtc_QWidget_showMaximized :: Ptr (TQWidget a) -> IO ()
showMinimized :: QWidget a -> (()) -> IO ()
showMinimized x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_showMinimized cobj_x0
foreign import ccall "qtc_QWidget_showMinimized" qtc_QWidget_showMinimized :: Ptr (TQWidget a) -> IO ()
showNormal :: QWidget a -> (()) -> IO ()
showNormal x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_showNormal cobj_x0
foreign import ccall "qtc_QWidget_showNormal" qtc_QWidget_showNormal :: Ptr (TQWidget a) -> IO ()
instance Qqqsize (QWidget a) (()) (IO (QSize ())) where
qqsize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_size cobj_x0
foreign import ccall "qtc_QWidget_size" qtc_QWidget_size :: Ptr (TQWidget a) -> IO (Ptr (TQSize ()))
instance Qqsize (QWidget a) (()) (IO (Size)) where
qsize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_size_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QWidget_size_qth" qtc_QWidget_size_qth :: Ptr (TQWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QqsizeHint (QWidget ()) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_sizeHint_h cobj_x0
foreign import ccall "qtc_QWidget_sizeHint_h" qtc_QWidget_sizeHint_h :: Ptr (TQWidget a) -> IO (Ptr (TQSize ()))
instance QqsizeHint (QWidgetSc a) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_sizeHint_h cobj_x0
instance QsizeHint (QWidget ()) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QWidget_sizeHint_qth_h" qtc_QWidget_sizeHint_qth_h :: Ptr (TQWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint (QWidgetSc a) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
qsizeIncrement :: QWidget a -> (()) -> IO (QSize ())
qsizeIncrement x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_sizeIncrement cobj_x0
foreign import ccall "qtc_QWidget_sizeIncrement" qtc_QWidget_sizeIncrement :: Ptr (TQWidget a) -> IO (Ptr (TQSize ()))
sizeIncrement :: QWidget a -> (()) -> IO (Size)
sizeIncrement x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_sizeIncrement_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QWidget_sizeIncrement_qth" qtc_QWidget_sizeIncrement_qth :: Ptr (TQWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
sizePolicy :: QWidget a -> (()) -> IO (QSizePolicy ())
sizePolicy x0 ()
= withQSizePolicyResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_sizePolicy cobj_x0
foreign import ccall "qtc_QWidget_sizePolicy" qtc_QWidget_sizePolicy :: Ptr (TQWidget a) -> IO (Ptr (TQSizePolicy ()))
stackUnder :: QWidget a -> ((QWidget t1)) -> IO ()
stackUnder x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_stackUnder cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_stackUnder" qtc_QWidget_stackUnder :: Ptr (TQWidget a) -> Ptr (TQWidget t1) -> IO ()
instance QstatusTip (QWidget a) (()) where
statusTip x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_statusTip cobj_x0
foreign import ccall "qtc_QWidget_statusTip" qtc_QWidget_statusTip :: Ptr (TQWidget a) -> IO (Ptr (TQString ()))
instance Qstyle (QWidget a) (()) (IO (QStyle ())) where
style x0 ()
= withQStyleResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_style cobj_x0
foreign import ccall "qtc_QWidget_style" qtc_QWidget_style :: Ptr (TQWidget a) -> IO (Ptr (TQStyle ()))
instance QstyleSheet (QWidget a) (()) where
styleSheet x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_styleSheet cobj_x0
foreign import ccall "qtc_QWidget_styleSheet" qtc_QWidget_styleSheet :: Ptr (TQWidget a) -> IO (Ptr (TQString ()))
instance QtabletEvent (QWidget ()) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_tabletEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_tabletEvent_h" qtc_QWidget_tabletEvent_h :: Ptr (TQWidget a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent (QWidgetSc a) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_tabletEvent_h cobj_x0 cobj_x1
testAttribute :: QWidget a -> ((WidgetAttribute)) -> IO (Bool)
testAttribute x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_testAttribute cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QWidget_testAttribute" qtc_QWidget_testAttribute :: Ptr (TQWidget a) -> CLong -> IO CBool
instance QtoolTip (QWidget a) (()) where
toolTip x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_toolTip cobj_x0
foreign import ccall "qtc_QWidget_toolTip" qtc_QWidget_toolTip :: Ptr (TQWidget a) -> IO (Ptr (TQString ()))
topLevelWidget :: QWidget a -> (()) -> IO (QWidget ())
topLevelWidget x0 ()
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_topLevelWidget cobj_x0
foreign import ccall "qtc_QWidget_topLevelWidget" qtc_QWidget_topLevelWidget :: Ptr (TQWidget a) -> IO (Ptr (TQWidget ()))
underMouse :: QWidget a -> (()) -> IO (Bool)
underMouse x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_underMouse cobj_x0
foreign import ccall "qtc_QWidget_underMouse" qtc_QWidget_underMouse :: Ptr (TQWidget a) -> IO CBool
instance QunsetCursor (QWidget a) (()) where
unsetCursor x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_unsetCursor cobj_x0
foreign import ccall "qtc_QWidget_unsetCursor" qtc_QWidget_unsetCursor :: Ptr (TQWidget a) -> IO ()
unsetLayoutDirection :: QWidget a -> (()) -> IO ()
unsetLayoutDirection x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_unsetLayoutDirection cobj_x0
foreign import ccall "qtc_QWidget_unsetLayoutDirection" qtc_QWidget_unsetLayoutDirection :: Ptr (TQWidget a) -> IO ()
unsetLocale :: QWidget a -> (()) -> IO ()
unsetLocale x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_unsetLocale cobj_x0
foreign import ccall "qtc_QWidget_unsetLocale" qtc_QWidget_unsetLocale :: Ptr (TQWidget a) -> IO ()
instance Qupdate (QWidget a) (()) where
update x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_update cobj_x0
foreign import ccall "qtc_QWidget_update" qtc_QWidget_update :: Ptr (TQWidget a) -> IO ()
instance Qupdate (QWidget a) ((Int, Int, Int, Int)) where
update x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_update3 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QWidget_update3" qtc_QWidget_update3 :: Ptr (TQWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qqupdate (QWidget a) ((QRect t1)) where
qupdate x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_update2 cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_update2" qtc_QWidget_update2 :: Ptr (TQWidget a) -> Ptr (TQRect t1) -> IO ()
instance Qupdate (QWidget a) ((QRegion t1)) where
update x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_update1 cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_update1" qtc_QWidget_update1 :: Ptr (TQWidget a) -> Ptr (TQRegion t1) -> IO ()
instance Qupdate (QWidget a) ((Rect)) where
update x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QWidget_update2_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QWidget_update2_qth" qtc_QWidget_update2_qth :: Ptr (TQWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
updateGeometry :: QWidget a -> (()) -> IO ()
updateGeometry x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_updateGeometry cobj_x0
foreign import ccall "qtc_QWidget_updateGeometry" qtc_QWidget_updateGeometry :: Ptr (TQWidget a) -> IO ()
instance QupdateMicroFocus (QWidget ()) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_updateMicroFocus cobj_x0
foreign import ccall "qtc_QWidget_updateMicroFocus" qtc_QWidget_updateMicroFocus :: Ptr (TQWidget a) -> IO ()
instance QupdateMicroFocus (QWidgetSc a) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_updateMicroFocus cobj_x0
updatesEnabled :: QWidget a -> (()) -> IO (Bool)
updatesEnabled x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_updatesEnabled cobj_x0
foreign import ccall "qtc_QWidget_updatesEnabled" qtc_QWidget_updatesEnabled :: Ptr (TQWidget a) -> IO CBool
visibleRegion :: QWidget a -> (()) -> IO (QRegion ())
visibleRegion x0 ()
= withQRegionResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_visibleRegion cobj_x0
foreign import ccall "qtc_QWidget_visibleRegion" qtc_QWidget_visibleRegion :: Ptr (TQWidget a) -> IO (Ptr (TQRegion ()))
instance QwhatsThis (QWidget a) (()) where
whatsThis x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_whatsThis cobj_x0
foreign import ccall "qtc_QWidget_whatsThis" qtc_QWidget_whatsThis :: Ptr (TQWidget a) -> IO (Ptr (TQString ()))
instance QwheelEvent (QWidget ()) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_wheelEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_wheelEvent_h" qtc_QWidget_wheelEvent_h :: Ptr (TQWidget a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent (QWidgetSc a) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_wheelEvent_h cobj_x0 cobj_x1
instance Qqwidth (QWidget a) (()) (IO (Int)) where
qwidth x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_width cobj_x0
foreign import ccall "qtc_QWidget_width" qtc_QWidget_width :: Ptr (TQWidget a) -> IO CInt
winId :: QWidget a -> (()) -> IO (QVoid ())
winId x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_winId cobj_x0
foreign import ccall "qtc_QWidget_winId" qtc_QWidget_winId :: Ptr (TQWidget a) -> IO (Ptr (TQVoid ()))
instance Qwindow (QWidget a) (()) (IO (QWidget ())) where
window x0 ()
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_window cobj_x0
foreign import ccall "qtc_QWidget_window" qtc_QWidget_window :: Ptr (TQWidget a) -> IO (Ptr (TQWidget ()))
instance QwindowActivationChange (QWidget ()) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_windowActivationChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QWidget_windowActivationChange" qtc_QWidget_windowActivationChange :: Ptr (TQWidget a) -> CBool -> IO ()
instance QwindowActivationChange (QWidgetSc a) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_windowActivationChange cobj_x0 (toCBool x1)
windowFlags :: QWidget a -> (()) -> IO (WindowFlags)
windowFlags x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_windowFlags cobj_x0
foreign import ccall "qtc_QWidget_windowFlags" qtc_QWidget_windowFlags :: Ptr (TQWidget a) -> IO CLong
windowIcon :: QWidget a -> (()) -> IO (QIcon ())
windowIcon x0 ()
= withQIconResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_windowIcon cobj_x0
foreign import ccall "qtc_QWidget_windowIcon" qtc_QWidget_windowIcon :: Ptr (TQWidget a) -> IO (Ptr (TQIcon ()))
windowIconText :: QWidget a -> (()) -> IO (String)
windowIconText x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_windowIconText cobj_x0
foreign import ccall "qtc_QWidget_windowIconText" qtc_QWidget_windowIconText :: Ptr (TQWidget a) -> IO (Ptr (TQString ()))
windowModality :: QWidget a -> (()) -> IO (WindowModality)
windowModality x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_windowModality cobj_x0
foreign import ccall "qtc_QWidget_windowModality" qtc_QWidget_windowModality :: Ptr (TQWidget a) -> IO CLong
windowOpacity :: QWidget a -> (()) -> IO (Double)
windowOpacity x0 ()
= withDoubleResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_windowOpacity cobj_x0
foreign import ccall "qtc_QWidget_windowOpacity" qtc_QWidget_windowOpacity :: Ptr (TQWidget a) -> IO CDouble
windowRole :: QWidget a -> (()) -> IO (String)
windowRole x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_windowRole cobj_x0
foreign import ccall "qtc_QWidget_windowRole" qtc_QWidget_windowRole :: Ptr (TQWidget a) -> IO (Ptr (TQString ()))
windowState :: QWidget a -> (()) -> IO (WindowStates)
windowState x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_windowState cobj_x0
foreign import ccall "qtc_QWidget_windowState" qtc_QWidget_windowState :: Ptr (TQWidget a) -> IO CLong
windowTitle :: QWidget a -> (()) -> IO (String)
windowTitle x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_windowTitle cobj_x0
foreign import ccall "qtc_QWidget_windowTitle" qtc_QWidget_windowTitle :: Ptr (TQWidget a) -> IO (Ptr (TQString ()))
windowType :: QWidget a -> (()) -> IO (WindowType)
windowType x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_windowType cobj_x0
foreign import ccall "qtc_QWidget_windowType" qtc_QWidget_windowType :: Ptr (TQWidget a) -> IO CLong
instance Qqx (QWidget a) (()) (IO (Int)) where
qx x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_x cobj_x0
foreign import ccall "qtc_QWidget_x" qtc_QWidget_x :: Ptr (TQWidget a) -> IO CInt
instance Qqy (QWidget a) (()) (IO (Int)) where
qy x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_y cobj_x0
foreign import ccall "qtc_QWidget_y" qtc_QWidget_y :: Ptr (TQWidget a) -> IO CInt
qWidget_delete :: QWidget a -> IO ()
qWidget_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_delete cobj_x0
foreign import ccall "qtc_QWidget_delete" qtc_QWidget_delete :: Ptr (TQWidget a) -> IO ()
qWidget_deleteLater :: QWidget a -> IO ()
qWidget_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_deleteLater cobj_x0
foreign import ccall "qtc_QWidget_deleteLater" qtc_QWidget_deleteLater :: Ptr (TQWidget a) -> IO ()
instance QchildEvent (QWidget ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_childEvent" qtc_QWidget_childEvent :: Ptr (TQWidget a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QWidgetSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QWidget ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QWidget_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QWidget_connectNotify" qtc_QWidget_connectNotify :: Ptr (TQWidget a) -> CWString -> IO ()
instance QconnectNotify (QWidgetSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QWidget_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QWidget ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_customEvent" qtc_QWidget_customEvent :: Ptr (TQWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QWidgetSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QWidget ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QWidget_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QWidget_disconnectNotify" qtc_QWidget_disconnectNotify :: Ptr (TQWidget a) -> CWString -> IO ()
instance QdisconnectNotify (QWidgetSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QWidget_disconnectNotify cobj_x0 cstr_x1
instance QeventFilter (QWidget ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QWidget_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QWidget_eventFilter_h" qtc_QWidget_eventFilter_h :: Ptr (TQWidget a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QWidgetSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QWidget_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QWidget ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QWidget_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QWidget_receivers" qtc_QWidget_receivers :: Ptr (TQWidget a) -> CWString -> IO CInt
instance Qreceivers (QWidgetSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QWidget_receivers cobj_x0 cstr_x1
instance Qsender (QWidget ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_sender cobj_x0
foreign import ccall "qtc_QWidget_sender" qtc_QWidget_sender :: Ptr (TQWidget a) -> IO (Ptr (TQObject ()))
instance Qsender (QWidgetSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QWidget_sender cobj_x0
instance QtimerEvent (QWidget ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QWidget_timerEvent" qtc_QWidget_timerEvent :: Ptr (TQWidget a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QWidgetSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QWidget_timerEvent cobj_x0 cobj_x1
|
keera-studios/hsQt
|
Qtc/Gui/QWidget.hs
|
bsd-2-clause
| 118,667
| 0
| 14
| 20,107
| 40,677
| 20,564
| 20,113
| -1
| -1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TypeOperators #-}
module IdentityServer where
import Control.Monad.Trans.Except
import Control.Monad.IO.Class
import Data.Aeson
import GHC.Generics
import Network.Wai
import Network.Wai.Handler.Warp
import Network.Info
import Servant
import Servant.API
import Servant.Client
import System.IO
import CommonServer
import CommonServerApi
--import CommonServerApiClient
identity :: Identity
identity = Identity "localhost" "8081" CommonServer.IdentityServer
identityApi :: Proxy IdentityApi
identityApi = Proxy
identityServer :: Server IdentityApi
identityServer =
submit :<|>
getNext :<|>
getAll :<|>
IdentityServer.getPort :<|>
report
identityApp :: Application
identityApp = serve identityApi identityServer
mkIdentityServer :: IO()
mkIdentityServer = run (read (port identity)::Int) identityApp
identities :: [Identity]
identities = [identity]
getPortsRecursive :: Identity -> [Int] -> [Int]
getPortsRecursive id is = return (is ++ (read (port id)::Int)
getPorts :: [Int]
getPorts = map (port Identity) identities
submit :: Identity -> ApiHandler CommonServer.Response
submit i = do
identities ++ [i]
return (Response IdentityReceived identity)
getNext :: ServerType -> ApiHandler Identity
getNext st = liftIO (head (filter (\n -> (serverType n) == st) identities))
getAll :: ServerType -> ApiHandler [Identity]
getAll st = (liftIO (filter (\n -> (serverType n) == st) identities))
getPort :: ServerType -> ApiHandler Int
getPort st = return (maximum getPorts) + 1
report :: Identity -> ApiHandler CommonServer.Response
report i = do
result <- i `elem` identities
if result then return (Response IdentityFound i)
else return (Response IdentityNotFound i)
|
Coggroach/Gluon
|
.stack-work/intero/intero10192Yq0.hs
|
bsd-3-clause
| 1,958
| 1
| 14
| 427
| 540
| 290
| 250
| -1
| -1
|
module Environment
(
module Environment.Internal,
AABB(..),
HasAABB(..),
AgentType(..),
AgentClass(..),
updateEnvironment,
newAgent,
runGame,
runMain,
addAgent
) where
import Control.Lens
import Control.Monad.Identity
import Control.Monad.State
import Control.Monad.Reader
import Control.Monad.RWS
import Graphics.UI.SDL.Events
import Graphics.UI.SDL.Keysym
import Graphics.UI.SDL.Time
import Data.Map as Map
import Config
import Environment.Internal
import Collision as Quad
import Assets.Internal
import MonadTime
updateEnvironment :: Float -> GameMonad ()
updateEnvironment dt = do
agents' <- use $ environment.agents
forM_ (Quad.toList agents') $ \(Agent ident oldAgent) -> do
newAgent <- runAgent ident oldAgent $ do
live dt
use agent
environment.agents %= move ident oldAgent newAgent
processInputs :: MainMonad ()
processInputs = do
event <- liftIO pollEvent
case event of
NoEvent -> return ()
KeyDown keySym -> do
changeInput keySym True
processInputs
KeyUp keySym -> do
changeInput keySym False
processInputs
_ -> processInputs
changeInput :: Keysym -> Bool -> MainMonad ()
changeInput key value = do
case symKey key of
SDLK_UP -> inputs.up .= value
SDLK_DOWN -> inputs.down .= value
SDLK_RIGHT -> inputs.right .= value
SDLK_LEFT -> inputs.left .= value
SDLK_w -> inputs.shot .= value
SDLK_x -> inputs.laser .= value
SDLK_ESCAPE -> inputs.pause .= value
_ -> return ()
uniqueID :: (MonadState e m, EnvironmentState e) => m Int
uniqueID = do
newId <- use $ environment.currentId
environment.currentId += 1
return newId
newAgent :: (MonadState e m, EnvironmentState e, AgentClass a) => a -> m Agent
newAgent agent = do
ident <- uniqueID
return $ Agent ident agent
runGame :: GameMonad a -> MainMonad a
runGame gameAction = do
processInputs
inputs' <- use inputs
assets' <- use assets
time <- getTimeMillis
environment.currentTime .= time
environment' <- use environment
let
reader = GameReader inputs' assets'
initGameState = GameState environment'
(res,gameState,()) = runRWS gameAction reader initGameState
environment .= gameState^.environment
return res
runMain :: MainMonad a -> IO a
runMain mainAction = do
time <- getTicks
let
initInputs = Inputs False False False False False False False
initEnv =
Environment
(Quad.empty screenAABB qTreeHeight)
0
(fromIntegral time)
initAssets = Assets Map.empty
initState = MainState initEnv initInputs initAssets
evalStateT mainAction initState
runAgent :: (AgentClass a) => Int -> a -> AgentMonad a b -> GameMonad b
runAgent ident agent agentAction = do
environment' <- use environment
inputs' <- query getInputs
assets' <- query getAssets
let
initialState = AgentState environment' agent
reader = AgentReader inputs' assets' ident
(result,finalState,()) = runRWS agentAction reader initialState
environment .= finalState^.environment
return result
addAgent :: (MonadState e m, EnvironmentState e) => Agent -> m ()
addAgent agent =
environment.agents %= Quad.insert agent
|
alexisVallet/haskell-shmup
|
Environment.hs
|
bsd-3-clause
| 3,261
| 0
| 15
| 740
| 1,025
| 509
| 516
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
module Funk.CLI
( getPending
, handleInit
, handlePlaying
) where
import Control.Monad (when, unless)
import Data.Aeson (encode, decode)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.UTF8 as UTF8
import Data.Maybe (fromJust)
import Data.Time.Clock.POSIX (getPOSIXTime)
import qualified System.Directory as D
import Funk.LastFM
import qualified Funk.Track as T
confDir :: IO FilePath
confDir = D.getXdgDirectory D.XdgConfig "funk"
confFile :: String -> IO String
confFile s = do
dir <- confDir
return $ dir ++ "/" ++ s
getTimestamp :: IO Integer
getTimestamp = round <$> getPOSIXTime
saveSessionKey :: String -> IO ()
saveSessionKey key = do
file <- confFile "auth"
writeFile file key
getSessionKey :: IO (Maybe B.ByteString)
getSessionKey = do
file <- confFile "auth"
fileExists <- D.doesFileExist file
if fileExists
then fmap (Just . UTF8.fromString) (readFile file)
else return Nothing
getPending :: IO (Maybe T.PlayedTrack)
getPending = do
file <- confFile "pending"
fileExists <- D.doesFileExist file
if fileExists
then decode <$> (L.readFile file)
else return Nothing
setPending :: T.PlayedTrack -> IO ()
setPending pt = do
current <- getPending
unless (Just pt == current) $ do
file <- confFile "pending"
L.writeFile file (encode pt)
scrobblePending :: B.ByteString -> T.PlayedTrack -> IO ()
scrobblePending sk pt = do
pending <- getPending
when (shouldScrobble pending pt) (scrobble sk (fromJust pending))
where
shouldScrobble (Just (T.PlayedTrack ts1 t1)) (T.PlayedTrack ts2 t2) =
ts2 - ts1 >= (T.duration t1) - 10
shouldScrobble _ _ = False
handleInit = do
confDir >>= D.createDirectoryIfMissing True
putStr "Username: "
username <- getLine
putStr "Password: "
password <- getLine
getSession username password >>= \case
Just s -> saveSessionKey s
_ -> putStrLn "Fail!"
handlePlaying :: [String] -> IO ()
handlePlaying args = do
sk <- getSessionKey
let track = T.fromList $ pairs args
case (sk, track) of
(Just sk, Just track) -> do
ts <- getTimestamp
let pt = T.PlayedTrack ts track
scrobblePending sk pt
setPending pt
(Just _, Nothing) -> putStrLn "Bad track!"
_ -> putStrLn "No session key"
where
pairs (k:v:t) = (k, v) : pairs t
pairs _ = []
|
apa512/funk
|
src/Funk/CLI.hs
|
bsd-3-clause
| 2,446
| 0
| 16
| 507
| 862
| 432
| 430
| 78
| 4
|
module Language.C.Syntax.ManualBinaryInstances where
import Control.Monad
import Data.Binary
import Language.C.Data.Ident
import Language.C.Data.Name
import Language.C.Data.Node
import Language.C.Data.Position
import Language.C.Syntax.Constants
instance Binary Ident where
put (Ident name uid inf) = put name >> put uid >> put inf
get = liftM3 Ident get get get
instance Binary NodeInfo where
put (OnlyPos p l) = put p >> put l >> put (Nothing :: Maybe Name)
put (NodeInfo p l n) = put p >> put l >> put (Just n)
get = liftM3 mkNode get get get
where mkNode p l mb = maybe (OnlyPos p l) (NodeInfo p l) mb
instance Binary Position where
put p
| isNoPos p = putWord8 0
| isBuiltinPos p = putWord8 1
| isInternalPos p = putWord8 2
| isSourcePos p = do putWord8 3
put (posOffset p)
put (posFile p)
put (posRow p)
put (posColumn p)
| otherwise = fail "impossible"
get = do _tag <- getWord8
case _tag of
0 -> return nopos
1 -> return builtinPos
2 -> return internalPos
3 -> liftM4 position get get get get
_ -> fail "no parse"
instance Binary Name where
put p = put (nameId p)
get = liftM Name get
instance Binary CInteger where
put (CInteger i r fs) = put i >> put r >> put fs
get = liftM3 CInteger get get get
instance Binary CIntFlag where
put FlagUnsigned = putWord8 0
put FlagLong = putWord8 1
put FlagLongLong = putWord8 2
put FlagImag = putWord8 3
get = do
tag_ <- getWord8
case tag_ of
0 -> return FlagUnsigned
1 -> return FlagLong
2 -> return FlagLongLong
3 -> return FlagImag
_ -> fail "no parse"
instance Binary CIntRepr where
put DecRepr = putWord8 0
put HexRepr = putWord8 1
put OctalRepr = putWord8 2
get = do
tag_ <- getWord8
case tag_ of
0 -> return DecRepr
1 -> return HexRepr
2 -> return OctalRepr
_ -> fail "no parse"
instance (Binary a) => Binary (Flags a) where
put (Flags a) = put a
get = get >>= \a -> return (Flags a)
instance Binary CChar where
put (CChar c b) = putWord8 0 >> put c >> put b
put (CChars cs b) = putWord8 1 >> put cs >> put b
get = do
tag_ <- getWord8
case tag_ of
0 -> liftM2 CChar get get
1 -> liftM2 CChars get get
_ -> fail "no parse"
instance Binary CFloat where
put (CFloat s) = put s
get = liftM CFloat get
instance Binary CString where
put (CString s b) = put s >> put b
get = liftM2 CString get get
|
atomb/language-c-binary
|
Language/C/Syntax/ManualBinaryInstances.hs
|
bsd-3-clause
| 2,641
| 0
| 11
| 831
| 1,036
| 492
| 544
| 82
| 0
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
-- | Use "runhaskell Setup.hs test" or "cabal test" to run these tests.
module Main where
import Language.Haskell.GHC.ExactPrint.Utils ( showGhc )
-- import qualified FastString as GHC
-- import qualified GHC as GHC
-- import qualified Data.Generics as SYB
-- import qualified GHC.SYB.Utils as SYB
import Control.Monad
import System.Directory
import System.FilePath
import System.IO
import System.Exit
import Data.List
import System.IO.Silently
import Test.Common
import Test.Transform
import Test.HUnit
-- import Debug.Trace
-- ---------------------------------------------------------------------
data GHCVersion = GHC710 | GHC8 deriving (Eq, Ord, Show)
ghcVersion :: GHCVersion
ghcVersion =
#if __GLASGOW_HASKELL__ >= 711
GHC8
#else
GHC710
#endif
-- | Directories to automatically find roundtrip tests
testDirs :: [FilePath]
testDirs =
case ghcVersion of
GHC710 -> ["ghc710-only","ghc710"]
GHC8 -> ["ghc710", "ghc8"]
-- ---------------------------------------------------------------------
main :: IO ()
main = hSilence [stderr] $ do
print ghcVersion
tests <- mkTests
cnts <- fst <$> runTestText (putTextToHandle stdout True) tests
putStrLn $ show cnts
if errors cnts > 0 || failures cnts > 0
then exitFailure
else return () -- exitSuccess
transform :: IO ()
transform = hSilence [stderr] $ do
cnts <- fst <$> runTestText (putTextToHandle stdout True) transformTests
putStrLn $ show cnts
if errors cnts > 0 || failures cnts > 0
then exitFailure
else return () -- exitSuccess
-- ---------------------------------------------------------------------
findTests :: IO Test
findTests = testList "Round-trip tests" <$> mapM findTestsDir testDirs
listTests :: IO ()
listTests = do
let
ftd dir = do
let fp = testPrefix </> dir
fs <- getDirectoryContents fp
let testFiles = sort $ filter (".hs" `isSuffixOf`) fs
return (zip [0::Integer ..] testFiles)
files <- mapM ftd testDirs
putStrLn $ "round trip tests:" ++ show (zip testDirs files)
findTestsDir :: FilePath -> IO Test
findTestsDir dir = do
let fp = testPrefix </> dir
fs <- getDirectoryContents fp
let testFiles = sort $ filter (".hs" `isSuffixOf`) fs
return $ testList dir (map (mkParserTest dir) testFiles)
mkTests :: IO Test
mkTests = do
-- listTests
roundTripTests <- findTests
return $ TestList [internalTests,roundTripTests, transformTests, failingTests]
-- Tests that will fail until https://phabricator.haskell.org/D907 lands in a
-- future GHC
failingTests :: Test
failingTests = testList "Failing tests"
[
-- Tests requiring future GHC modifications
mkTestModBad "InfixOperator.hs"
#if __GLASGOW_HASKELL__ > 710
, mkTestModBad "overloadedlabelsrun04.hs"
#else
, mkTestModBad "UnicodeSyntax.hs"
, mkTestModBad "UnicodeRules.hs"
, mkTestModBad "Deprecation.hs"
, mkTestModBad "MultiLineWarningPragma.hs"
#endif
]
mkParserTest :: FilePath -> FilePath -> Test
mkParserTest dir fp =
let basename = testPrefix </> dir </> fp
writeFailure = writeFile (basename <.> "out")
writeHsPP = writeFile (basename <.> "hspp")
writeIncons s = writeFile (basename <.> "incons") (showGhc s)
in
TestCase (do r <- either (\(ParseFailure _ s) -> error (s ++ basename)) id
<$> roundTripTest basename
writeFailure (debugTxt r)
forM_ (inconsistent r) writeIncons
forM_ (cppStatus r) writeHsPP
assertBool fp (status r == Success))
-- ---------------------------------------------------------------------
formatTT :: ([([Char], Bool)], [([Char], Bool)]) -> IO ()
formatTT (ts, fs) = do
when (not . null $ tail ts) (do
putStrLn "Pass"
mapM_ (putStrLn . fst) (tail ts)
)
when (not . null $ fs) (do
putStrLn "Fail"
mapM_ (putStrLn . fst) fs)
tt' :: IO (Counts,Int)
tt' = runTestText (putTextToHandle stdout True) $ TestList [
-- mkParserTest "ghc710" "Unicode.hs"
-- , mkParserTest "ghc8" "BundleExport.hs"
-- , mkParserTest "ghc8" "ExportSyntax.hs"
-- , mkParserTest "ghc8" "T10689a.hs"
-- , mkParserTest "ghc8" "Test10313.hs"
-- , mkParserTest "ghc8" "Test11018.hs"
-- , mkParserTest "ghc8" "determ004.hs"
-- , mkParserTest "ghc8" "export-class.hs"
-- , mkParserTest "ghc8" "export-syntax.hs"
-- , mkParserTest "ghc8" "export-type.hs"
-- , mkParserTest "ghc8" "overloadedlabelsrun04.hs"
-- mkParserTest "ghc710" "RdrNames.hs"
mkParserTest "ghc710" "Process1.hs"
-- mkParserTest "ghc8" "T10620.hs"
-- mkParserTest "ghc8" "Vta1.hs"
-- , mkParserTest "ghc8" "Vta2.hs"
-- , mkParserTest "failing" "Deprecation.hs"
-- , mkParserTest "failing" "MultiLineWarningPragma.hs"
-- , mkParserTest "failing" "UnicodeRules.hs"
-- , mkParserTest "failing" "UnicodeSyntax.hs"
]
testsTT :: Test
testsTT = TestList
[
mkParserTest "ghc710" "Cpp.hs"
, mkParserTest "ghc710" "DroppedDoSpace.hs"
]
tt :: IO ()
-- tt = hSilence [stderr] $ do
tt = do
cnts <- fst <$> runTestText (putTextToHandle stdout True) testsTT
putStrLn $ show cnts
if errors cnts > 0 || failures cnts > 0
then exitFailure
else return () -- exitSuccess
-- ---------------------------------------------------------------------
ii :: IO ()
ii = do
cnts <- fst <$> runTestText (putTextToHandle stdout True) internalTests
putStrLn $ show cnts
if errors cnts > 0 || failures cnts > 0
then exitFailure
else return () -- exitSuccess
internalTests :: Test
internalTests = testList "Internal tests"
[
-- testCleanupOneLine
]
{-
testCleanupOneLine :: Test
testCleanupOneLine = do
let
makeCase n = (show n
,(T.replicate n " ") <> "\t|" <> T.replicate n " " <> "\t"
,(T.replicate 8 " " <> "|"))
mkTest n = TestCase $ assertEqual name outp (cleanupOneLine inp)
where (name,inp,outp) = makeCase n
testList "cleanupOneLine" $ map mkTest [1..7]
-}
-- ---------------------------------------------------------------------
pwd :: IO FilePath
pwd = getCurrentDirectory
cd :: FilePath -> IO ()
cd = setCurrentDirectory
|
mpickering/ghc-exactprint
|
tests/Test.hs
|
bsd-3-clause
| 6,330
| 0
| 18
| 1,333
| 1,361
| 709
| 652
| 120
| 2
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TemplateHaskell #-}
module Test.Delorean.Local.Time where
import Delorean.Local.Time
import P
import System.IO
import Test.Delorean.Arbitrary ()
import Test.Delorean.ParserCheck
import Test.QuickCheck
prop_roundTripHourOfDay :: HourOfDay -> Property
prop_roundTripHourOfDay h =
(hourOfDayFromInt . hourOfDayToInt) h === pure h
prop_roundTripMinuteOfHour :: MinuteOfHour -> Property
prop_roundTripMinuteOfHour m =
(minuteOfHourFromInt . minuteOfHourToInt) m === pure m
prop_roundTripSecondOfMinute :: SecondOfMinute -> Property
prop_roundTripSecondOfMinute s =
(secondOfMinuteFromInt . secondOfMinuteToInt) s === pure s
prop_midnight :: Property
prop_midnight =
pure midnight === hourOfDayFromInt 0
prop_symmetricMinuteOfHour :: MinuteOfHour -> Property
prop_symmetricMinuteOfHour =
symmetric minuteOfHourParser renderMinuteOfHour
prop_symmetricTime :: Time -> Property
prop_symmetricTime =
symmetric timeParser renderTime
prop_parseMinuteOfHour :: MinuteOfHour -> Property
prop_parseMinuteOfHour =
parserAlias minuteOfHourParser renderMinuteOfHour parseMinuteOfHour
prop_parseTime :: Time -> Property
prop_parseTime =
parserAlias timeParser renderTime parseTime
return []
tests :: IO Bool
tests = $quickCheckAll
|
ambiata/delorean
|
test/Test/Delorean/Local/Time.hs
|
bsd-3-clause
| 1,349
| 0
| 8
| 219
| 268
| 143
| 125
| 36
| 1
|
module Main where
import Control.Monad
import Data.List
import Debug.Trace
import System.Environment
import System.Exit
import System.IO
main :: IO ()
main = do
args <- getArgs
when (length args /= 1) $ die "Usage: Solve3 <file>"
contents <- lines `fmap` readFile (args !! 0)
let probs = map (\l -> map readi $ words l) $ tail contents
solns = map solve probs
mapM_ printSoln $ zip [1..] solns
where
readi :: String -> Int
readi = read
printSoln :: (Int, Int) -> IO ()
printSoln (n, soln) = putStrLn $ "Case #" ++ show n ++ ": " ++ show soln
die :: String -> IO ()
die err = do
hPutStrLn stderr err
exitFailure
solve :: [Int] -> Int
solve [min, max] = go min 0
where
go i count
| i > max = count
| otherwise =
let rs = filter (\x -> x > i && x <= max) $ rotations i
in go (i + 1) (count + length rs)
solve _ = error "Bad input line! too many numbers"
-- This can give bad rotations (i.e 120 -> 012 -> 12) but
-- we just filter numbers outside the min range so this is OK.
rotations :: Int -> [Int]
rotations i =
let s = show i
rotate n = let (x, y) = splitAt n s
in read (y ++ x)
in tail $ nub $ map rotate [0..(length s - 1)]
|
dterei/Scraps
|
codeJam2012/q3/Solve3.hs
|
bsd-3-clause
| 1,273
| 0
| 18
| 386
| 513
| 257
| 256
| 37
| 1
|
{-# LANGUAGE CPP, ForeignFunctionInterface #-}
{-# OPTIONS_GHC -fglasgow-exts #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : Numeric.LinearAlgebra.Internal
-- Copyright : Copyright (c) 2008, Patrick Perry <patperry@stanford.edu>
-- License : BSD3
-- Maintainer : Patrick Perry <patperry@stanford.edu>
-- Stability : experimental
--
module Numeric.LinearAlgebra.Internal (
clearArray,
bzero,
inlinePerformIO,
checkedRow,
checkedCol,
checkedDiag,
checkedSubmatrix,
checkMatMatOp,
checkMatVecMult,
checkMatMatMult,
checkMatVecMultAdd,
checkMatMatMultAdd,
checkMatVecSolv,
checkMatMatSolv,
checkMatVecSolvTo,
checkMatMatSolvTo,
checkSquare,
checkFat,
checkTall,
checkBinaryOp,
checkTernaryOp,
diagStart,
diagLen,
) where
import Foreign ( Ptr, Storable, castPtr, sizeOf )
import Foreign.C.Types ( CSize )
import Text.Printf ( printf )
#if defined(__GLASGOW_HASKELL__)
import GHC.Base ( realWorld# )
import GHC.IO ( IO(IO) )
#else
import System.IO.Unsafe ( unsafePerformIO )
#endif
clearArray :: Storable e => Ptr e -> Int -> IO ()
clearArray = clearArray' undefined
where
clearArray' :: Storable e => e -> Ptr e -> Int -> IO ()
clearArray' e ptr n =
let nbytes = fromIntegral (n * sizeOf e)
in do
bzero ptr nbytes
{-# INLINE clearArray #-}
bzero :: Ptr a -> Int -> IO ()
bzero ptr n =
let ptr' = castPtr ptr
n' = fromIntegral n
in bzero_ ptr' n'
foreign import ccall "strings.h bzero"
bzero_ :: Ptr () -> CSize -> IO ()
inlinePerformIO :: IO a -> a
#if defined(__GLASGOW_HASKELL__)
inlinePerformIO (IO m) = case m realWorld# of (# _, r #) -> r
#else
inlinePerformIO = unsafePerformIO
#endif
{-# INLINE inlinePerformIO #-}
checkedRow :: (Int,Int) -> (Int -> v) -> Int -> v
checkedRow (m,n) row i
| i < 0 || i >= m =
error $ printf
"Error in row index. Tried to get row `%d' in a matrix with shape `(%d,%d)'" i m n
| otherwise =
row i
checkedCol :: (Int,Int) -> (Int -> v) -> Int -> v
checkedCol (m,n) col j
| j < 0 || j >= n =
error $ printf
"Error in column index. Tried to get column `%d' in a matrix with shape `(%d,%d)'" j m n
| otherwise =
col j
checkedDiag :: (Int,Int) -> (Int -> v) -> Int -> v
checkedDiag (m,n) diag i
| i < 0 && negate i >= m =
error $ printf
"Tried to get sub-diagonal `%d' of a matrix with shape `(%d,%d)'" (negate i) m n
| i > 0 && i >= n =
error $ printf
"Tried to get super-diagonal `%d' of a matrix with shape `(%d,%d)'" i m n
| otherwise =
diag i
diagStart :: Int -> (Int,Int)
diagStart i
| i <= 0 =
(negate i, 0)
| otherwise =
(0, i)
diagLen :: (Int,Int) -> Int -> Int
diagLen (m,n) i
| m <= n =
if i <= 0
then max (m + i) 0
else min (n - i) m
| otherwise =
if i > 0
then max (n - i) 0
else min (m + i) n
checkedSubmatrix :: (Int,Int) -> ((Int,Int) -> (Int,Int) -> a) -> (Int,Int) -> (Int,Int) -> a
checkedSubmatrix (m,n) sub (i,j) (m',n')
| or [ i < 0, m' < 0, i + m' > m,
j < 0, n' < 0, j + n' > n ] =
error $ printf ("tried to create submatrix of a `(%d,%d)' matrix " ++
" using offset `(%d,%d)' and shape (%d,%d)") m n i j m' n'
| otherwise =
sub (i,j) (m',n')
checkMatMatOp :: String -> (Int,Int) -> (Int,Int) -> a -> a
checkMatMatOp name mn1 mn2
| mn1 /= mn2 =
error $ printf
("%s: x and y have different shapes. x has shape `%s',"
++ " and y has shape `%s'") name (show mn1) (show mn2)
| otherwise = id
checkMatVecMult :: (Int,Int) -> Int -> a -> a
checkMatVecMult mn n
| snd mn /= n =
error $ printf
("Tried to multiply a matrix with shape `%s' by a vector of dimension `%d'")
(show mn) n
| otherwise = id
checkMatMatMult :: (Int,Int) -> (Int,Int) -> a -> a
checkMatMatMult mk kn
| snd mk /= fst kn =
error $ printf
("Tried to multiply a matrix with shape `%s' by a matrix with shape `%s'")
(show mk) (show kn)
| otherwise = id
checkMatVecMultAdd :: (Int,Int) -> Int -> Int -> a -> a
checkMatVecMultAdd mn n m
| snd mn /= n =
error $ printf
("Tried to multiply a matrix with shape `%s' by a vector of dimension `%d'")
(show mn) n
| fst mn /= m =
error $ printf
("Tried to add a vector of dimension `%d' to a vector of dimension `%d'")
(fst mn) m
| otherwise = id
checkMatMatMultAdd :: (Int,Int) -> (Int,Int) -> (Int,Int) -> a -> a
checkMatMatMultAdd mk kn mn
| snd mk /= fst kn =
error $ printf
("Tried to multiply a matrix with shape `%s' by a matrix with shape `%s'")
(show mk) (show kn)
| (fst mk, snd kn) /= mn =
error $ printf
("Tried to add a matrix with shape `%s' to a matrix with shape `%s'")
(show (fst mk, snd kn)) (show mn)
| otherwise = id
checkMatVecSolv :: (Int,Int) -> Int -> a -> a
checkMatVecSolv mn m
| fst mn /= m =
error $ printf
("Tried to solve a matrix with shape `%s' for a vector of dimension `%d'")
(show mn) m
| otherwise = id
checkMatVecSolvTo :: (Int,Int) -> Int -> Int -> a -> a
checkMatVecSolvTo mn m n
| fst mn /= m =
error $ printf
("Tried to solve a matrix with shape `%s' for a vector of dimension `%d'")
(show mn) m
| snd mn /= n =
error $ printf
("Tried to store a vector of dimension `%s' in a vector of dimension `%d'")
(show $ snd mn) n
| otherwise = id
checkMatMatSolv :: (Int,Int) -> (Int,Int) -> a -> a
checkMatMatSolv mn mk
| fst mn /= fst mk =
error $ printf
("Tried to solve a matrix with shape `%s' for a matrix with shape `%s'")
(show mn) (show mk)
| otherwise = id
checkMatMatSolvTo :: (Int,Int) -> (Int,Int) -> (Int,Int) -> a -> a
checkMatMatSolvTo mk mn kn
| fst mn /= fst mk =
error $ printf
("Tried to solve a matrix with shape `%s' for a matrix with shape `%s'")
(show mk) (show mn)
| kn /= (snd mk, snd mn) =
error $ printf
("Tried to store a matrix with shape `%s' in a matrix with shape `%s'")
(show (snd mk, snd mn)) (show kn)
| otherwise = id
checkSquare :: String -> (Int,Int) -> a -> a
checkSquare str (m,n)
| m /= n =
error $ printf
"%s <matrix of shape (%d,%d)>: matrix shape must be square."
str m n
| otherwise = id
checkFat :: String -> (Int,Int) -> a -> a
checkFat str (m,n)
| m > n =
error $ printf
"%s <matrix of shape (%d,%d)>: matrix must have at least as many columns as rows."
str m n
| otherwise = id
checkTall :: String -> (Int,Int) -> a -> a
checkTall str (m,n)
| m < n =
error $ printf
"%s <matrix of shape (%d,%d)>: matrix must have at least as many rows as columns."
str m n
| otherwise = id
checkBinaryOp :: (Eq i, Show i) => i -> i -> a -> a
checkBinaryOp m n
| m /= n =
error $ printf
("Shapes in binary operation do not match. "
++ " First operand has shape `%s' and second has shapw `%s'.")
(show m)
(show n)
| otherwise = id
{-# INLINE checkBinaryOp #-}
checkTernaryOp :: (Eq i, Show i) => i -> i -> i -> a -> a
checkTernaryOp l m n
| l == m && l == n = id
| otherwise =
error $ printf
("Shapes in ternary operation do not match. "
++ " First operand has shape `%s', second has shapw `%s',"
++ " and third has shape `%s'.")
(show l)
(show m)
(show n)
{-# INLINE checkTernaryOp #-}
|
patperry/hs-linear-algebra
|
lib/Numeric/LinearAlgebra/Internal.hs
|
bsd-3-clause
| 8,174
| 0
| 14
| 2,720
| 2,527
| 1,304
| 1,223
| 219
| 3
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
module Bead.Controller.UserStories where
import Bead.Domain.Entities hiding (name, uid)
import qualified Bead.Domain.Entities as Entity (uid)
import qualified Bead.Domain.Entity.Assignment as Assignment
import qualified Bead.Domain.Entity.Assessment as Assessment
import qualified Bead.Domain.Entity.Notification as Notification
import Bead.Domain.Relationships
import Bead.Domain.RolePermission (permission)
import Bead.Controller.ServiceContext
import Bead.Controller.Logging as L
import Bead.Controller.Pages as P hiding (modifyEvaluation,modifyAssessment)
import Bead.Persistence.Persist (Persist)
import qualified Bead.Persistence.Persist as Persist
import qualified Bead.Persistence.Relations as Persist
import qualified Bead.Persistence.Guards as Persist
import Bead.View.Translation
import Control.Lens (_1, view)
import Control.Applicative
import Control.Exception
import Control.Monad hiding (guard)
import Control.Monad.Error (Error(..))
import qualified Control.Monad.State as CMS
import qualified Control.Monad.Error as CME
import qualified Control.Monad.Reader as CMR
import Control.Monad.Trans
import Prelude hiding (log, userError)
import Data.Hashable
import Data.Function (on)
import Data.List (nub, sortBy, (\\))
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (catMaybes)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.String
import Data.Time (UTCTime(..), getCurrentTime)
import Numeric (showHex)
import Text.Printf (printf)
-- User error can be a message that need to be displayed, or
-- a parametrized message with a string parameter that needs
-- to be resolved in the place where the message is rendered
newtype UserError = UserError TransMsg
deriving (Show)
-- Template method for the UserError functions
userErrorCata f (UserError t) = f t
-- Creates a user error that contains a non-parametrized message
userError :: Translation String -> UserError
userError = UserError . TransMsg
-- Creates a user error that contains a parametrized message, with one parameter
userParamError :: Translation String -> String -> UserError
userParamError t p = UserError (TransPrmMsg t p)
-- Creates a user error that contains a parametrized message, with 2 parameters
userPrm2Error :: Translation String -> String -> String -> UserError
userPrm2Error t p1 p2 = UserError (TransPrm2Msg t p1 p2)
-- Creates a user error that contains a parametrized message, with 3 parameters
userPrm3Error :: Translation String -> String -> String -> String -> UserError
userPrm3Error t p1 p2 p3 = UserError (TransPrm3Msg t p1 p2 p3)
-- Translates the given user error with the given translation function,
-- applying the parameters if necessary to the parametrized messages
translateUserError :: (Translation String -> String) -> UserError -> String
translateUserError = userErrorCata . translateMessage
instance Error UserError where
noMsg = userError (msg_UserStoryError_UnknownError "Unknown Error: No message.")
strMsg m = userParamError (msg_UserStoryError_Message "Some error happened: %s") m
-- The User Story Context contains a service context and the localization transformation.
-- The service context is used for user manipulation.
-- The localization is used for translation of the messages that will be stored in
-- the persistence layer
type UserStoryContext = (ServiceContext, I18N)
newtype UserStory a = UserStory {
unStory :: CMR.ReaderT UserStoryContext (CMS.StateT UserState (CME.ErrorT UserError IO)) a
} deriving (Monad, CMS.MonadState UserState
, CME.MonadError UserError
, CMR.MonadReader UserStoryContext
, Functor
, Applicative
, MonadIO)
runUserStory
:: ServiceContext
-> I18N
-> UserState
-> UserStory a
-> IO (Either UserError (a, UserState))
runUserStory context i18n userState
= CME.runErrorT
. flip CMS.runStateT userState
. flip CMR.runReaderT (context,i18n)
. unStory
-- * High level user stories
-- | The user logs in with a given username and password
-- QUESTION: Is there multiple login for the given user?
-- ANSWER: No, the user can log in once at a time
login :: Username -> String -> UserStory ()
login username token = do
withUsername username $ \uname ->
logMessage INFO $ concat [uname, " is trying to login, with session ", token, " ."]
usrContainer <- asksUserContainer
validUser <- persistence $ Persist.doesUserExist username
notLoggedIn <- liftIO $ isUserLoggedIn usrContainer (userToken (username, token))
case (validUser, notLoggedIn) of
(True, False) -> do
loadUserData username token home'
s <- userState
liftIO $ userLogsIn usrContainer (userToken s) s
(True , True) -> errorPage . userError $ msg_UserStoryError_SameUserIsLoggedIn "This user is logged in somewhere else."
(False, _) -> errorPage . userError $ msg_UserStoryError_InvalidUsernameOrPassword "Invalid username or password."
where
home' = home ()
-- | The user logs out
logout :: UserStory ()
logout = do
state <- userState
users <- asksUserContainer
liftIO $ userLogsOut users (userToken state)
CMS.put userNotLoggedIn
doesUserExist :: Username -> UserStory Bool
doesUserExist u = logAction INFO ("searches after user " ++ show u) $ do
authorize P_Open P_User
persistence $ Persist.doesUserExist u
-- | The user navigates to the next page
changePage :: P.PageDesc -> UserStory ()
changePage p = do
authorize P_Open (pageAsPermObj p)
changeUserState $ \userState -> userState { page = p }
where
pageAsPermObj p
| isAdministration p = P_AdminPage
| otherwise = P_PlainPage
-- | The authorized user creates a new user
createUser :: User -> UserStory ()
createUser newUser = do
authorize P_Create P_User
persistence $ Persist.saveUser newUser
logger <- asksLogger
liftIO $ log logger INFO $ "User is created: " ++ show (u_username newUser)
-- Updates the timezone of the current user
setTimeZone :: TimeZoneName -> UserStory ()
setTimeZone tz = do
changeUserState $ \userState -> userState { timezone = tz }
putStatusMessage $ msg_UserStory_SetTimeZone "The time zone has been set."
-- Updates the current user's full name, timezone and language in the persistence layer
changeUserDetails :: String -> TimeZoneName -> Language -> UserStory ()
changeUserDetails name timezone language = logAction INFO ("changes fullname, timezone and language") $ do
user <- currentUser
persistence $ Persist.updateUser user { u_name = name , u_timezone = timezone , u_language = language }
putStatusMessage $ msg_UserStory_ChangedUserDetails "The user details have been updated."
-- Updates the user information
updateUser :: User -> UserStory ()
updateUser u = logAction INFO ("updates user " ++ (usernameCata id $ u_username u)) $ do
authorize P_Modify P_User
persistence $ Persist.updateUser u
-- | Selecting users that satisfy the given criteria
selectUsers :: (User -> Bool) -> UserStory [User]
selectUsers f = logAction INFO "selects some users" $ do
authorize P_Open P_User
persistence $ Persist.filterUsers f
-- | Load another user's data if the current user is authorized to open
-- other users' profile
loadUser :: Username -> UserStory User
loadUser u = logAction INFO "Loading user information" $ do
authorize P_Open P_User
persistence $ Persist.loadUser u
loadUserDesc :: Username -> UserStory UserDesc
loadUserDesc u = mkUserDescription <$> loadUser u
-- Returns the username who is active in the current userstory
username :: UserStory Username
username = CMS.gets user
-- The UserStory calculation returns the current user's profile data
currentUser :: UserStory User
currentUser = logAction INFO "Load the current user's data" $ do
u <- user <$> userState
persistence $ Persist.loadUser u
-- Saves (copies) a file to the actual directory from the given filepath
-- which will be determined. If the user has no permission for the uploading
-- an error is thrown
saveUsersFile :: FilePath -> UsersFile -> UserStory ()
saveUsersFile tempPath usersfile = logAction INFO logMessage $ do
authorize P_Create P_File
u <- username
persistence $ Persist.copyFile u tempPath usersfile
where
msg u = " uploads a file " ++ show u
logMessage = usersFile msg msg usersfile
-- List all the user's file. If the user has no permission for the listing
-- of files an error is thrown
listUsersFiles :: UserStory [(UsersFile, FileInfo)]
listUsersFiles = logAction INFO " lists all his files" $ do
authorize P_Open P_File
u <- username
persistence $ Persist.listFiles u
-- Returns the user's data file real path, for further processing, if
-- the user has authentication, otherwise throws an error page
getFilePath :: UsersFile -> UserStory FilePath
getFilePath usersfile = logAction INFO logMessage $ do
authorize P_Open P_File
u <- username
persistence $ Persist.getFile u usersfile
where
msg u = " asks the file path: " ++ show u
logMessage = usersFile msg msg usersfile
-- Produces true if the given user is the student of the courses or groups which
-- the actual user administrates.
isStudentOfMine :: Username -> UserStory Bool
isStudentOfMine student = logAction INFO (concat ["Student ", usernameCata id student, " of the actual user"]) $ do
authorize P_Modify P_StudentPassword
u <- username
persistence $ Persist.isStudentOf student u
administratedCourses :: UserStory [(CourseKey, Course)]
administratedCourses = logAction INFO "selects adminstrated courses" $ do
authorize P_Open P_Course
u <- username
persistence $ Persist.administratedCourses u
-- Produces a list of group keys, group and the full name of the group
administratedGroups :: UserStory [(GroupKey, Group, String)]
administratedGroups = logAction INFO "selects administrated groups" $ do
authorize P_Open P_Group
u <- username
persistence $ Persist.administratedGroupsWithCourseName u
-- | The 'create' function is an abstract function
-- for other creators like, createCourse and createExercise
create
:: (PermissionObj o)
=> (o -> v -> String) -- ^ Descriptor for the logger
-> o -- ^ The object to save
-> (o -> Persist v) -- ^ Saver function of the persistence
-> UserStory v
create descriptor object saver = do
authorize P_Create (permissionObject object)
value <- persistence (saver object)
logMessage INFO $ descriptor object value
return value
#ifndef SSO
createUserReg :: UserRegistration -> UserStory UserRegKey
createUserReg u = logAction INFO "Creates user registration" $ do
create descriptor u Persist.saveUserReg
where
descriptor x _ = reg_username x
loadUserReg :: UserRegKey -> UserStory UserRegistration
loadUserReg k = logAction INFO "Loading user registration" $ do
authorize P_Open P_UserReg
persistence $ Persist.loadUserReg k
#endif
-- | Creates a new course
createCourse :: Course -> UserStory CourseKey
createCourse course = logAction INFO "creates course" $ do
authorize P_Create P_Course
key <- create descriptor course Persist.saveCourse
putStatusMessage $ msg_UserStory_CreateCourse "The course has been created."
return key
where
descriptor course _ =
printf "Course is created: %s"
(show (courseName course))
selectCourses :: (CourseKey -> Course -> Bool) -> UserStory [(CourseKey, Course)]
selectCourses f = logAction INFO "selects some courses" $ do
authorize P_Open P_Course
persistence $ Persist.filterCourses f
loadCourse :: CourseKey -> UserStory (Course,[GroupKey])
loadCourse k = logAction INFO ("loads course: " ++ show k) $ do
authorize P_Open P_Course
persistence $ do
c <- Persist.loadCourse k
ks <- Persist.groupKeysOfCourse k
return (c,ks)
createCourseAdmin :: Username -> CourseKey -> UserStory ()
createCourseAdmin user ck = logAction INFO "sets user to course admin" $ do
authorize P_Create P_CourseAdmin
authorize P_Open P_User
persistence $ do
cas <- Persist.courseAdmins ck
Persist.createCourseAdmin user ck
c <- Persist.loadCourse ck
now <- liftIO getCurrentTime
let msg = Notification.NE_CourseAdminCreated (courseName c)
let affected = [user]
Persist.notifyUsers (Notification.Notification msg now Notification.System) affected
userUser <- Persist.loadUser user
let msg = Notification.NE_CourseAdminAssigned (courseName c) (u_name userUser)
let affected = cas
Persist.notifyUsers (Notification.Notification msg now Notification.System) affected
putStatusMessage $ msg_UserStory_SetCourseAdmin "The user has become a course administrator."
-- Produces a list of courses and users who administrators for the courses
courseAdministrators :: UserStory [(Course, [User])]
courseAdministrators = logAction INFO "lists the course and admins" $ do
authorize P_Open P_Course
authorize P_Open P_User
persistence $ do
Persist.filterCourses (\_ _ -> True) >>= (mapM $ \(ck,c) -> do
admins <- mapM Persist.loadUser =<< Persist.courseAdmins ck
return (c,admins))
-- Produces a list of courses that the user administrates and for all the courses
-- the list of groups and users who are groups admins for the given group
groupAdministrators :: UserStory [(Course, [(Group, [User])])]
groupAdministrators = logAction INFO "lists the groups and admins" $ do
authorize P_Open P_Course
authorize P_Open P_Group
authorize P_Open P_User
u <- username
persistence $ do
courses <- Persist.administratedCourses u
forM courses $ \(ck,course) -> do
gks <- Persist.groupKeysOfCourse ck
groups <- mapM groupAndAdmins gks
return (course, groups)
where
groupAndAdmins gk = do
g <- Persist.loadGroup gk
as <- mapM Persist.loadUser =<< Persist.groupAdmins gk
return (g,as)
-- Deletes the given users from the given course if the current user is a course
-- admin for the given course, otherwise redirects to the error page
deleteUsersFromCourse :: CourseKey -> [Username] -> UserStory ()
deleteUsersFromCourse ck sts = logAction INFO ("deletes users from course: " ++ show ck) $ do
authorize P_Modify P_Course
u <- username
join $ persistence $ do
admined <- Persist.isAdministratedCourse u ck
if admined
then do mapM_ (Persist.deleteUserFromCourse ck) sts
return . putStatusMessage $
msg_UserStory_UsersAreDeletedFromCourse "The students have been removed from the course."
else return $ do
logMessage INFO . violation $ printf "The user tries to delete users from a course (%s) which not belongs to him" (courseKeyMap id ck)
errorPage . userError $ msg_UserStoryError_NoCourseAdminOfCourse "The user is not course admin for the course."
-- Saves the given test script associated with the given course, if the
-- current user have authorization for the operation and if he administrates the
-- course given in the parameter. If authorization violation happens the page
-- redirects to the error page
saveTestScript :: CourseKey -> TestScript -> UserStory ()
saveTestScript ck ts = logAction INFO ("creates new test script for course: " ++ show ck) $ do
authorize P_Create P_TestScript
join $ withUserAndPersist $ \u -> do
let user = u_username u
cs <- map fst <$> Persist.administratedCourses user
case ck `elem` cs of
False -> return . errorPage . userError $ msg_UserStoryError_NoCourseAdminOfCourse "The user is not course admin for the course."
True -> do
Persist.saveTestScript ck ts
now <- liftIO getCurrentTime
c <- Persist.loadCourse ck
let msg = Notification.NE_TestScriptCreated (u_name u) (courseName c)
cas <- Persist.courseAdmins ck
gks <- Persist.groupKeysOfCourse ck
gas <- concat <$> mapM Persist.groupAdmins gks
let affected = nub (cas ++ gas) \\ [user]
Persist.notifyUsers (Notification.Notification msg now Notification.System) affected
return . putStatusMessage $
msg_UserStory_NewTestScriptIsCreated "The test script has been created."
-- Overwrite the test script with the given one if the current user administrates
-- the course that are of the given test script otherwise redirects to the error page
modifyTestScript :: TestScriptKey -> TestScript -> UserStory ()
modifyTestScript tsk ts = logAction INFO ("modifies the existing test script: " ++ show tsk) $ do
authorize P_Modify P_TestScript
join $ withUserAndPersist $ \u -> do
let user = u_username u
cs <- map fst <$> Persist.administratedCourses user
ck <- Persist.courseOfTestScript tsk
case ck `elem` cs of
False -> return . errorPage . userError $ msg_UserStoryError_NoAssociatedTestScript "You are trying to modify someone else's test script."
True -> do
Persist.modifyTestScript tsk ts
now <- liftIO getCurrentTime
c <- Persist.loadCourse ck
let msg = Notification.NE_TestScriptUpdated (u_name u) (tsName ts) (courseName c)
cas <- Persist.courseAdmins ck
gks <- Persist.groupKeysOfCourse ck
gas <- concat <$> mapM Persist.groupAdmins gks
let affected = nub (cas ++ gas) \\ [user]
Persist.notifyUsers (Notification.Notification msg now Notification.System) affected
return . putStatusMessage $
msg_UserStory_ModifyTestScriptIsDone "The test script has been updated."
-- | Loads the test script if the user has authorization for the load, and
-- otherwise redirects to the error page
loadTestScript :: TestScriptKey -> UserStory (TestScript, CourseKey)
loadTestScript tsk = logAction INFO ("loads the test script: " ++ show tsk) $ do
authorize P_Open P_TestScript
persistence $ do
ck <- Persist.courseOfTestScript tsk
ts <- Persist.loadTestScript tsk
return (ts, ck)
-- | Returns Just test case key and test case for the given assignment if there any, otherwise Nothing
testCaseOfAssignment :: AssignmentKey -> UserStory (Maybe (TestCaseKey, TestCase, TestScriptKey))
testCaseOfAssignment ak = logAction INFO (" loads the test case for assignment: " ++ show ak) $ do
persistence $ do
mtk <- Persist.testCaseOfAssignment ak
maybe
(return Nothing)
(\tk -> do tc <- Persist.loadTestCase tk
tsk <- Persist.testScriptOfTestCase tk
return (Just (tk, tc, tsk)))
mtk
-- | Returns the test scrips of the given assignments, that are attached to the course of the assignment
testScriptInfosOfAssignment :: AssignmentKey -> UserStory [(TestScriptKey, TestScriptInfo)]
testScriptInfosOfAssignment ak = do
authorize P_Open P_TestScript
persistence $ do
keys <- Persist.courseOrGroupOfAssignment ak
ck <- either (return) Persist.courseOfGroup keys
tsks <- Persist.testScriptsOfCourse ck
tss <- mapM loadTestScriptWithKey tsks
return tss
where
loadTestScriptWithKey tk = do
ti <- Persist.testScriptInfo tk
return (tk, ti)
-- | Returns the test scripts of the given group, that are arrached to the course of the group
testScriptInfosOfGroup :: GroupKey -> UserStory [(TestScriptKey, TestScriptInfo)]
testScriptInfosOfGroup gk = do
authorize P_Open P_TestScript
persistence $ do
ck <- Persist.courseOfGroup gk
tsks <- Persist.testScriptsOfCourse ck
tss <- mapM loadTestScriptWithKey tsks
return tss
where
loadTestScriptWithKey tk = do
ti <- Persist.testScriptInfo tk
return (tk, ti)
-- | Returns the test scripts of the given course
testScriptInfosOfCourse :: CourseKey -> UserStory [(TestScriptKey, TestScriptInfo)]
testScriptInfosOfCourse ck = do
authorize P_Open P_TestScript
persistence $ do
tsks <- Persist.testScriptsOfCourse ck
tss <- mapM loadTestScriptWithKey tsks
return tss
where
loadTestScriptWithKey tk = do
ti <- Persist.testScriptInfo tk
return (tk, ti)
-- Deletes the given users from the given group if the current user is a group
-- admin for the given group, otherwise redirects to the error page
deleteUsersFromGroup :: GroupKey -> [Username] -> UserStory ()
deleteUsersFromGroup gk sts = logAction INFO ("delets users form group: " ++ show gk) $ do
authorize P_Modify P_Group
join $ withUserAndPersist $ \u -> do
let user = u_username u
admined <- Persist.isAdministratedGroup user gk
if admined
then do ck <- Persist.courseOfGroup gk
mapM_ (\student -> Persist.unsubscribe student ck gk) sts
now <- liftIO getCurrentTime
g <- Persist.loadGroup gk
let msg = Notification.NE_RemovedFromGroup (groupName g) (u_name u)
let affected = sts
Persist.notifyUsers (Notification.Notification msg now Notification.System) affected
return . putStatusMessage $
msg_UserStory_UsersAreDeletedFromGroup "The students have been removed from the group."
else return $ do
logMessage INFO . violation $ printf "The user tries to delete users from group (%s) which is not administrated by him" (groupKeyMap id gk)
errorPage . userError $ msg_UserStoryError_NoGroupAdminOfGroup "You are not a group admin for the group."
createGroupAdmin :: Username -> GroupKey -> UserStory ()
createGroupAdmin user gk = logAction INFO "sets user as a group admin of a group" $ do
authorize P_Create P_GroupAdmin
authorize P_Open P_User
let uname = usernameCata id user
admin <- username
join . persistence $ do
info <- Persist.personalInfo user
withPersonalInfo info $ \role _name _tz _ui -> do
admined <- Persist.isAdministratedCourseOfGroup admin gk
if (and [groupAdmin role, admined])
then do Persist.createGroupAdmin user gk
now <- liftIO getCurrentTime
g <- Persist.loadGroup gk
ck <- Persist.courseOfGroup gk
c <- Persist.loadCourse ck
adminUser <- Persist.loadUser admin
userUser <- Persist.loadUser user
let userName = u_name userUser
let adminName = u_name adminUser
let msg = Notification.NE_GroupAdminCreated
(courseName c) adminName (groupName g)
let affected = [user] \\ [admin]
Persist.notifyUsers (Notification.Notification msg now Notification.System) affected
let username = usernameCata id user
let msg = Notification.NE_GroupAssigned (groupName g) (courseName c) adminName userName
cas <- Persist.courseAdmins ck
let affected = cas \\ [admin]
Persist.notifyUsers (Notification.Notification msg now Notification.System) affected
return $ putStatusMessage $ msg_UserStory_SetGroupAdmin "The user has become a teacher."
else return . CME.throwError $ userParamError (msg_UserStoryError_NoGroupAdmin "%s is not a group admin!") $ uname
-- Unsubscribes the student from the given group (and course) if the group is one of the student's group
-- and the sutdent did not submit any solutions for the assignments of the group. In that
-- case the error page is rendered
unsubscribeFromCourse :: GroupKey -> UserStory ()
unsubscribeFromCourse gk = logAction INFO ("unsubscribes from group: " ++ show gk) $ do
u <- username
join $ persistence $ do
registered <- Persist.isUserInGroup u gk
case registered of
False -> return . errorPage . userError $ msg_UserStoryError_NoGroupAdminOfGroup "You are not group admin for the group."
True -> do
ck <- Persist.courseOfGroup gk
s <- (&&) <$> Persist.isThereASubmissionForGroup u gk
<*> Persist.isThereASubmissionForCourse u ck
if s then (return . errorPage . userError $ msg_UserStoryError_AlreadyHasSubmission "You have already submitted some solution for the assignments of the course.")
else do
Persist.unsubscribe u ck gk
return . putStatusMessage $
msg_UserStory_SuccessfulCourseUnsubscription "Unregistration was successful."
-- | Adds a new group to the given course
createGroup :: CourseKey -> Group -> UserStory GroupKey
createGroup ck g = logAction INFO ("creats group " ++ show (groupName g)) $ do
authorize P_Create P_Group
join $ withUserAndPersist $ \u -> do
let user = u_username u
admined <- Persist.isAdministratedCourse user ck
if admined
then do key <- Persist.saveGroup ck g
now <- liftIO getCurrentTime
c <- Persist.loadCourse ck
let msg = Notification.NE_GroupCreated (courseName c) (u_name u) (groupName g)
cas <- Persist.courseAdmins ck
let affected = cas \\ [user]
Persist.notifyUsers (Notification.Notification msg now Notification.System) affected
return $ do
putStatusMessage $ msg_UserStory_CreateGroup "The group has been created."
return key
else return . errorPage $ userError nonAdministratedCourse
loadGroup :: GroupKey -> UserStory Group
loadGroup gk = logAction INFO ("loads group " ++ show gk) $ do
authorize P_Open P_Group
persistence $ Persist.loadGroup gk
-- | Checks is the user is subscribed for the group
isUserInGroup :: GroupKey -> UserStory Bool
isUserInGroup gk = logAction INFO ("checks if user is in the group " ++ show gk) $ do
authorize P_Open P_Group
state <- userState
persistence $ Persist.isUserInGroup (user state) gk
-- | Checks if the user is subscribed for the course
isUserInCourse :: CourseKey -> UserStory Bool
isUserInCourse ck = logAction INFO ("checks if user is in the course " ++ show ck) $ do
authorize P_Open P_Course
state <- userState
persistence $ Persist.isUserInCourse (user state) ck
-- | Lists all users subscribed for the given course
subscribedToCourse :: CourseKey -> UserStory [Username]
subscribedToCourse ck = logAction INFO ("lists all users in course " ++ show ck) $ do
authorize P_Open P_Course
isAdministratedCourse ck
persistence $ Persist.subscribedToCourse ck
-- | Lists all users subscribed for the given group
subscribedToGroup :: GroupKey -> UserStory [Username]
subscribedToGroup gk = logAction INFO ("lists all users in group " ++ show gk) $ do
authorize P_Open P_Group
isAdministratedGroup gk
persistence $ Persist.subscribedToGroup gk
-- | Regsiter the user in the group, if the user does not submitted
-- any solutions for the other groups of the actual course, otherwise
-- puts a message on the UI, indicating that the course change is
-- not allowed.
subscribeToGroup :: GroupKey -> UserStory ()
subscribeToGroup gk = logAction INFO ("subscribes to the group " ++ (show gk)) $ do
authorize P_Open P_Group
state <- userState
message <- persistence $ do
let u = user state
ck <- Persist.courseOfGroup gk
gks <- Persist.groupsOfUsersCourse u ck
hasSubmission <- isThereASubmission u gks
case hasSubmission of
True -> return $ msg_UserStory_SubscribedToGroup_ChangeNotAllowed
"It is not possible to move between groups as there are submission for the current group."
False -> do
mapM_ (Persist.unsubscribe u ck) gks
Persist.subscribe u ck gk
return $ msg_UserStory_SubscribedToGroup "Successful registration."
putStatusMessage message
where
isThereASubmission u gks = do
aks <- concat <$> mapM Persist.groupAssignments gks
(not . null . catMaybes) <$> (mapM (flip Persist.lastSubmission u) aks)
-- Returns a list of elements of group key, description and a boolean value indicating
-- that the user already submitted a solution for the group or the course of the group
attendedGroups :: UserStory [(GroupKey, GroupDesc, Bool)]
attendedGroups = logAction INFO "selects courses attended in" $ do
authorize P_Open P_Group
uname <- username
persistence $ do
ks <- Persist.userGroups uname
ds <- mapM Persist.groupDescription ks
mapM (isThereASubmissionDesc uname) ds
where
isThereASubmissionDesc u (gk, desc) = do
ck <- Persist.courseOfGroup gk
s <- (||) <$> Persist.isThereASubmissionForGroup u gk
<*> Persist.isThereASubmissionForCourse u ck
return (gk,desc,s)
testCaseModificationForAssignment :: Username -> AssignmentKey -> TCModification -> Persist ()
testCaseModificationForAssignment u ak = tcModificationCata noModification fileOverwrite textOverwrite tcDelete where
noModification = return ()
fileOverwrite tsk uf = do
let usersFileName = usersFile id id uf
testCase = TestCase {
tcName = usersFileName
, tcDescription = usersFileName
, tcValue = ZippedTestCase ""
, tcInfo = usersFileName
}
mtk <- Persist.testCaseOfAssignment ak
-- TODO: Join the test case creation and test case file copy
tk <- case mtk of
Just tk -> Persist.modifyTestCase tk testCase >> return tk
Nothing -> Persist.saveTestCase tsk ak testCase
Persist.modifyTestScriptOfTestCase tk tsk
Persist.copyTestCaseFile tk u uf
return ()
textOverwrite tsk t = do
a <- Persist.loadAssignment ak
let name = Assignment.name a
testCase = TestCase {
tcName = name
, tcDescription = name
, tcValue = SimpleTestCase t
, tcInfo = ""
}
mtk <- Persist.testCaseOfAssignment ak
tk <- case mtk of
Just tk -> Persist.modifyTestCase tk testCase >> return tk
Nothing -> Persist.saveTestCase tsk ak testCase
Persist.modifyTestScriptOfTestCase tk tsk
tcDelete = do
mtk <- Persist.testCaseOfAssignment ak
case mtk of
Nothing -> return ()
Just tk -> Persist.removeTestCaseAssignment tk ak
-- Interprets the TCCreation value, copying a binary file or filling up the
-- normal test case file with the plain value, creating the test case for the
-- given assingment
testCaseCreationForAssignment :: Username -> AssignmentKey -> TCCreation -> Persist ()
testCaseCreationForAssignment u ak = tcCreationCata noCreation fileCreation textCreation where
noCreation = return ()
fileCreation tsk usersfile = do
let usersFileName = usersFile id id usersfile
testCase = TestCase {
tcName = usersFileName
, tcDescription = usersFileName
, tcValue = ZippedTestCase ""
, tcInfo = usersFileName
}
tk <- Persist.saveTestCase tsk ak testCase
Persist.copyTestCaseFile tk u usersfile
return ()
-- Set plain text as test case value
textCreation tsk plain = do
a <- Persist.loadAssignment ak
let name = Assignment.name a
testCase = TestCase {
tcName = name
, tcDescription = name
, tcValue = SimpleTestCase plain
, tcInfo = ""
}
Persist.saveTestCase tsk ak testCase
return ()
createGroupAssignment :: GroupKey -> Assignment -> TCCreation -> UserStory AssignmentKey
createGroupAssignment gk a tc = logAction INFO msg $ do
authorize P_Open P_Group
authorize P_Create P_Assignment
when (null $ Assignment.name a) $
errorPage . userError $ msg_UserStoryError_EmptyAssignmentTitle
"Assignment title is empty."
when (null $ Assignment.desc a) $
errorPage . userError $ msg_UserStoryError_EmptyAssignmentDescription
"Assignment description is empty."
join . withUserAndPersist $ \u -> do
let user = u_username u
admined <- Persist.isAdministratedGroup user gk
if admined
then do ak <- Persist.saveGroupAssignment gk a
testCaseCreationForAssignment user ak tc
now <- liftIO getCurrentTime
g <- Persist.loadGroup gk
ck <- Persist.courseOfGroup gk
c <- Persist.loadCourse ck
let msg = Notification.NE_GroupAssignmentCreated
(u_name u) (groupName g) (courseName c) (Assignment.name a)
gas <- Persist.groupAdmins gk
let affected = nub gas \\ [user]
Persist.notifyUsers (Notification.Notification msg now $ Notification.Assignment ak) affected
sbs <- Persist.subscribedToGroup gk
let affected = nub (sbs \\ (gas ++ [user]))
let time = Assignment.start a
Persist.notifyUsers (Notification.Notification msg time $ Notification.Assignment ak) affected
return $ do
statusMsg a
logMessage INFO $ descriptor ak
return ak
else return $ do
logMessage INFO . violation $ printf "User tries to access to group: %s" (groupKeyMap id gk)
errorPage $ userError nonAdministratedGroup
where
descriptor key = printf "Exercise is created with id: %s" (assignmentKeyMap id key)
msg = "creates assignment for group " ++ show gk
statusMsg = const .
putStatusMessage $ msg_UserStory_NewGroupAssignment "The group assignment has been created."
createCourseAssignment :: CourseKey -> Assignment -> TCCreation -> UserStory AssignmentKey
createCourseAssignment ck a tc = logAction INFO msg $ do
authorize P_Open P_Course
authorize P_Create P_Assignment
when (null $ Assignment.name a) $
errorPage . userError $ msg_UserStoryError_EmptyAssignmentTitle
"Assignment title is empty."
when (null $ Assignment.desc a) $
errorPage . userError $ msg_UserStoryError_EmptyAssignmentDescription
"Assignment description is empty."
join . withUserAndPersist $ \u -> do
let user = u_username u
admined <- Persist.isAdministratedCourse user ck
if admined
then do ak <- Persist.saveCourseAssignment ck a
testCaseCreationForAssignment user ak tc
now <- liftIO getCurrentTime
c <- Persist.loadCourse ck
let msg = Notification.NE_CourseAssignmentCreated
(u_name u) (courseName c) (Assignment.name a)
cas <- Persist.courseAdmins ck
gks <- Persist.groupKeysOfCourse ck
gas <- concat <$> mapM Persist.groupAdmins gks
sbs <- Persist.subscribedToCourse ck
let affected = nub (gas ++ cas) \\ [user]
Persist.notifyUsers (Notification.Notification msg now $ Notification.Assignment ak) affected
let affected = nub (sbs \\ (gas ++ cas ++ [user]))
let time = Assignment.start a
Persist.notifyUsers (Notification.Notification msg time $ Notification.Assignment ak) affected
return $ do
statusMsg a
logMessage INFO $ descriptor ak
return ak
else return $ do
logMessage INFO . violation $ printf "User tries to access to course: %s" (courseKeyMap id ck)
errorPage $ userError nonAdministratedCourse
where
descriptor key = printf "Exercise is created with id: %s" (assignmentKeyMap id key)
msg = "creates assignment for course " ++ show ck
statusMsg = const .
putStatusMessage $ msg_UserStory_NewCourseAssignment "The course assignment has been created."
-- | The 'loadExercise' loads an exercise from the persistence layer
loadAssignment :: AssignmentKey -> UserStory Assignment
loadAssignment k = logAction INFO ("loads assignment " ++ show k) $ do
authorize P_Open P_Assignment
persistence $ Persist.loadAssignment k
createGroupAssessment :: GroupKey -> Assessment -> UserStory AssessmentKey
createGroupAssessment gk a = logAction INFO ("creates assessment for group " ++ show gk) $ do
authorize P_Open P_Group
authorize P_Create P_Assessment
isAdministratedGroup gk
ak <- persistence (Persist.saveGroupAssessment gk a)
withUserAndPersist $ \u -> do
let user = u_username u
now <- liftIO getCurrentTime
ck <- Persist.courseOfGroup gk
g <- Persist.loadGroup gk
c <- Persist.loadCourse ck
let msg = Notification.NE_GroupAssessmentCreated
(u_name u) (groupName g) (courseName c) (Assessment.title a)
gas <- Persist.groupAdmins gk
sbs <- Persist.subscribedToGroup gk
let affected = nub (gas ++ sbs) \\ [user]
Persist.notifyUsers (Notification.Notification msg now $ Notification.Assessment ak) affected
return ak
createCourseAssessment :: CourseKey -> Assessment -> UserStory AssessmentKey
createCourseAssessment ck a = logAction INFO ("creates assessment for course " ++ show ck) $ do
authorize P_Open P_Course
authorize P_Create P_Assessment
isAdministratedCourse ck
ak <- persistence (Persist.saveCourseAssessment ck a)
withUserAndPersist $ \u -> do
let user = u_username u
now <- liftIO getCurrentTime
c <- Persist.loadCourse ck
let msg = Notification.NE_CourseAssessmentCreated
(u_name u) (courseName c) (Assessment.title a)
cas <- Persist.courseAdmins ck
sbs <- Persist.subscribedToCourse ck
let affected = nub (cas ++ sbs) \\ [user]
Persist.notifyUsers (Notification.Notification msg now $ Notification.Assessment ak) affected
return ak
modifyAssessment :: AssessmentKey -> Assessment -> UserStory ()
modifyAssessment ak a = logAction INFO ("modifies assessment " ++ show ak) $ do
authorize P_Open P_Assessment
authorize P_Modify P_Assessment
isAdministratedAssessment ak
withUserAndPersist $ \u -> do
let user = u_username u
hasScore <- isThereAScorePersist ak
new <- if hasScore
then do
-- Overwrite the assignment type with the old one
-- if there is a score for the given assessment
evConfig <- Assessment.evaluationCfg <$> Persist.loadAssessment ak
return (a { Assessment.evaluationCfg = evConfig})
else return a
Persist.modifyAssessment ak new
now <- liftIO getCurrentTime
let msg = Notification.NE_AssessmentUpdated (u_name u) (Assessment.title a)
mck <- Persist.courseOfAssessment ak
mgk <- Persist.groupOfAssessment ak
affected <- case (mck, mgk) of
(Just ck, _) -> do
cas <- Persist.courseAdmins ck
sbs <- Persist.subscribedToCourse ck
return $ nub (cas ++ sbs) \\ [user]
(_, Just gk) -> do
gas <- Persist.groupAdmins gk
sbs <- Persist.subscribedToGroup gk
return $ nub (gas ++ sbs) \\ [user]
_ -> return []
Persist.notifyUsers (Notification.Notification msg now $ Notification.Assessment ak) affected
when (hasScore && Assessment.evaluationCfg a /= Assessment.evaluationCfg new) $
void . return . putStatusMessage . msg_UserStory_AssessmentEvalTypeWarning $ concat
[ "The evaluation type of the assessment is not modified. "
, "A score is already submitted."
]
modifyAssessmentAndScores :: AssessmentKey -> Assessment -> Map Username Evaluation -> UserStory ()
modifyAssessmentAndScores ak a scores = logAction INFO ("modifies assessment and scores of " ++ show ak) $ do
modifyAssessment ak a
cGKey <- courseOrGroupOfAssessment ak
case cGKey of
Left ck -> do
usernames <- subscribedToCourse ck
modifyScoresOfUsers usernames
Right gk -> do
usernames <- subscribedToGroup gk
modifyScoresOfUsers usernames
where
modifyScoresOfUsers :: [Username] -> UserStory ()
modifyScoresOfUsers usernames = do
forM_ usernames $ \u -> do
case Map.lookup u scores of
Nothing -> return ()
Just newEv -> do
maybeSk <- scoreInfoOfUser u ak
case maybeSk of
Just (Just sk, _) -> persistence $ do
mEvKey <- Persist.evaluationOfScore sk
case mEvKey of
Just evKey -> Persist.modifyEvaluation evKey newEv
Nothing -> return ()
Just (_,_) -> void $ saveUserScore u ak newEv
_ -> return ()
loadAssessment :: AssessmentKey -> UserStory Assessment
loadAssessment ak = logAction INFO ("loads assessment " ++ show ak) $ do
authorize P_Open P_Assessment
persistence (Persist.loadAssessment ak)
courseOrGroupOfAssessment :: AssessmentKey -> UserStory (Either CourseKey GroupKey)
courseOrGroupOfAssessment ak = logAction INFO ("gets course key or group key of assessment " ++ show ak) $
persistence (Persist.courseOrGroupOfAssessment ak)
assessmentDesc :: AssessmentKey -> UserStory AssessmentDesc
assessmentDesc ak = logAction INFO ("loads information of assessment " ++ show ak) $ do
authorize P_Open P_Assessment
persistence (Persist.assessmentDesc ak)
usernameOfScore :: ScoreKey -> UserStory Username
usernameOfScore sk = logAction INFO ("looks up the user of score " ++ show sk) $ do
persistence (Persist.usernameOfScore sk)
assessmentOfScore :: ScoreKey -> UserStory AssessmentKey
assessmentOfScore sk = logAction INFO ("looks up the assessment of score " ++ show sk) $ do
persistence (Persist.assessmentOfScore sk)
isThereAScorePersist :: AssessmentKey -> Persist Bool
isThereAScorePersist ak = not . null <$> Persist.scoresOfAssessment ak
isThereAScore :: AssessmentKey -> UserStory Bool
isThereAScore ak = logAction INFO ("checks whether there is a score for the assessment " ++ show ak) $
persistence (isThereAScorePersist ak)
scoreInfo :: ScoreKey -> UserStory ScoreInfo
scoreInfo sk = logAction INFO ("loads score information of score " ++ show sk) $ do
persistence (Persist.scoreInfo sk)
scoreDesc :: ScoreKey -> UserStory ScoreDesc
scoreDesc sk = logAction INFO ("loads score description of score " ++ show sk) $ do
authPerms scoreDescPermissions
currentUser <- username
scoreUser <- usernameOfScore sk
if (currentUser == scoreUser)
then persistence $ Persist.scoreDesc sk
else do
logMessage INFO . violation $ printf "The user tries to view a score (%s) that not belongs to him."
(show sk)
errorPage $ userError nonAccessibleScore
saveUserScore :: Username -> AssessmentKey -> Evaluation -> UserStory ()
saveUserScore u ak evaluation = logAction INFO ("saves user score of " ++ show u ++ " for assessment " ++ show ak) $ do
authorize P_Open P_Assessment
scoreInfo <- scoreInfoOfUser u ak
case scoreInfo of
Just (Nothing, Score_Not_Found) ->
persistence $ do
sk <- Persist.saveScore u ak (Score ())
void $ Persist.saveScoreEvaluation sk evaluation
_ -> do
logMessage INFO "Other admin just gave a score for this user's assessment"
putStatusMessage $ msg_UserStoryError_ScoreAlreadyExists
"This user already has a score for this assessment"
modifyUserScore :: ScoreKey -> Evaluation -> UserStory ()
modifyUserScore sk newEvaluation = logAction INFO ("modifies user score " ++ show sk) $ do
mEKey <- persistence (Persist.evaluationOfScore sk)
maybe (return ()) (\eKey -> modifyEvaluation eKey newEvaluation) mEKey
saveScoresOfCourseAssessment :: CourseKey -> Assessment -> Map Username Evaluation -> UserStory ()
saveScoresOfCourseAssessment ck a evaluations = do
ak <- createCourseAssessment ck a
logAction INFO ("saves scores of assessment " ++ show ak ++ " of course " ++ show ck) $ do
users <- subscribedToCourse ck
persistence (mapM_ (saveEvaluation ak) users)
where
saveEvaluation ak user = case Map.lookup user evaluations of
Just eval -> do sk <- Persist.saveScore user ak score
void $ Persist.saveScoreEvaluation sk eval
Nothing -> return ()
score = Score ()
saveScoresOfGroupAssessment :: GroupKey -> Assessment -> Map Username Evaluation -> UserStory ()
saveScoresOfGroupAssessment gk a evaluations = do
ak <- createGroupAssessment gk a
logAction INFO ("saves scores of assessment " ++ show ak ++ " of group " ++ show gk) $ do
users <- subscribedToGroup gk
persistence (mapM_ (saveEvaluation ak) users)
where
saveEvaluation ak user = case Map.lookup user evaluations of
Just eval -> do sk <- Persist.saveScore user ak score
void $ Persist.saveScoreEvaluation sk eval
Nothing -> return ()
score = Score ()
-- Produces a map of assessments and information about the evaluations for the
-- assessments.
userAssessments :: UserStory (Map CourseKey (Course, [(AssessmentKey, Assessment, Maybe ScoreKey, ScoreInfo)]))
userAssessments = logAction INFO "lists assessments" $ do
-- authorize P_Open P_Assessment
authorize P_Open P_Course
authorize P_Open P_Group
u <- username
userAssessments <- persistence $ Persist.userAssessmentKeys u
newMap <- forM (Map.toList userAssessments) $ \(ckey,asks) -> do
(course,_groups) <- loadCourse ckey
infos <- catMaybes <$> mapM (getInfo u) (Set.toList asks)
return $! (ckey, (course, infos))
return $! Map.fromList newMap
where
getInfo :: Username
-> AssessmentKey
-> UserStory (Maybe (AssessmentKey, Assessment, Maybe ScoreKey, ScoreInfo))
getInfo u ak = do
assessment <- loadAssessment ak
mScoreInfo <- scoreInfoOfUser u ak
case mScoreInfo of
Nothing -> return Nothing
Just (sk,sInfo) -> return $ Just (ak, assessment, sk, sInfo)
-- Produces the score key, score info for the specific user and assessment.
-- Returns Nothing if there are multiple scoreinfos available.
scoreInfoOfUser :: Username -> AssessmentKey -> UserStory (Maybe (Maybe ScoreKey, ScoreInfo))
scoreInfoOfUser u ak = logAction INFO ("loads score info of user " ++ show u ++ " and assessment " ++ show ak) $
persistence $ do
scoreKeys <- Persist.scoreOfAssessmentAndUser u ak
case scoreKeys of
[] -> return . Just $ (Nothing, Score_Not_Found)
[sk] -> do info <- Persist.scoreInfo sk
return . Just $ (Just sk,info)
_ -> return Nothing
scoresOfGroup :: GroupKey -> AssessmentKey -> UserStory [(UserDesc, Maybe ScoreInfo)]
scoresOfGroup gk ak = logAction INFO ("lists scores of group " ++ show gk ++ " and assessment " ++ show ak) $ do
authorize P_Open P_Group
isAdministratedGroup gk
usernames <- subscribedToGroup gk
forM usernames $ \u -> do
mScoreInfo <- scoreInfoOfUser u ak
userDesc <- loadUserDesc u
case mScoreInfo of
Nothing -> return (userDesc, Nothing)
Just (_sk, scoreInfo) -> return (userDesc, Just scoreInfo)
scoresOfCourse :: CourseKey -> AssessmentKey -> UserStory [(UserDesc, Maybe ScoreInfo)]
scoresOfCourse ck ak = logAction INFO ("lists scores of course " ++ show ck ++ " and assessment " ++ show ak) $ do
authorize P_Open P_Course
isAdministratedCourse ck
usernames <- subscribedToCourse ck
forM usernames $ \u -> do
userDesc <- loadUserDesc u
mScoreInfo <- scoreInfoOfUser u ak
case mScoreInfo of
Nothing -> return (userDesc, Nothing)
Just (_sk, scoreInfo) -> return (userDesc, Just scoreInfo)
scoreBoards :: UserStory (Map (Either CourseKey GroupKey) ScoreBoard)
scoreBoards = logAction INFO "lists scoreboards" $ do
authPerms scoreBoardPermissions
withUserAndPersist $ Persist.scoreBoards . u_username
-- Puts the given status message to the actual user state
putStatusMessage :: Translation String -> UserStory ()
putStatusMessage = changeUserState . setStatus . SmNormal
-- Puts the given message as the error status message to the actual user state
putErrorMessage :: Translation String -> UserStory ()
putErrorMessage = changeUserState . setStatus . SmError
-- Clears the status message of the user
clearStatusMessage :: UserStory ()
clearStatusMessage = changeUserState clearStatus
-- Logs the error message into the logfile and, also throw as an error
errorPage :: UserError -> UserStory a
errorPage e = do
logMessage ERROR $ translateUserError trans e
CME.throwError e
-- * Low level user story functionality
authPerms :: ObjectPermissions -> UserStory ()
authPerms = mapM_ (uncurry authorize) . permissions
-- | Authorize the user for the given operation.
-- It throws exception if the user is not authorized
-- for the given operation
authorize :: Permission -> PermissionObject -> UserStory ()
authorize p o = do
er <- CMS.gets userRole
case er of
Left EmptyRole ->
errorPage $ userError (msg_UserStoryError_UserIsNotLoggedIn "The user is not logged in.")
Left RegRole -> case elem (p,o) regPermObjects of
True -> return ()
False -> errorPage $ userPrm2Error
(msg_UserStoryError_RegistrationProcessError $ unlines [
"During the registration process some internal error happened ",
"and tries to reach other processes %s %s."])
(show p) (show o)
Left TestAgentRole -> case elem (p,o) testAgentPermObjects of
True -> return ()
False -> errorPage $ userPrm2Error
(msg_UserStoryError_TestAgentError $ unlines [
"During the automated testing process some internal error happened ",
"and tries to reach other processes %s %s."])
(show p) (show o)
Right r -> case permission r p o of
True -> return ()
False -> errorPage $ userPrm3Error
(msg_UserStoryError_AuthenticationNeeded "Authentication needed %s %s %s")
(show r) (show p) (show o)
where
regPermObjects = [
(P_Create, P_User), (P_Open, P_User)
, (P_Create, P_UserReg), (P_Open, P_UserReg)
, (P_Modify, P_User)
]
testAgentPermObjects = [
(P_Open, P_TestIncoming), (P_Open, P_Submission), (P_Create, P_Feedback)
]
-- | No operational User Story
noOperation :: UserStory ()
noOperation = return ()
-- | Log error message through the log subsystem
logErrorMessage :: String -> UserStory ()
logErrorMessage = logMessage ERROR
-- | Log a message through the log subsystem
logMessage :: LogLevel -> String -> UserStory ()
logMessage level msg = do
CMS.get >>=
userStateCata
userNotLoggedIn
registration
testAgent
loggedIn
where
logMsg preffix =
asksLogger >>= (\lgr -> (liftIO $ log lgr level $ join [preffix, " ", msg, "."]))
userNotLoggedIn = logMsg "[USER NOT LOGGED IN]"
registration = logMsg "[REGISTRATION]"
testAgent = logMsg "[TEST AGENT]"
loggedIn _ u _ _ _ t _ _ = logMsg (join [Entity.uid id u, " ", t])
-- | Change user state, if the user state is logged in
changeUserState :: (UserState -> UserState) -> UserStory ()
changeUserState f = do
state <- CMS.get
case state of
UserNotLoggedIn -> return ()
state' -> CMS.put (f state')
loadUserData :: Username -> String -> PageDesc -> UserStory ()
loadUserData uname t p = do
info <- persistence $ Persist.personalInfo uname
flip personalInfoCata info $ \r n tz ui -> do
CMS.put $ UserState {
user = uname
, uid = ui
, page = p
, name = n
, role = r
, token = t
, timezone = tz
, status = Nothing
}
userState :: UserStory UserState
userState = CMS.get
submitSolution :: AssignmentKey -> Submission -> UserStory SubmissionKey
submitSolution ak s = logAction INFO ("submits solution for assignment " ++ show ak) $ do
authorize P_Open P_Assignment
authorize P_Create P_Submission
checkActiveAssignment
join $ withUserAndPersist $ \u -> do
let user = u_username u
attended <- Persist.isUsersAssignment user ak
if attended
then do removeUserOpenedSubmissions user ak
sk <- Persist.saveSubmission ak user s
Persist.saveTestJob sk
return (return sk)
else return $ do
logMessage INFO . violation $
printf "The user tries to submit a solution for an assignment which not belongs to him: (%s)" (assignmentKeyMap id ak)
errorPage $ userError nonRelatedAssignment
where
checkActiveAssignment :: UserStory ()
checkActiveAssignment = do
a <- Bead.Controller.UserStories.loadAssignment ak
now <- liftIO getCurrentTime
unless (Assignment.isActive a now) . errorPage . userError $
msg_UserStoryError_SubmissionDeadlineIsReached "The submission deadline is reached."
-- TODO: Change the ABI to remove the unevaluated automatically
removeUserOpenedSubmissions u ak = do
sks <- Persist.usersOpenedSubmissions ak u
mapM_ (Persist.removeFromOpened ak u) sks
-- Returns all the group for that the user does not submitted a soultion already
availableGroups :: UserStory [(GroupKey, GroupDesc)]
availableGroups = logAction INFO "lists available groups" $ do
authorize P_Open P_Group
u <- username
persistence $ do
allGroups <- map fst <$> Persist.filterGroups each
available <- filterM (thereIsNoSubmission u) allGroups
mapM Persist.groupDescription available
where
each _ _ = True
thereIsNoSubmission u gk = not <$> Persist.isThereASubmissionForGroup u gk
-- Produces a list that contains the assignments for the actual user,
-- if the user is not subscribed to a course or group the list
-- will be empty. The map consist of all the assignment key groupped by the
-- course key, through group keys if necessary.
userAssignmentKeys :: UserStory (Map CourseKey (Set AssignmentKey))
userAssignmentKeys = logAction INFO "lists its assignments" $ do
authorize P_Open P_Assignment
uname <- username
persistence $ Persist.userAssignmentKeys uname
userSubmissionKeys :: AssignmentKey -> UserStory [SubmissionKey]
userSubmissionKeys ak = logAction INFO msg $ do
authorize P_Open P_Assignment
authorize P_Open P_Submission
withUserAndPersist $ \u -> Persist.userSubmissions (u_username u) ak
where
msg = "lists the submissions for assignment " ++ show ak
submissionDetailsDesc :: SubmissionKey -> UserStory SubmissionDetailsDesc
submissionDetailsDesc sk = logAction INFO msg $ do
authPerms submissionDetailsDescPermissions
persistence $ Persist.submissionDetailsDesc sk
where
msg = "loads information about submission " ++ show sk
loadSubmission :: SubmissionKey -> UserStory Submission
loadSubmission sk = logAction INFO ("loads submission " ++ show sk) $ do
authorize P_Open P_Submission
persistence $ Persist.loadSubmission sk
-- Checks if the submission is accessible for the user and loads it,
-- otherwise throws an exception.
getSubmission :: SubmissionKey -> UserStory (Submission, SubmissionDesc)
getSubmission sk = logAction INFO ("downloads submission " ++ show sk) $ do
authorize P_Open P_Submission
isAccessibleBallotBoxSubmission sk
persistence $ do
s <- Persist.loadSubmission sk
d <- Persist.submissionDesc sk
return (s,d)
-- Creates a submission limit for the given assignment
assignmentSubmissionLimit :: AssignmentKey -> UserStory SubmissionLimit
assignmentSubmissionLimit key = logAction INFO msg $ do
authorize P_Open P_Assignment
authorize P_Open P_Submission
withUserAndPersist $ \u -> Persist.submissionLimitOfAssignment (u_username u) key
where
msg = "user assignments submission Limit"
-- Loads the assignment and the assignment description if the given assignment key
-- refers an assignment accessible by the user for submission
userAssignmentForSubmission :: AssignmentKey -> UserStory (AssignmentDesc, Assignment)
userAssignmentForSubmission key = logAction INFO "check user assignment for submission" $ do
authorize P_Open P_Assignment
authorize P_Open P_Submission
isUsersAssignment key
now <- liftIO getCurrentTime
withUserAndPersist $ \u ->
(,) <$> (assignmentDesc now (u_username u) key) <*> (Persist.loadAssignment key)
-- Helper function which computes the assignment description
assignmentDesc :: UTCTime -> Username -> AssignmentKey -> Persist AssignmentDesc
assignmentDesc now user key = do
a <- Persist.loadAssignment key
limit <- Persist.submissionLimitOfAssignment user key
let aspects = Assignment.aspects a
(name, adminNames) <- Persist.courseNameAndAdmins key
return $! AssignmentDesc {
aActive = Assignment.isActive a now
, aIsolated = Assignment.isIsolated aspects
, aLimit = limit
, aTitle = Assignment.name a
, aTeachers = adminNames
, aGroup = name
, aEndDate = Assignment.end a
}
-- Produces a map of assignments and information about the submissions for the
-- described assignment, which is associated with the course or group
userAssignments :: UserStory (Map CourseKey (Course,[(AssignmentKey, AssignmentDesc, SubmissionInfo)]))
userAssignments = logAction INFO "lists assignments" $ do
authorize P_Open P_Assignment
authorize P_Open P_Course
authorize P_Open P_Group
now <- liftIO getCurrentTime
withUserAndPersist $ \u -> do
let user = u_username u
asgMap <- Persist.userAssignmentKeys user
newMap <- forM (Map.toList asgMap) $ \(key,aks) -> do
key' <- Persist.loadCourse key
descs <- catMaybes <$> mapM (createDesc user now) (Set.toList aks)
return $! (key, (key', descs))
return $! Map.fromList newMap
where
-- Produces the assignment description if the assignment is active
-- Returns Nothing if the assignment is not visible for the user
createDesc :: Username -> UTCTime -> AssignmentKey -> Persist (Maybe (AssignmentKey, AssignmentDesc, SubmissionInfo))
createDesc u now ak = do
a <- Persist.loadAssignment ak
case (now < Assignment.start a) of
True -> return Nothing
False -> do
desc <- assignmentDesc now u ak
si <- Persist.userLastSubmissionInfo u ak
return $ (Just (ak, desc, si))
submissionDescription :: SubmissionKey -> UserStory SubmissionDesc
submissionDescription sk = logAction INFO msg $ do
authPerms submissionDescPermissions
u <- username
join . persistence $ do
admined <- Persist.isAdministratedSubmission u sk
if admined
then do sd <- Persist.submissionDesc sk
return (return sd)
else return $ do
logMessage INFO . violation $ printf "The user tries to evaluate a submission that not belongs to him."
errorPage $ userError nonAdministratedSubmission
where
msg = "loads submission infomation for " ++ show sk
openSubmissions :: UserStory OpenedSubmissions
openSubmissions = logAction INFO ("lists unevaluated submissions") $ do
authorize P_Open P_Submission
u <- username
persistence $ Persist.openedSubmissionInfo u
submissionListDesc :: AssignmentKey -> UserStory SubmissionListDesc
submissionListDesc ak = logAction INFO ("lists submissions for assignment " ++ show ak) $ do
authPerms submissionListDescPermissions
withUserAndPersist $ \u -> Persist.submissionListDesc (u_username u) ak
courseSubmissionTable :: CourseKey -> UserStory SubmissionTableInfo
courseSubmissionTable ck = logAction INFO ("gets submission table for course " ++ show ck) $ do
authPerms submissionTableInfoPermissions
u <- username
join . persistence $ do
admined <- Persist.isAdministratedCourse u ck
if admined
then do sti <- Persist.courseSubmissionTableInfo ck
return (return sti)
else return $ do
logMessage INFO . violation $ printf "The user tries to open a course overview (%s) that is not administrated by him." (courseKeyMap id ck)
errorPage $ userError nonAdministratedCourse
submissionTables :: UserStory [SubmissionTableInfo]
submissionTables = logAction INFO "lists submission tables" $ do
authPerms submissionTableInfoPermissions
withUserAndPersist $ Persist.submissionTables . u_username
-- Calculates the test script infos for the given course
testScriptInfos :: CourseKey -> UserStory [(TestScriptKey, TestScriptInfo)]
testScriptInfos ck = persistence $
mapM testScriptInfoAndKey =<< (Persist.testScriptsOfCourse ck)
where
testScriptInfoAndKey tk = do
ts <- Persist.testScriptInfo tk
return (tk,ts)
newEvaluation :: SubmissionKey -> Evaluation -> UserStory ()
newEvaluation sk e = logAction INFO ("saves new evaluation for " ++ show sk) $ do
authorize P_Open P_Submission
authorize P_Create P_Evaluation
now <- liftIO $ getCurrentTime
userData <- currentUser
join . withUserAndPersist $ \u -> do
let user = u_username u
admined <- Persist.isAdminedSubmission user sk
if admined
then do mek <- Persist.evaluationOfSubmission sk
case mek of
Nothing -> do
ek <- Persist.saveSubmissionEvaluation sk e
Persist.removeOpenedSubmission sk
Persist.saveFeedback sk (evaluationToFeedback now userData e)
let msg = Notification.NE_EvaluationCreated (u_name u) (withSubmissionKey sk id)
ak <- Persist.assignmentOfSubmission sk
mck <- Persist.courseOfAssignment ak
mgk <- Persist.groupOfAssignment ak
submitter <- Persist.usernameOfSubmission sk
affected <- case (mck, mgk) of
(Just ck, _) -> do
cas <- Persist.courseAdmins ck
return $ nub ([submitter] ++ cas) \\ [user]
(_, Just gk) -> do
gas <- Persist.groupAdmins gk
return $ nub ([submitter] ++ gas) \\ [user]
_ -> return []
Persist.notifyUsers (Notification.Notification msg now $ Notification.Evaluation ek) affected
return (return ())
Just _ -> return $ do
logMessage INFO "Other admin just evaluated this submission"
putStatusMessage $ msg_UserStory_AlreadyEvaluated
"Other admin just evaluated this submission"
else return $ do
logMessage INFO . violation $ printf "The user tries to save evalution for a submission (%s) that not belongs to him" (show sk)
errorPage $ userError nonAdministratedSubmission
modifyEvaluation :: EvaluationKey -> Evaluation -> UserStory ()
modifyEvaluation ek e = logAction INFO ("modifies evaluation " ++ show ek) $ do
authorize P_Modify P_Evaluation
now <- liftIO $ getCurrentTime
userData <- currentUser
join . withUserAndPersist $ \u -> do
let user = u_username u
sbk <- Persist.submissionOfEvaluation ek
sck <- Persist.scoreOfEvaluation ek
case (sbk, sck) of
(Just _, Just _) -> return . errorPage $ strMsg "Impossible, submission and score have the same evaluation"
(Nothing, Just sk) -> do
let admined = True
if admined
then do Persist.modifyEvaluation ek e
-- Persist.saveFeedback sk (evaluationToFeedback now userData e)
let msg = Notification.NE_AssessmentEvaluationUpdated (u_name u) (scoreKey id sk)
affected <- do
ak <- Persist.assessmentOfScore sk
mck <- Persist.courseOfAssessment ak
mgk <- Persist.groupOfAssessment ak
recipient <- Persist.usernameOfScore sk
case (mck, mgk) of
(Just ck, _) -> do
cas <- Persist.courseAdmins ck
sbs <- Persist.subscribedToCourse ck
return $ nub ([recipient] ++ cas) \\ [user]
(_, Just gk) -> do
gas <- Persist.groupAdmins gk
sbs <- Persist.subscribedToGroup gk
return $ nub ([recipient] ++ gas) \\ [user]
_ -> return []
Persist.notifyUsers (Notification.Notification msg now $ Notification.Evaluation ek) affected
return (return ())
else return $ do
logMessage INFO . violation $
printf "The user tries to modify an evaluation (%s) that not belongs to him."
(show ek)
errorPage $ userError nonAdministratedSubmission
(Just sk, Nothing) -> do
admined <- Persist.isAdminedSubmission user sk
if admined
then do Persist.modifyEvaluation ek e
Persist.saveFeedback sk (evaluationToFeedback now userData e)
let msg = Notification.NE_AssignmentEvaluationUpdated (u_name u) (withSubmissionKey sk id)
affected <- do
ak <- Persist.assignmentOfSubmission sk
mck <- Persist.courseOfAssignment ak
mgk <- Persist.groupOfAssignment ak
submitter <- Persist.usernameOfSubmission sk
case (mck, mgk) of
(Just ck, _) -> do
cas <- Persist.courseAdmins ck
return $ nub ([submitter] ++ cas) \\ [user]
(_, Just gk) -> do
gas <- Persist.groupAdmins gk
return $ nub ([submitter] ++ gas) \\ [user]
_ -> return []
Persist.notifyUsers (Notification.Notification msg now $ Notification.Evaluation ek) affected
return (return ())
else return $ do
logMessage INFO . violation $
printf "The user tries to modify an evaluation (%s) that not belongs to him."
(show ek)
errorPage $ userError nonAdministratedSubmission
(Nothing, Nothing) -> return (return ())
createComment :: SubmissionKey -> Comment -> UserStory ()
createComment sk c = logAction INFO ("comments on " ++ show sk) $ do
authorize P_Open P_Submission
authorize P_Create P_Comment
join $ withUserAndPersist $ \u -> do
let user = u_username u
canComment <- Persist.canUserCommentOn user sk
admined <- Persist.isAdministratedSubmission user sk
attended <- Persist.isUserSubmission user sk
if (canComment && (admined || attended))
then do ck <- Persist.saveComment sk c
let Comment { commentAuthor = author, commentDate = now, comment = body } = c
let maxLength = 100
let maxLines = 5
let trimmedBody = (init $ unlines $ take maxLines $ lines $ take maxLength body) ++ "..."
let msg = Notification.NE_CommentCreated author (withSubmissionKey sk id) trimmedBody
ak <- Persist.assignmentOfSubmission sk
mck <- Persist.courseOfAssignment ak
mgk <- Persist.groupOfAssignment ak
submitter <- Persist.usernameOfSubmission sk
affected <- case (mck, mgk) of
(Just ck, _) -> do
cas <- Persist.courseAdmins ck
gk <- Persist.groupOfUserForCourse submitter ck
gas <- Persist.groupAdmins gk
return $ nub ([submitter] ++ cas ++ gas) \\ [user]
(_, Just gk) -> do
gas <- Persist.groupAdmins gk
return $ nub ([submitter] ++ gas) \\ [user]
_ -> return []
Persist.notifyUsers (Notification.Notification msg now $ Notification.Comment ck) affected
return (return ())
else return $ do
logMessage INFO . violation $ printf "The user tries to comment on a submission (%s) that not belongs to him" (show sk)
errorPage . userError $ msg_UserStoryError_NonCommentableSubmission "The submission is not commentable"
#ifdef TEST
-- Insert test feedback with the TestAgent only for testing purposes.
insertTestFeedback :: SubmissionKey -> FeedbackInfo -> UserStory ()
insertTestFeedback sk fb = do
authorize P_Create P_Feedback
persistence $ do
Persist.insertTestFeedback sk fb
Persist.finalizeTestFeedback sk
#endif
-- Test agent user story, that reads out all the feedbacks that the test daemon left
-- and saves them
testAgentFeedbacks :: UserStory ()
testAgentFeedbacks = do
authorize P_Open P_TestIncoming
authorize P_Open P_Submission
authorize P_Create P_Feedback
persistence $ do
feedbacks <- Persist.testFeedbacks
forM_ feedbacks (uncurry Persist.saveFeedback)
mapM_ Persist.deleteTestFeedbacks (nub $ map submission feedbacks)
where
submission = fst
userSubmissions :: Username -> AssignmentKey -> UserStory (Maybe UserSubmissionDesc)
userSubmissions s ak = logAction INFO msg $ do
authPerms userSubmissionDescPermissions
withUserAndPersist $ \u -> do
let user = u_username u
-- The admin can see the submission of students who are belonging to him
courses <- (map fst) <$> Persist.administratedCourses user
groups <- (map fst) <$> Persist.administratedGroups user
courseStudents <- concat <$> mapM Persist.subscribedToCourse courses
groupStudents <- concat <$> mapM Persist.subscribedToGroup groups
let students = nub (courseStudents ++ groupStudents)
case elem s students of
False -> return Nothing
True -> Just <$> Persist.userSubmissionDesc s ak
where
msg = join ["lists ",show s,"'s submissions for assignment ", show ak]
-- List all the related notifications for the active user and marks them
-- as seen if their state is new.
notifications :: UserStory [(Notification.Notification, Notification.NotificationState, Notification.NotificationReference)]
notifications = do
now <- liftIO $ getCurrentTime
orderedNotifs <- withUserAndPersist $ \u -> do
let user = u_username u
notifs <- Persist.notificationsOfUser user (Just notificationLimit)
forM notifs (\(k,s,_p) -> do
notif <- Persist.loadNotification k
notifRef <- Persist.notificationReference (Notification.notifType notif)
when (s == Notification.New) $ Persist.markSeen user k
return (notif, s, notifRef))
return orderedNotifs
noOfUnseenNotifications :: UserStory Int
noOfUnseenNotifications = do
withUserAndPersist $ Persist.noOfUnseenNotifications . u_username
-- Helper function: checks if there at least one submission for the given
isThereSubmissionPersist = fmap (not . null) . Persist.submissionsForAssignment
-- | Checks if there is at least one submission for the given assignment
isThereASubmission :: AssignmentKey -> UserStory Bool
isThereASubmission ak = logAction INFO ("" ++ show ak) $ do
authorize P_Open P_Assignment
isAdministratedAssignment ak
persistence $ isThereSubmissionPersist ak
-- | Modify the given assignment but keeps the evaluation type if there is
-- a submission for the given assignment, also shows a warning message if the
-- modification of the assignment type is not viable.
modifyAssignment :: AssignmentKey -> Assignment -> TCModification -> UserStory ()
modifyAssignment ak a tc = logAction INFO ("modifies assignment " ++ show ak) $ do
authorize P_Modify P_Assignment
join . withUserAndPersist $ \u -> do
let user = u_username u
admined <- Persist.isAdministratedAssignment user ak
if admined
then do hasSubmission <- isThereSubmissionPersist ak
new <- if hasSubmission
then do -- Overwrite the assignment type with the old one
-- if there is submission for the given assignment
ev <- Assignment.evType <$> Persist.loadAssignment ak
return (a { Assignment.evType = ev })
else return a
Persist.modifyAssignment ak new
testCaseModificationForAssignment user ak tc
now <- liftIO getCurrentTime
let msg = Notification.NE_AssignmentUpdated (u_name u) (Assignment.name a)
mck <- Persist.courseOfAssignment ak
mgk <- Persist.groupOfAssignment ak
affected <- case (mck, mgk) of
(Just ck, _) -> do
cas <- Persist.courseAdmins ck
gks <- Persist.groupKeysOfCourse ck
gas <- concat <$> mapM Persist.groupAdmins gks
return $ nub (cas ++ gas) \\ [user]
(_, Just gk) -> do
gas <- Persist.groupAdmins gk
return $ nub gas \\ [user]
_ -> return []
Persist.notifyUsers (Notification.Notification msg now $ Notification.Assignment ak) affected
if (Assignment.start a <= now)
then do
affected <- case (mck, mgk) of
(Just ck, _) -> do
cas <- Persist.courseAdmins ck
gks <- Persist.groupKeysOfCourse ck
gas <- concat <$> mapM Persist.groupAdmins gks
sbs <- Persist.subscribedToCourse ck
return $ nub (sbs \\ (cas ++ gas ++ [user]))
(_, Just gk) -> do
gas <- Persist.groupAdmins gk
sbs <- Persist.subscribedToGroup gk
return $ nub (sbs \\ (gas ++ [user]))
_ -> return []
Persist.notifyUsers (Notification.Notification msg now $ Notification.Assignment ak) affected
else do
nks <- Persist.notificationsOfAssignment ak
forM_ nks $ \nk -> do
mNot <- do
nt <- Persist.loadNotification nk
case (mck, mgk, Notification.notifEvent nt) of
(Just ck, _, Notification.NE_CourseAssignmentCreated _ _ _) -> return $ Just nt
(_, Just gk, Notification.NE_GroupAssignmentCreated _ _ _ _) -> return $ Just nt
_ -> return Nothing
case mNot of
Just n -> do
let newDate = Assignment.start a
let n' = n { Notification.notifDate = newDate }
Persist.updateNotification nk n'
Persist.updateUserNotification nk newDate
_ -> return ()
if and [hasSubmission, Assignment.evType a /= Assignment.evType new]
then return . putStatusMessage . msg_UserStory_EvalTypeWarning $ concat
[ "The evaluation type of the assignment is not modified. "
, "A solution is submitted already."
]
else (return (return ()))
else return $ do
logMessage INFO . violation $ printf "User tries to modify the assignment: (%s)" (assignmentKeyMap id ak)
errorPage $ userError nonAdministratedAssignment
-- * Guards
-- Checks with the given guard function if the user has passed the guard,
-- otherwise logs a violation printf message, and renders the error page with
-- the given user error
guard
:: (Show a)
=> (Username -> a -> Persist Bool) -- Guard
-> String -- Violation printf message
-> UserError -- Error for the error page
-> a -- The value for the guard
-> UserStory ()
guard g m e x = do
u <- username
join . persistence $ do
passed <- g u x
if passed
then (return (return ()))
else return $ do
logMessage INFO . violation $ printf m (show x)
errorPage e
-- Checks if the given course is administrated by the actual user and
-- throws redirects to the error page if not, otherwise do nothing
isAdministratedCourse :: CourseKey -> UserStory ()
isAdministratedCourse = guard
Persist.isAdministratedCourse
"The user tries to access a course (%s) which is not administrated by him."
(userError nonAdministratedCourse)
-- Checks if the given group is administrated by the actual user and
-- throws redirects to the error page if not, otherwise do nothing
isAdministratedGroup :: GroupKey -> UserStory ()
isAdministratedGroup = guard
Persist.isAdministratedGroup
"The user tries to access a group (%s) which is not administrated by him."
(userError nonAdministratedGroup)
-- Checks if the given assignment is administrated by the actual user and
-- throws redirects to the error page if not, otherwise do nothing
isAdministratedAssignment :: AssignmentKey -> UserStory ()
isAdministratedAssignment = guard
Persist.isAdministratedAssignment
"The user tries to access an assignment (%s) which is not administrated by him."
(userError nonAdministratedAssignment)
-- Checks if the given assessment is administrated by the actual user and
-- throws redirects to the error page if not, otherwise do nothing
isAdministratedAssessment :: AssessmentKey -> UserStory ()
isAdministratedAssessment = guard
Persist.isAdministratedAssessment
"User tries to modify the assessment (%s) which is not administrated by him."
(userError nonAdministratedAssessment)
-- Checks if the given assignment is an assignment of a course or group that
-- the users attend otherwise, renders the error page
isUsersAssignment :: AssignmentKey -> UserStory ()
isUsersAssignment = guard
Persist.isUsersAssignment
"The user tries to access an assignment (%s) which is not of him's."
(userError nonRelatedAssignment)
isAdministratedTestScript :: TestScriptKey -> UserStory ()
isAdministratedTestScript = guard
Persist.isAdministratedTestScript
"The user tries to access a test script (%s) which is not administrated by him."
(userError nonAdministratedTestScript)
-- Checks if the submission is submitted by the user, or is part of a course
-- or group that the user administrates
isAccessibleSubmission :: SubmissionKey -> UserStory ()
isAccessibleSubmission = guard
Persist.isAccessibleSubmission
"The user tries to download a submission (%s) which is not accessible for him."
(userError nonAccessibleSubmission)
-- This action implements a check similar that of `isAccessibleSubmission` but
-- it also considers if the assignment of the submission is in ballot box mode.
isAccessibleBallotBoxSubmission :: SubmissionKey -> UserStory ()
isAccessibleBallotBoxSubmission = guard
Persist.isAccessibleBallotBoxSubmission
"The user tries to download a submission (%s) which is not accessible for him."
(userError nonAccessibleSubmission)
doesBlockSubmissionView :: SubmissionKey -> UserStory ()
doesBlockSubmissionView = guard
(const Persist.doesBlockSubmissionView)
"The user tries to access a blocked submission (%s)."
(userError blockedSubmission)
doesBlockAssignmentView :: AssignmentKey -> UserStory ()
doesBlockAssignmentView = guard
(const Persist.doesBlockAssignmentView)
"The user tries to access a blocked submissions (%s)."
(userError blockedSubmission)
-- * User Story combinators
-- * Tools
-- Creates a message adding the "VIOLATION: " preffix to it
violation :: String -> String
violation = ("[GUARD VIOLATION]: " ++)
asksUserContainer :: UserStory (UserContainer UserState)
asksUserContainer = CMR.asks (userContainer . fst)
asksLogger :: UserStory Logger
asksLogger = CMR.asks (logger . fst)
asksPersistInterpreter :: UserStory Persist.Interpreter
asksPersistInterpreter = CMR.asks (persistInterpreter . fst)
asksI18N :: UserStory I18N
asksI18N = CMR.asks snd
-- | The 'logAction' first logs the message after runs the given operation
logAction :: LogLevel -> String -> UserStory a -> UserStory a
logAction level msg s = do
logMessage level (concat [msg, " ..."])
x <- s
logMessage level (concat [msg, " ... DONE"])
return x
withUserAndPersist :: (User -> Persist a) -> UserStory a
withUserAndPersist f = do
u <- currentUser
persistence (f u)
-- | Lifting a persistence action, if some error happens
-- during the action we create a unique hash ticket and we display
-- the ticket to the user, and log the original message with the
-- ticket itself
persistence :: Persist a -> UserStory a
persistence m = do
interp <- asksPersistInterpreter
x <- liftIO . try $ Persist.runPersist interp m
case x of
(Left e) -> do
-- Exception happened somewhere
up <- userPart
let err = showSomeException e
let xid = encodeMessage (concat [up, " ", err])
logMessage ERROR $ concat ["Exception in persistence layer: ", err, " XID: ", xid]
CME.throwError $ userParamError
(msg_UserStoryError_XID "Some internal error happened, XID: %s")
xid
(Right (Left e)) -> do
-- No exception but error processing the persistence command
up <- userPart
let xid = encodeMessage (concat [up, " ", e])
logMessage ERROR $ concat ["Persistence error: ", e, "XID: ", xid]
CME.throwError $ userParamError
(msg_UserStoryError_XID "Some internal error happened, XID: %s")
xid
(Right (Right x)) -> return x -- Everything went fine
where
showSomeException :: SomeException -> String
showSomeException = show
encodeMessage :: String -> String
encodeMessage = flip showHex "" . abs . hash
userPart = (userStateCata userNotLoggedIn registration testAgent loggedIn) <$> CMS.get
where
userNotLoggedIn = "Not logged in user!"
registration = "Registration"
testAgent = "Test Agent"
loggedIn _ ui _ _ _ t _ _ = concat [Entity.uid id ui, " ", t]
-- * User Error Messages
nonAdministratedCourse = msg_UserStoryError_NonAdministratedCourse "The course is not administrated by you"
nonAdministratedGroup = msg_UserStoryError_NonAdministratedGroup "This group is not administrated by you."
nonAdministratedAssignment = msg_UserStoryError_NonAdministratedAssignment "This assignment is not administrated by you."
nonAdministratedAssessment = msg_UserStoryError_NonAdministratedAssessment "This assessment is not administrated by you."
nonAdministratedSubmission = msg_UserStoryError_NonAdministratedSubmission "The submission is not administrated by you."
nonAdministratedTestScript = msg_UserStoryError_NonAdministratedTestScript "The test script is not administrated by you."
nonRelatedAssignment = msg_UserStoryError_NonRelatedAssignment "The assignment is not belongs to you."
nonAccessibleSubmission = msg_UserStoryError_NonAccessibleSubmission "The submission is not belongs to you."
blockedSubmission = msg_UserStoryError_BlockedSubmission "The submission is blocked by an isolated assignment."
nonAccessibleScore = msg_UserStoryError_NonAccessibleScore "The score does not belong to you."
-- * constants
notificationLimit :: Int
notificationLimit = 100
|
andorp/bead
|
src/Bead/Controller/UserStories.hs
|
bsd-3-clause
| 83,789
| 751
| 23
| 20,943
| 14,119
| 7,944
| 6,175
| 1,491
| 12
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-|
This module exports vect-floating instances to make Vec2, Normal2, Vec3, Normal3, Vec4, Normal4, Quaternion, and UnitQuaternion
compatible with accelerate.
The instances are defined:
'Vec2' Accelerate Instances:
* @instance 'Elt' a => 'Elt' ('Vec2' a)@
* @instance 'IsTuple' ('Vec2' a)@
* @instance ('Lift' 'Exp' a, 'Elt' ('Plain' a)) => 'Lift' 'Exp' ('Vec2' a)@
* @instance ('Elt' a) => 'Unlift' 'Exp' ('Vec2' ('Exp' a))@
'Normal2' Accelerate Instances:
* @instance ('Elt' a, 'Floating' a) => 'Elt' ('Normal2' a)@
* @instance 'Floating' a => 'IsTuple' ('Normal2' a)@
* @instance ('Lift' 'Exp' a, 'Elt' ('Plain' a), 'Floating' a, 'Floating' ('Plain' a)) => 'Lift' 'Exp' ('Normal2' a)@
* @instance ('Elt' a, 'Floating' a, 'IsFloating' a) => 'Unlift' 'Exp' ('Normal2' ('Exp' a))@
'Vec3' Accelerate Instances:
* @instance 'Elt' a => 'Elt' ('Vec3' a)@
* @instance 'IsTuple' ('Vec3' a)@
* @instance ('Lift' 'Exp' a, 'Elt' ('Plain' a)) => 'Lift' 'Exp' ('Vec3' a)@
* @instance 'Elt' a => 'Unlift' 'Exp' ('Vec3' ('Exp' a))@
'Normal3' Accelerate Instances:
* @instance ('Elt' a, 'Floating' a) => 'Elt' ('Normal3' a)@
* @instance 'Floating' a => 'IsTuple' ('Normal3' a)@
* @instance ('Lift' 'Exp' a, 'Elt' ('Plain' a), 'Floating' a, 'Floating' ('Plain' a)) => 'Lift' 'Exp' ('Normal3' a)@
* @instance ('Elt' a, 'Floating' a, 'IsFloating' a) => 'Unlift' 'Exp' ('Normal3' ('Exp' a))@
'Vec4' Accelerate Instances:
* @instance 'Elt' a => 'Elt' ('Vec4' a)@
* @instance 'IsTuple' ('Vec4' a)@
* @instance ('Lift' 'Exp' a, 'Elt' ('Plain' a)) => 'Lift' 'Exp' ('Vec4' a)@
* @instance 'Elt' a => 'Unlift' 'Exp' ('Vec4' ('Exp' a))@
'Normal4' Accelerate Instances:
* @instance ('Elt' a, 'Floating' a) => 'Elt' ('Normal4' a)@
* @instance 'Floating' a => 'IsTuple' ('Normal4' a)@
* @instance ('Lift' 'Exp' a, 'Elt' ('Plain' a), 'Floating' a, 'Floating' ('Plain' a)) => 'Lift' 'Exp' ('Normal4' a)@
* @instance ('Elt' a, 'Floating' a, 'IsFloating' a) => 'Unlift' 'Exp' ('Normal4' ('Exp' a))@
'Quaternion' Accelerate Instances:
* @instance 'Elt' a => 'Elt' ('Quaternion' a)@
* @instance 'IsTuple' ('Quaternion' a)@
* @instance ('Lift' 'Exp' a, 'Elt' ('Plain' a)) => 'Lift' 'Exp' ('Quaternion' a)@
* @instance 'Elt' a => 'Unlift' 'Exp' ('Quaternion' ('Exp' a))@
'UnitQuaternion' Accelerate Instances:
* @instance ('Elt' a, 'Floating' a) => 'Elt' ('UnitQuaternion' a)@
* @instance 'Floating' a => 'IsTuple' ('UnitQuaternion' a)@
* @instance ('Lift' 'Exp' a, 'Elt' ('Plain' a), 'Floating' a, 'Floating' ('Plain' a)) => 'Lift' 'Exp' ('UnitQuaternion' a)@
* @instance ('Elt' a, 'IsFloating' a) => 'Unlift' 'Exp' ('UnitQuaternion' ('Exp' a))@
-}
module Data.Vect.Floating.Accelerate.Instances () where
import Data.Array.Accelerate
import Data.Array.Accelerate.Smart
import Data.Array.Accelerate.Tuple
import Data.Array.Accelerate.Array.Sugar
import Data.Vect.Floating
import Data.Vect.Floating.Util.Quaternion
{- Vec2 Accelerate Instances -}
type instance EltRepr (Vec2 a) = EltRepr (a,a)
type instance EltRepr' (Vec2 a) = EltRepr' (a,a)
instance Elt a => Elt (Vec2 a) where
eltType (_ :: Vec2 a) = eltType (undefined :: (a,a))
toElt p = let (x,y) = toElt p in Vec2 x y
fromElt (Vec2 x y) = fromElt (x,y)
eltType' (_ :: Vec2 a) = eltType (undefined :: (a,a))
toElt' p = let (x,y) = toElt p in Vec2 x y
fromElt' (Vec2 x y) = fromElt (x,y)
instance IsTuple (Vec2 a) where
type TupleRepr (Vec2 a) = TupleRepr (a,a)
fromTuple (Vec2 x y) = fromTuple (x,y)
toTuple t = let (x,y) = toTuple t in Vec2 x y
instance (Lift Exp a, Elt (Plain a)) => Lift Exp (Vec2 a) where
type Plain (Vec2 a) = Vec2 (Plain a)
lift (Vec2 x y) = Exp . Tuple $ NilTup `SnocTup` lift x `SnocTup` lift y
instance (Elt a) => Unlift Exp (Vec2 (Exp a)) where
unlift t = let x = Exp $ SuccTupIdx ZeroTupIdx `Prj` t
y = Exp $ ZeroTupIdx `Prj` t
in Vec2 x y
{- Normal2 Accelerate Instances -}
type instance EltRepr (Normal2 a) = EltRepr (a,a)
type instance EltRepr' (Normal2 a) = EltRepr' (a,a)
instance (Elt a, Floating a) => Elt (Normal2 a) where
eltType (_ :: Normal2 a) = eltType (undefined :: (a,a))
toElt p = let (x,y) = toElt p in toNormalUnsafe (Vec2 x y)
fromElt n = let (Vec2 x y) = fromNormal n in fromElt (x,y)
eltType' (_ :: Normal2 a) = eltType (undefined :: (a,a))
toElt' p = let (x,y) = toElt p in toNormalUnsafe (Vec2 x y)
fromElt' n = let (Vec2 x y) = fromNormal n in fromElt (x,y)
instance Floating a => IsTuple (Normal2 a) where
type TupleRepr (Normal2 a) = TupleRepr (a,a)
fromTuple n = let Vec2 x y = fromNormal n in fromTuple (x,y)
toTuple t = let (x,y) = toTuple t in toNormalUnsafe (Vec2 x y)
instance (Lift Exp a, Elt (Plain a), Floating a, Floating (Plain a)) => Lift Exp (Normal2 a) where
type Plain (Normal2 a) = Normal2 (Plain a)
lift n = let (Vec2 x y) = fromNormal n in Exp . Tuple $ NilTup `SnocTup` lift x `SnocTup` lift y
instance (Elt a, Floating a, IsFloating a) => Unlift Exp (Normal2 (Exp a)) where
unlift t = let x = Exp $ SuccTupIdx ZeroTupIdx `Prj` t
y = Exp $ ZeroTupIdx `Prj` t
in toNormalUnsafe (Vec2 x y)
{- Vec3 Accelerate Instances -}
type instance EltRepr (Vec3 a) = EltRepr (a,a,a)
type instance EltRepr' (Vec3 a) = EltRepr' (a,a,a)
instance Elt a => Elt (Vec3 a) where
eltType (_ :: Vec3 a) = eltType (undefined :: (a,a,a))
toElt p = let (x,y,z) = toElt p in Vec3 x y z
fromElt (Vec3 x y z) = fromElt (x,y,z)
eltType' (_ :: Vec3 a) = eltType (undefined :: (a,a,a))
toElt' p = let (x,y,z) = toElt p in Vec3 x y z
fromElt' (Vec3 x y z) = fromElt (x,y,z)
instance IsTuple (Vec3 a) where
type TupleRepr (Vec3 a) = TupleRepr (a,a,a)
fromTuple (Vec3 x y z) = fromTuple (x,y,z)
toTuple t = let (x,y,z) = toTuple t in Vec3 x y z
instance (Lift Exp a, Elt (Plain a)) => Lift Exp (Vec3 a) where
type Plain (Vec3 a) = Vec3 (Plain a)
lift (Vec3 x y z) = Exp . Tuple $ NilTup `SnocTup` lift x `SnocTup` lift y `SnocTup` lift z
instance Elt a => Unlift Exp (Vec3 (Exp a)) where
unlift t = let x = Exp $ SuccTupIdx (SuccTupIdx ZeroTupIdx) `Prj` t
y = Exp $ SuccTupIdx ZeroTupIdx `Prj` t
z = Exp $ ZeroTupIdx `Prj` t
in Vec3 x y z
{- Normal3 Accelerate Instances -}
type instance EltRepr (Normal3 a) = EltRepr (a,a,a)
type instance EltRepr' (Normal3 a) = EltRepr' (a,a,a)
instance (Elt a, Floating a) => Elt (Normal3 a) where
eltType (_ :: Normal3 a) = eltType (undefined :: (a,a,a))
toElt p = let (x,y,z) = toElt p in toNormalUnsafe (Vec3 x y z)
fromElt n = let (Vec3 x y z) = fromNormal n in fromElt (x,y,z)
eltType' (_ :: Normal3 a) = eltType (undefined :: (a,a,a))
toElt' p = let (x,y,z) = toElt p in toNormalUnsafe (Vec3 x y z)
fromElt' n = let (Vec3 x y z) = fromNormal n in fromElt (x,y,z)
instance Floating a => IsTuple (Normal3 a) where
type TupleRepr (Normal3 a) = TupleRepr (a,a,a)
fromTuple n = let Vec3 x y z = fromNormal n in fromTuple (x,y,z)
toTuple t = let (x,y,z) = toTuple t in toNormalUnsafe (Vec3 x y z)
instance (Lift Exp a, Elt (Plain a), Floating a, Floating (Plain a)) => Lift Exp (Normal3 a) where
type Plain (Normal3 a) = Normal3 (Plain a)
lift n = let (Vec3 x y z) = fromNormal n in Exp . Tuple $ NilTup `SnocTup` lift x `SnocTup` lift y `SnocTup` lift z
instance (Elt a, Floating a, IsFloating a) => Unlift Exp (Normal3 (Exp a)) where
unlift t = let x = Exp $ SuccTupIdx (SuccTupIdx ZeroTupIdx) `Prj` t
y = Exp $ SuccTupIdx ZeroTupIdx `Prj` t
z = Exp $ ZeroTupIdx `Prj` t
in toNormalUnsafe (Vec3 x y z)
{- Vec4 Accelerate Instances -}
type instance EltRepr (Vec4 a) = EltRepr (a,a,a,a)
type instance EltRepr' (Vec4 a) = EltRepr' (a,a,a,a)
instance Elt a => Elt (Vec4 a) where
eltType (_ :: Vec4 a) = eltType (undefined :: (a,a,a,a))
toElt p = let (x,y,z,w) = toElt p in Vec4 x y z w
fromElt (Vec4 x y z w) = fromElt (x,y,z,w)
eltType' (_ :: Vec4 a) = eltType (undefined :: (a,a,a,a))
toElt' p = let (x,y,z,w) = toElt p in Vec4 x y z w
fromElt' (Vec4 x y z w) = fromElt (x,y,z,w)
instance IsTuple (Vec4 a) where
type TupleRepr (Vec4 a) = TupleRepr (a,a,a,a)
fromTuple (Vec4 x y z w) = fromTuple (x,y,z,w)
toTuple t = let (x,y,z,w) = toTuple t in Vec4 x y z w
instance (Lift Exp a, Elt (Plain a)) => Lift Exp (Vec4 a) where
type Plain (Vec4 a) = Vec4 (Plain a)
lift (Vec4 x y z w) = Exp . Tuple $ NilTup `SnocTup` lift x `SnocTup` lift y `SnocTup` lift z `SnocTup` lift w
instance Elt a => Unlift Exp (Vec4 (Exp a)) where
unlift t = let x = Exp $ SuccTupIdx (SuccTupIdx (SuccTupIdx ZeroTupIdx)) `Prj` t
y = Exp $ SuccTupIdx (SuccTupIdx ZeroTupIdx) `Prj` t
z = Exp $ SuccTupIdx ZeroTupIdx `Prj` t
w = Exp $ ZeroTupIdx `Prj` t
in Vec4 x y z w
{- Normal4 Accelerate Instances -}
type instance EltRepr (Normal4 a) = EltRepr (a,a,a,a)
type instance EltRepr' (Normal4 a) = EltRepr' (a,a,a,a)
instance (Elt a, Floating a) => Elt (Normal4 a) where
eltType (_ :: Normal4 a) = eltType (undefined :: (a,a,a,a))
toElt p = let (x,y,z,w) = toElt p in toNormalUnsafe (Vec4 x y z w)
fromElt n = let (Vec4 x y z w) = fromNormal n in fromElt (x,y,z,w)
eltType' (_ :: Normal4 a) = eltType (undefined :: (a,a,a,a))
toElt' p = let (x,y,z,w) = toElt p in toNormalUnsafe (Vec4 x y z w)
fromElt' n = let (Vec4 x y z w) = fromNormal n in fromElt (x,y,z,w)
instance Floating a => IsTuple (Normal4 a) where
type TupleRepr (Normal4 a) = TupleRepr (a,a,a,a)
fromTuple n = let Vec4 x y z w = fromNormal n in fromTuple (x,y,z,w)
toTuple t = let (x,y,z,w) = toTuple t in toNormalUnsafe (Vec4 x y z w)
instance (Lift Exp a, Elt (Plain a), Floating a, Floating (Plain a)) => Lift Exp (Normal4 a) where
type Plain (Normal4 a) = Normal4 (Plain a)
lift n = let (Vec4 x y z w) = fromNormal n in Exp . Tuple $ NilTup `SnocTup` lift x `SnocTup` lift y `SnocTup` lift z `SnocTup` lift w
instance (Elt a, Floating a, IsFloating a) => Unlift Exp (Normal4 (Exp a)) where
unlift t = let x = Exp $ SuccTupIdx (SuccTupIdx (SuccTupIdx ZeroTupIdx)) `Prj` t
y = Exp $ SuccTupIdx (SuccTupIdx ZeroTupIdx) `Prj` t
z = Exp $ SuccTupIdx ZeroTupIdx `Prj` t
w = Exp $ ZeroTupIdx `Prj` t
in toNormalUnsafe (Vec4 x y z w)
{- Quaternion Accelerate Instances -}
type instance EltRepr (Quaternion a) = EltRepr (a,a,a,a)
type instance EltRepr' (Quaternion a) = EltRepr' (a,a,a,a)
instance Elt a => Elt (Quaternion a) where
eltType (_ :: Quaternion a) = eltType (undefined :: (a,a,a,a))
toElt p = let (x,y,z,w) = toElt p in Q (Vec4 x y z w)
fromElt (Q (Vec4 x y z w)) = fromElt (x,y,z,w)
eltType' (_ :: Quaternion a) = eltType (undefined :: (a,a,a,a))
toElt' p = let (x,y,z,w) = toElt p in Q (Vec4 x y z w)
fromElt' (Q (Vec4 x y z w)) = fromElt (x,y,z,w)
instance IsTuple (Quaternion a) where
type TupleRepr (Quaternion a) = TupleRepr (a,a,a,a)
fromTuple (Q (Vec4 x y z w)) = fromTuple (x,y,z,w)
toTuple t = let (x,y,z,w) = toTuple t in Q (Vec4 x y z w)
instance (Lift Exp a, Elt (Plain a)) => Lift Exp (Quaternion a) where
type Plain (Quaternion a) = Quaternion (Plain a)
lift (Q (Vec4 x y z w)) = Exp . Tuple $ NilTup `SnocTup` lift x `SnocTup` lift y `SnocTup` lift z `SnocTup` lift w
instance Elt a => Unlift Exp (Quaternion (Exp a)) where
unlift t = let x = Exp $ SuccTupIdx (SuccTupIdx (SuccTupIdx ZeroTupIdx)) `Prj` t
y = Exp $ SuccTupIdx (SuccTupIdx ZeroTupIdx) `Prj` t
z = Exp $ SuccTupIdx ZeroTupIdx `Prj` t
w = Exp $ ZeroTupIdx `Prj` t
in Q $ Vec4 x y z w
{- Unit Quaternion Accelerate Instances -}
type instance EltRepr (UnitQuaternion a) = EltRepr (a,a,a,a)
type instance EltRepr' (UnitQuaternion a) = EltRepr' (a,a,a,a)
instance (Elt a, Floating a) => Elt (UnitQuaternion a) where
eltType (_ :: UnitQuaternion a) = eltType (undefined :: (a,a,a,a))
toElt p = let (x,y,z,w) = toElt p in toNormalUnsafe $ Q (Vec4 x y z w)
fromElt u = let (Q (Vec4 x y z w)) = fromNormal u in fromElt (x,y,z,w)
eltType' (_ :: UnitQuaternion a) = eltType (undefined :: (a,a,a,a))
toElt' p = let (x,y,z,w) = toElt p in toNormalUnsafe $ Q (Vec4 x y z w)
fromElt' u = let (Q (Vec4 x y z w)) = fromNormal u in fromElt (x,y,z,w)
instance Floating a => IsTuple (UnitQuaternion a) where
type TupleRepr (UnitQuaternion a) = TupleRepr (a,a,a,a)
fromTuple u = let (Q (Vec4 x y z w)) = fromNormal u in fromTuple (x,y,z,w)
toTuple t = let (x,y,z,w) = toTuple t in toNormalUnsafe $ Q (Vec4 x y z w)
instance (Lift Exp a, Elt (Plain a), Floating a, Floating (Plain a)) => Lift Exp (UnitQuaternion a) where
type Plain (UnitQuaternion a) = UnitQuaternion (Plain a)
lift u = let (Q (Vec4 x y z w)) = fromNormal u in Exp . Tuple $ NilTup `SnocTup` lift x `SnocTup` lift y `SnocTup` lift z `SnocTup` lift w
instance (Elt a, IsFloating a) => Unlift Exp (UnitQuaternion (Exp a)) where
unlift t = let x = Exp $ SuccTupIdx (SuccTupIdx (SuccTupIdx ZeroTupIdx)) `Prj` t
y = Exp $ SuccTupIdx (SuccTupIdx ZeroTupIdx) `Prj` t
z = Exp $ SuccTupIdx ZeroTupIdx `Prj` t
w = Exp $ ZeroTupIdx `Prj` t
in toNormalUnsafe . Q $ Vec4 x y z w
|
cpdurham/vect-floating-accelerate
|
src/Data/Vect/Floating/Accelerate/Instances.hs
|
bsd-3-clause
| 13,833
| 2
| 16
| 3,256
| 5,799
| 3,034
| 2,765
| -1
| -1
|
module Assets.Internal
(
Assets(..),
animations
) where
import Control.Lens
import Data.Map
import Animation
data Assets = Assets {
_animations :: Map String Animation
}
makeLenses ''Assets
|
alexisVallet/haskell-shmup
|
Assets/Internal.hs
|
bsd-3-clause
| 229
| 0
| 9
| 65
| 59
| 34
| 25
| -1
| -1
|
module Scurry.KeepAlive (
keepAliveThread
) where
import Control.Concurrent.STM.TChan
import Control.Monad (forever)
import GHC.Conc
import Scurry.Comm.Message
import Scurry.Comm.Util
import Scurry.State
import Scurry.Peer
import Scurry.Types.Threads
import Scurry.Types.Network
import Scurry.Util
isMVarFull :: (MVar a) -> IO Bool
isMVarFull mv = do
var <- tryTakeMVar mv
case var of
(Just v) -> putMVar mv v >> return True
Nothing -> return False
keepAliveThread :: StateRef -> SockWriterChan -> (MVar (ScurryAddress, ScurryMask)) -> IO ()
keepAliveThread sr chan tap_mv = forever $ do
peers <- getPeers sr
myref <- getMyRecord sr
mapM_ (messenger myref) peers
threadDelay (sToMs 10)
b <- isMVarFull tap_mv
if b then return ()
else mapM_ reqaddr peers
where sendMsg dest msg = atomically $ writeTChan chan (dest,msg)
messenger rec pr = sendMsg (DestSingle (peerEndPoint pr)) (SKeepAlive rec)
reqaddr pr = sendMsg (DestSingle (peerEndPoint pr)) SAddrRequest
{-
case mac of
Nothing -> do mymac <- getMAC sr
sendMsg (DestSingle addr) (SJoin mymac)
(Just _) -> sendMsg (DestSingle addr) (SKeepAlive)
-}
|
dmagyar/scurry
|
src/Scurry/KeepAlive.hs
|
bsd-3-clause
| 1,325
| 0
| 11
| 382
| 361
| 183
| 178
| 30
| 2
|
{-# LINE 1 "Data.Function.hs" #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Function
-- Copyright : Nils Anders Danielsson 2006
-- , Alexander Berntsen 2014
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Simple combinators working solely on and with functions.
--
-----------------------------------------------------------------------------
module Data.Function
( -- * "Prelude" re-exports
id, const, (.), flip, ($)
-- * Other combinators
, (&)
, fix
, on
) where
import GHC.Base ( ($), (.), id, const, flip )
infixl 0 `on`
infixl 1 &
-- | @'fix' f@ is the least fixed point of the function @f@,
-- i.e. the least defined @x@ such that @f x = x@.
fix :: (a -> a) -> a
fix f = let x = f x in x
-- | @(*) \`on\` f = \\x y -> f x * f y@.
--
-- Typical usage: @'Data.List.sortBy' ('compare' \`on\` 'fst')@.
--
-- Algebraic properties:
--
-- * @(*) \`on\` 'id' = (*)@ (if @(*) ∉ {⊥, 'const' ⊥}@)
--
-- * @((*) \`on\` f) \`on\` g = (*) \`on\` (f . g)@
--
-- * @'flip' on f . 'flip' on g = 'flip' on (g . f)@
-- Proofs (so that I don't have to edit the test-suite):
-- (*) `on` id
-- =
-- \x y -> id x * id y
-- =
-- \x y -> x * y
-- = { If (*) /= _|_ or const _|_. }
-- (*)
-- (*) `on` f `on` g
-- =
-- ((*) `on` f) `on` g
-- =
-- \x y -> ((*) `on` f) (g x) (g y)
-- =
-- \x y -> (\x y -> f x * f y) (g x) (g y)
-- =
-- \x y -> f (g x) * f (g y)
-- =
-- \x y -> (f . g) x * (f . g) y
-- =
-- (*) `on` (f . g)
-- =
-- (*) `on` f . g
-- flip on f . flip on g
-- =
-- (\h (*) -> (*) `on` h) f . (\h (*) -> (*) `on` h) g
-- =
-- (\(*) -> (*) `on` f) . (\(*) -> (*) `on` g)
-- =
-- \(*) -> (*) `on` g `on` f
-- = { See above. }
-- \(*) -> (*) `on` g . f
-- =
-- (\h (*) -> (*) `on` h) (g . f)
-- =
-- flip on (g . f)
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
(.*.) `on` f = \x y -> f x .*. f y
-- | '&' is a reverse application operator. This provides notational
-- convenience. Its precedence is one higher than that of the forward
-- application operator '$', which allows '&' to be nested in '$'.
--
-- @since 4.8.0.0
(&) :: a -> (a -> b) -> b
x & f = f x
|
phischu/fragnix
|
builtins/base/Data.Function.hs
|
bsd-3-clause
| 2,425
| 0
| 9
| 631
| 294
| 202
| 92
| 17
| 1
|
{-# LANGUAGE RankNTypes #-}
-- | Helpers for 'BlockProperty'.
module Test.Pos.Block.Property
( blockPropertySpec
) where
import Universum
import Test.Hspec (Spec)
import Test.Hspec.QuickCheck (prop)
import Pos.Chain.Delegation (HasDlgConfiguration)
import Pos.Chain.Genesis as Genesis (Config)
import Pos.Chain.Update (HasUpdateConfiguration, updateConfiguration)
import Test.Pos.Block.Logic.Mode (BlockProperty,
blockPropertyTestable)
import Test.QuickCheck.Property (Testable)
-- | Specialized version of 'prop' function from 'hspec'.
blockPropertySpec ::
(HasDlgConfiguration, HasUpdateConfiguration, Testable a)
=> String
-> (Genesis.Config -> BlockProperty a)
-> Spec
blockPropertySpec description bp =
prop description (blockPropertyTestable updateConfiguration bp)
|
input-output-hk/pos-haskell-prototype
|
generator/test/Test/Pos/Block/Property.hs
|
mit
| 917
| 0
| 10
| 220
| 170
| 103
| 67
| -1
| -1
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
module CO4.Monad
( CO4, SAT, newId, getCallStackTrace, isProfileRun, setProfileRun, abortWithStackTrace
, runCO4, withCallCache, withAdtCache, traced, profiledCase
)
where
import Control.Monad.State.Strict
import Data.List (nub)
import qualified Satchmo.Core.SAT.Minisat
import Satchmo.Core.MonadSAT (MonadSAT (..))
import qualified Satchmo.Core.MonadSAT as MonadSAT
import CO4.Cache
import CO4.Profiling as P
import CO4.Stack
import {-# SOURCE #-} CO4.EncodedAdt (Primitive,EncodedAdt,makeWithId,constantConstructorIndex)
type SAT = Satchmo.Core.SAT.Minisat.SAT
type AdtCacheKey = ([Primitive], [EncodedAdt], Bool)
type CallCacheKey = (String, [EncodedAdt])
type AdtCache = Cache AdtCacheKey Int
type CallCache = Cache CallCacheKey EncodedAdt
data CO4Data = CO4Data {
idCounter :: ! Int
, adtCache :: ! AdtCache
, callCache :: ! CallCache
, profile :: ! Profile
, callStack :: ! CallStack
, profileRun :: ! Bool
}
emptyData :: CO4Data
emptyData = CO4Data 0 emptyCache emptyCache emptyProfile emptyStack False
newtype CO4 a = CO4 { unCO4 :: StateT CO4Data SAT a }
deriving (Functor, Applicative, Monad, MonadState CO4Data)
liftSAT :: SAT a -> CO4 a
liftSAT sat = CO4 $! StateT $! \s -> sat >>= \r -> return (r,s)
newId :: CO4 Int
newId = do
id <- gets idCounter
modify $! \s -> s { idCounter = id + 1 }
return id
onProfile :: (Profile -> Profile) -> CO4Data -> CO4Data
onProfile f c = c { profile = f $ profile c }
onAdtCache :: (AdtCache -> AdtCache) -> CO4Data -> CO4Data
onAdtCache f c = c { adtCache = f $ adtCache c }
setAdtCache :: AdtCache -> CO4Data -> CO4Data
setAdtCache = onAdtCache . const
onCallCache :: (CallCache -> CallCache) -> CO4Data -> CO4Data
onCallCache f c = c { callCache = f $ callCache c }
setCallCache :: CallCache -> CO4Data -> CO4Data
setCallCache = onCallCache . const
onCallStack :: (CallStack -> CallStack) -> CO4Data -> CO4Data
onCallStack f c = c { callStack = f $ callStack c }
getCallStackTrace :: CO4 CallStackTrace
getCallStackTrace = gets $ trace . callStack
isProfileRun :: CO4 Bool
isProfileRun = gets profileRun
setProfileRun :: CO4 ()
setProfileRun = modify $! \c -> c { profileRun = True }
abortWithStackTrace :: String -> CO4 a
abortWithStackTrace msg = do
stackTrace <- getCallStackTrace
let trace = if null stackTrace
then format ("stack trace", "no stack trace available")
else format ("stack trace", unlines stackTrace)
error $ unlines [ msg, trace ]
where
format (header,trace) =
concat ["## ", header, " ", replicate (20 - length header) '#', "\n"]
++ trace
instance MonadSAT CO4 where
fresh = do
modify $! onProfile $! onCurrentInner incNumVariables
liftSAT fresh
emit c = do
modify $! onProfile $! onCurrentInner incNumClauses
liftSAT $! emit c
note = liftSAT . note
numVariables = liftSAT MonadSAT.numVariables
numClauses = liftSAT MonadSAT.numClauses
runCO4 :: CO4 a -> SAT a
runCO4 p = do
(result, co4Data) <- runStateT (unCO4 p) emptyData
let h = numHits $ callCache co4Data
m = numMisses $ callCache co4Data
when ( h + m > 0 ) $ note $
concat [ "Cache hits: ", show h, " (", show $ (h*100) `div` (h+m), "%), "
, "misses: ", show m, " (", show $ (m*100) `div` (h+m), "%)" ]
printProfile $ profile co4Data
return result
withCallCache :: CallCacheKey -> CO4 EncodedAdt -> CO4 EncodedAdt
withCallCache key action =
gets (retrieve key . callCache) >>= \case
(Just hit, c) -> modify (setCallCache c) >> return hit
(Nothing , c) -> do
modify $! setCallCache c
result <- action
modify $! onCallCache $! cache key result
return result
withAdtCache :: AdtCacheKey -> CO4 EncodedAdt
withAdtCache key@(fs,args,pf) = gets (retrieve key . adtCache) >>= \case
(Just id, c) -> do modify (setAdtCache c)
return $ makeWithId id fs args pf
(Nothing, c) -> do
id <- newId
modify $! setAdtCache $! cache key id c
return $ makeWithId id fs args pf
traced :: String -> CO4 a -> CO4 a
traced name action = do
setProfileRun
previousFun <- gets $ currentFunction . profile
previousInner <- gets $ currentInner . profile
modify $! onProfile $! callFunction name . resetCurrentInner
modify $! onCallStack $! pushToStack name
result <- action
vs <- gets $ P.numVariables . currentInner . profile
cs <- gets $ P.numClauses . currentInner . profile
trace' <- getCallStackTrace >>= return . nub
modify $! onProfile $ \p -> foldr (incInnerUnderBy vs cs) p trace'
modify $! onProfile $ returnTo previousFun previousInner
modify $! onCallStack $! popFromStack
return result
profiledCase :: Int -> Int -> Int -> EncodedAdt -> CO4 EncodedAdt
profiledCase line col numCons discriminant = do
modify $! onProfile $! profileCase (line,col) isKnown
return discriminant
where
isKnown = case constantConstructorIndex numCons discriminant of
Nothing -> False
Just _ -> True
|
apunktbau/co4
|
src/CO4/Monad.hs
|
gpl-3.0
| 5,178
| 12
| 13
| 1,186
| 1,754
| 917
| 837
| 136
| 2
|
{-# 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.OpsWorks.DeleteInstance
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a specified instance, which terminates the associated Amazon EC2
-- instance. You must stop an instance before you can delete it.
--
-- For more information, see
-- <http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-delete.html Deleting Instances>.
--
-- __Required Permissions__: To use this action, an IAM user must have a
-- Manage permissions level for the stack, or an attached policy that
-- explicitly grants permissions. For more information on user permissions,
-- see
-- <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing User Permissions>.
--
-- /See:/ <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_DeleteInstance.html AWS API Reference> for DeleteInstance.
module Network.AWS.OpsWorks.DeleteInstance
(
-- * Creating a Request
deleteInstance
, DeleteInstance
-- * Request Lenses
, diDeleteVolumes
, diDeleteElasticIP
, diInstanceId
-- * Destructuring the Response
, deleteInstanceResponse
, DeleteInstanceResponse
) where
import Network.AWS.OpsWorks.Types
import Network.AWS.OpsWorks.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'deleteInstance' smart constructor.
data DeleteInstance = DeleteInstance'
{ _diDeleteVolumes :: !(Maybe Bool)
, _diDeleteElasticIP :: !(Maybe Bool)
, _diInstanceId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteInstance' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'diDeleteVolumes'
--
-- * 'diDeleteElasticIP'
--
-- * 'diInstanceId'
deleteInstance
:: Text -- ^ 'diInstanceId'
-> DeleteInstance
deleteInstance pInstanceId_ =
DeleteInstance'
{ _diDeleteVolumes = Nothing
, _diDeleteElasticIP = Nothing
, _diInstanceId = pInstanceId_
}
-- | Whether to delete the instance\'s Amazon EBS volumes.
diDeleteVolumes :: Lens' DeleteInstance (Maybe Bool)
diDeleteVolumes = lens _diDeleteVolumes (\ s a -> s{_diDeleteVolumes = a});
-- | Whether to delete the instance Elastic IP address.
diDeleteElasticIP :: Lens' DeleteInstance (Maybe Bool)
diDeleteElasticIP = lens _diDeleteElasticIP (\ s a -> s{_diDeleteElasticIP = a});
-- | The instance ID.
diInstanceId :: Lens' DeleteInstance Text
diInstanceId = lens _diInstanceId (\ s a -> s{_diInstanceId = a});
instance AWSRequest DeleteInstance where
type Rs DeleteInstance = DeleteInstanceResponse
request = postJSON opsWorks
response = receiveNull DeleteInstanceResponse'
instance ToHeaders DeleteInstance where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("OpsWorks_20130218.DeleteInstance" :: ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON DeleteInstance where
toJSON DeleteInstance'{..}
= object
(catMaybes
[("DeleteVolumes" .=) <$> _diDeleteVolumes,
("DeleteElasticIp" .=) <$> _diDeleteElasticIP,
Just ("InstanceId" .= _diInstanceId)])
instance ToPath DeleteInstance where
toPath = const "/"
instance ToQuery DeleteInstance where
toQuery = const mempty
-- | /See:/ 'deleteInstanceResponse' smart constructor.
data DeleteInstanceResponse =
DeleteInstanceResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteInstanceResponse' with the minimum fields required to make a request.
--
deleteInstanceResponse
:: DeleteInstanceResponse
deleteInstanceResponse = DeleteInstanceResponse'
|
olorin/amazonka
|
amazonka-opsworks/gen/Network/AWS/OpsWorks/DeleteInstance.hs
|
mpl-2.0
| 4,505
| 0
| 12
| 926
| 572
| 345
| 227
| 76
| 1
|
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
-------------------------------------------------------------------------------------
-- |
-- Copyright : (c) Hans Hoglund 2012-2014
--
-- License : BSD-style
--
-- Maintainer : hans@hanshoglund.se
-- Stability : experimental
-- Portability : non-portable (TF,GNTD)
--
-- A simple backend that supports rendering scores to lists of pitch and velocity.
--
-- This exists as a sanity check for the 'Backend' classes, and as an example.
--
module Music.Score.Export.NoteList (
-- * Note list backend
NoteList,
toNoteList,
) where
import Music.Dynamics.Literal
import Music.Pitch.Literal
import qualified Codec.Midi as Midi
import Control.Comonad (Comonad (..), extract)
import Control.Applicative
import Data.Colour.Names as Color
import Data.Foldable (Foldable)
import qualified Data.Foldable
import Data.Functor.Couple
import Data.Maybe
import Data.Ratio
import Data.Traversable (Traversable, sequenceA)
import Music.Score.Internal.Export hiding (MVoice)
import System.Process
import Music.Score.Internal.Quantize
import qualified Text.Pretty as Pretty
import qualified Data.List
import Music.Score.Internal.Util (composed, unRatio, swap, retainUpdates)
import Music.Score.Export.DynamicNotation
import Data.Semigroup.Instances
import Music.Score.Export.Backend
import Music.Time
import Music.Score.Dynamics
import Music.Score.Part
import Music.Score.Export.Backend
import Data.Functor.Identity
import Data.Semigroup
import Control.Monad
import Data.VectorSpace hiding (Sum(..))
import Data.AffineSpace
import Control.Lens hiding (rewrite)
-- import Control.Lens.Operators hiding ((|>))
import Music.Time
import Music.Score.Meta
import Music.Score.Meta.Title
import Music.Score.Meta.Attribution
import Music.Score.Dynamics
import Music.Score.Articulation
import Music.Score.Part
import Music.Score.Tremolo
import Music.Score.Text
import Music.Score.Harmonics
import Music.Score.Slide
import Music.Score.Color
import Music.Score.Ties
import Music.Score.Export.Backend
import Music.Score.Meta.Time
import Music.Score.Phrases
-- |
-- A token to represent the note list backend.
--
data NoteList
instance HasBackend NoteList where
type BackendScore NoteList = []
type BackendContext NoteList = Identity
type BackendNote NoteList = [(Sum Int, Int)]
type BackendMusic NoteList = [(Sum Int, Int)]
finalizeExport _ = concat
instance HasBackendScore NoteList [a] where
type BackendScoreEvent NoteList [a] = a
exportScore _ = fmap Identity
instance HasBackendScore NoteList (Score a) where
type BackendScoreEvent NoteList (Score a) = a
exportScore _ = fmap Identity . toListOf traverse
instance HasBackendNote NoteList a => HasBackendNote NoteList [a] where
exportNote b ps = mconcat $ map (exportNote b) $ sequenceA ps
instance HasBackendNote NoteList Int where
exportNote _ (Identity p) = [(mempty, p)]
instance HasBackendNote NoteList Double where
exportNote _ (Identity p) = [(mempty, round p)]
-- TODO prettier
instance HasBackendNote NoteList a => HasBackendNote NoteList (DynamicT b a) where
exportNote b = exportNote b . fmap extract
instance HasBackendNote NoteList a => HasBackendNote NoteList (ArticulationT b a) where
exportNote b = exportNote b . fmap extract
instance HasBackendNote NoteList a => HasBackendNote NoteList (PartT n a) where
exportNote b = exportNote b . fmap extract
instance HasBackendNote NoteList a => HasBackendNote NoteList (TremoloT a) where
exportNote b = exportNote b . fmap extract
instance HasBackendNote NoteList a => HasBackendNote NoteList (TextT a) where
exportNote b = exportNote b . fmap extract
instance HasBackendNote NoteList a => HasBackendNote NoteList (HarmonicT a) where
exportNote b = exportNote b . fmap extract
instance HasBackendNote NoteList a => HasBackendNote NoteList (SlideT a) where
exportNote b = exportNote b . fmap extract
instance HasBackendNote NoteList a => HasBackendNote NoteList (TieT a) where
exportNote b = exportNote b . fmap extract
instance HasBackendNote NoteList a => HasBackendNote NoteList (ColorT a) where
exportNote b = exportNote b . fmap extract
-- |
-- Export music as a note list.
--
toNoteList :: (HasBackendNote NoteList (BackendScoreEvent NoteList s), HasBackendScore NoteList s) => s -> [(Int, Int)]
toNoteList = over (mapped._1) getSum . export (undefined::NoteList)
|
music-suite/music-score
|
src/Music/Score/Export/NoteList.hs
|
bsd-3-clause
| 5,297
| 0
| 10
| 1,097
| 1,162
| 658
| 504
| -1
| -1
|
-----------------------------------------------------------------------------
-- |
-- Module : Position
-- Copyright : 2000-2004 Malcolm Wallace
-- Licence : LGPL
--
-- Maintainer : Malcolm Wallace <Malcolm.Wallace@cs.york.ac.uk>
-- Stability : experimental
-- Portability : All
--
-- Simple file position information, with recursive inclusion points.
-----------------------------------------------------------------------------
module Language.Preprocessor.Cpphs.Position
( Posn(..)
, newfile
, addcol, newline, tab, newlines, newpos
, cppline
, filename, lineno, directory
) where
-- | Source positions contain a filename, line, column, and an
-- inclusion point, which is itself another source position,
-- recursively.
data Posn = Pn String !Int !Int (Maybe Posn)
deriving (Eq)
instance Show Posn where
showsPrec _ (Pn f l c i) = showString f .
showString " at line " . shows l .
showString " col " . shows c .
( case i of
Nothing -> id
Just p -> showString "\n used by " .
shows p )
-- | Constructor
newfile :: String -> Posn
newfile name = Pn name 1 1 Nothing
-- | Updates
addcol :: Int -> Posn -> Posn
addcol n (Pn f r c i) = Pn f r (c+n) i
newline, tab :: Posn -> Posn
--newline (Pn f r _ i) = Pn f (r+1) 1 i
newline (Pn f r _ i) = let r' = r+1 in r' `seq` Pn f r' 1 i
tab (Pn f r c i) = Pn f r (((c`div`8)+1)*8) i
newlines :: Int -> Posn -> Posn
newlines n (Pn f r _ i) = Pn f (r+n) 1 i
newpos :: Int -> Maybe String -> Posn -> Posn
newpos r Nothing (Pn f _ c i) = Pn f r c i
newpos r (Just ('"':f)) (Pn _ _ c i) = Pn (init f) r c i
newpos r (Just f) (Pn _ _ c i) = Pn f r c i
-- | Projections
lineno :: Posn -> Int
filename :: Posn -> String
directory :: Posn -> FilePath
lineno (Pn _ r _ _) = r
filename (Pn f _ _ _) = f
directory (Pn f _ _ _) = dirname f
-- | cpp-style printing
cppline :: Posn -> String
cppline (Pn f r _ _) = "#line "++show r++" "++show f
-- | Strip non-directory suffix from file name (analogous to the shell
-- command of the same name).
dirname :: String -> String
dirname = reverse . safetail . dropWhile (not.(`elem`"\\/")) . reverse
where safetail [] = []
safetail (_:x) = x
|
alekar/hugs
|
cpphs/Language/Preprocessor/Cpphs/Position.hs
|
bsd-3-clause
| 2,515
| 1
| 12
| 818
| 789
| 418
| 371
| 45
| 2
|
{-# LANGUAGE JavaScriptFFI, ForeignFunctionInterface, DeriveDataTypeable #-}
module JavaScript.Web.Canvas.Pattern {-( Pattern
, Repeat(..)
, create
)-} where
import Data.Typeable
import Data.Data
{-
create :: ...
{-# INLINE create #-}
-- -----------------------------------------------------------------------------
foreign import javascript unsafe js_create
:: JSString -> IO Pattern
-}
|
ghcjs/ghcjs-base
|
JavaScript/Web/Canvas/Pattern.hs
|
mit
| 507
| 0
| 4
| 160
| 21
| 15
| 6
| 4
| 0
|
module Main where
-- $Id$
-- socket-interface für tool
-- geklaut und vereinfacht von Face.hs
-- Autoren: Johannes Waldmann, Alf Richter
-- hier sind die aufgaben drin:
import Inter.Boiler ( boiler )
import qualified Challenger
import Inter.Validate
import Inter.Evaluate
import Inter.Bank
import Inter.Types
import qualified Inter.Param as P
import qualified Inter.ID as I
import ToDoc (Doc, render, toDoc)
import Reporter
import qualified Output
import qualified Passwort
import qualified Posix
import qualified Network
import qualified Exception
import IO
import Control.Concurrent
main :: IO ()
main = do
variants <- boiler
Posix.installHandler Posix.sigPIPE Posix.Ignore Nothing
sock <- Network.listenOn $ Network.PortNumber 1234
sequence_ $ repeat $ waiter variants sock
waiter variants sock = do
connection @ ( h , rhost, rport ) <- Network.accept sock
forkIO ( do handler variants connection
`Exception.catch` \ any -> do
print any
return ()
hClose h
)
handler variants ( h, rhost, rport ) = do
putStrLn $ "got call from " ++ show (rhost, rport)
first <- hGetLine h
let id = read first
print id ; hFlush stdout
let par = P.empty { P.problem = I.problem id
, P.aufgabe = I.aufgabe id
, P.version = I.version id
, P.matrikel = I.matrikel id
, P.passwort = read $ I.passwort id
-- , P.input = rest
, P.variants = variants
}
res <- validate par
case res of
Left _ -> do
hPutStrLn h "oops"
Right par -> case P.variante par of
Variant v -> do
k <- key v $ P.matrikel par
generator <- gen v k
let gen @ ( Just i, com :: Doc ) = export generator
print gen ; hFlush stdout
hPutStrLn h $ show i -- Kommentar wird ignoriert
hFlush h
block <- hGetBlock h
par <- return $ par { P.input = unlines $ block }
let evl @ ( res :: Maybe Int , com :: Doc )
= export $ evaluate ( problem v ) i par
print evl ; hFlush stdout
msg <- bank par res
print msg ; hFlush stdout
hPutStrLn h $ msg
hPutStrLn h $ render com
hGetBlock :: Handle -> IO [ String ]
-- bis zu leerzeile lesen
hGetBlock h = do
l <- hGetLine h
putStrLn $ "<< " ++ l ; hFlush stdout
if null l
then return [ l ]
else do ls <- hGetBlock h
return $ l : ls
|
florianpilz/autotool
|
src/Inter/Streamer.hs
|
gpl-2.0
| 2,465
| 45
| 21
| 752
| 821
| 418
| 403
| -1
| -1
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
module PackageTests.DeterministicAr.Check where
import Control.Monad
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.Char (isSpace)
import Data.List
#if __GLASGOW_HASKELL__ < 710
import Data.Traversable
#endif
import PackageTests.PackageTester
import System.Exit
import System.FilePath
import System.IO
import Test.HUnit (Assertion, Test (TestCase), assertFailure)
import Distribution.Compiler (CompilerFlavor(..), CompilerId(..))
import Distribution.Package (packageKeyHash)
import Distribution.Version (Version(..))
import Distribution.Simple.Compiler (compilerId)
import Distribution.Simple.Configure (getPersistBuildConfig)
import Distribution.Simple.LocalBuildInfo (LocalBuildInfo, compiler, pkgKey)
-- Perhaps these should live in PackageTester.
-- For a polymorphic @IO a@ rather than @Assertion = IO ()@.
assertFailure' :: String -> IO a
assertFailure' msg = assertFailure msg >> return {-unpossible!-}undefined
ghcPkg_field :: String -> String -> FilePath -> IO [FilePath]
ghcPkg_field libraryName fieldName ghcPkgPath = do
(cmd, exitCode, raw) <- run Nothing ghcPkgPath []
["--user", "field", libraryName, fieldName]
let output = filter ('\r' /=) raw -- Windows
-- copypasta of PackageTester.requireSuccess
unless (exitCode == ExitSuccess) . assertFailure $
"Command " ++ cmd ++ " failed.\n" ++ "output: " ++ output
let prefix = fieldName ++ ": "
case traverse (stripPrefix prefix) (lines output) of
Nothing -> assertFailure' $ "Command " ++ cmd ++ " failed: expected "
++ show prefix ++ " prefix on every line.\noutput: " ++ output
Just fields -> return fields
ghcPkg_field1 :: String -> String -> FilePath -> IO FilePath
ghcPkg_field1 libraryName fieldName ghcPkgPath = do
fields <- ghcPkg_field libraryName fieldName ghcPkgPath
case fields of
[field] -> return field
_ -> assertFailure' $ "Command ghc-pkg field failed: "
++ "output not a single line.\noutput: " ++ show fields
------------------------------------------------------------------------
this :: String
this = "DeterministicAr"
suite :: FilePath -> FilePath -> Test
suite ghcPath ghcPkgPath = TestCase $ do
let dir = "PackageTests" </> this
let spec = PackageSpec
{ directory = dir
, configOpts = []
, distPref = Nothing
}
unregister this ghcPkgPath
iResult <- cabal_install spec ghcPath
assertInstallSucceeded iResult
let distBuild = dir </> "dist" </> "build"
libdir <- ghcPkg_field1 this "library-dirs" ghcPkgPath
lbi <- getPersistBuildConfig (dir </> "dist")
mapM_ (checkMetadata lbi) [distBuild, libdir]
unregister this ghcPkgPath
-- Almost a copypasta of Distribution.Simple.Program.Ar.wipeMetadata
checkMetadata :: LocalBuildInfo -> FilePath -> Assertion
checkMetadata lbi dir = withBinaryFile path ReadMode $ \ h -> do
hFileSize h >>= checkArchive h
where
path = dir </> "libHS" ++ this ++ "-0"
++ (if ghc_7_10 then ("-" ++ packageKeyHash (pkgKey lbi)) else "")
++ ".a"
ghc_7_10 = case compilerId (compiler lbi) of
CompilerId GHC version | version >= Version [7, 10] [] -> True
_ -> False
checkError msg = assertFailure' $
"PackageTests.DeterministicAr.checkMetadata: " ++ msg ++
" in " ++ path
archLF = "!<arch>\x0a" -- global magic, 8 bytes
x60LF = "\x60\x0a" -- header magic, 2 bytes
metadata = BS.concat
[ "0 " -- mtime, 12 bytes
, "0 " -- UID, 6 bytes
, "0 " -- GID, 6 bytes
, "0644 " -- mode, 8 bytes
]
headerSize = 60
-- http://en.wikipedia.org/wiki/Ar_(Unix)#File_format_details
checkArchive :: Handle -> Integer -> IO ()
checkArchive h archiveSize = do
global <- BS.hGet h (BS.length archLF)
unless (global == archLF) $ checkError "Bad global header"
checkHeader (toInteger $ BS.length archLF)
where
checkHeader :: Integer -> IO ()
checkHeader offset = case compare offset archiveSize of
EQ -> return ()
GT -> checkError (atOffset "Archive truncated")
LT -> do
header <- BS.hGet h headerSize
unless (BS.length header == headerSize) $
checkError (atOffset "Short header")
let magic = BS.drop 58 header
unless (magic == x60LF) . checkError . atOffset $
"Bad magic " ++ show magic ++ " in header"
unless (metadata == BS.take 32 (BS.drop 16 header))
. checkError . atOffset $ "Metadata has changed"
let size = BS.take 10 $ BS.drop 48 header
objSize <- case reads (BS8.unpack size) of
[(n, s)] | all isSpace s -> return n
_ -> checkError (atOffset "Bad file size in header")
let nextHeader = offset + toInteger headerSize +
-- Odd objects are padded with an extra '\x0a'
if odd objSize then objSize + 1 else objSize
hSeek h AbsoluteSeek nextHeader
checkHeader nextHeader
where
atOffset msg = msg ++ " at offset " ++ show offset
|
DavidAlphaFox/ghc
|
libraries/Cabal/Cabal/tests/PackageTests/DeterministicAr/Check.hs
|
bsd-3-clause
| 5,526
| 0
| 23
| 1,581
| 1,380
| 706
| 674
| 105
| 7
|
module Dotnet.System.Char where
import Dotnet
import qualified Dotnet.System.Object
data Char_ a
type Char a = Dotnet.System.Object.Object (Char_ a)
|
FranklinChen/Hugs
|
dotnet/lib/Dotnet/System/Char.hs
|
bsd-3-clause
| 152
| 0
| 7
| 21
| 41
| 27
| 14
| -1
| -1
|
module Main where
import Haste
import Haste.DOM
import Haste.Events
main :: IO ()
main = do
ul <- elemsByQS document "ul#demo-list"
case ul of
(el:_) -> mapQS_ document "#demo-list li" (handleRemove el)
_ -> error "Element 'ul#demo-list' not found"
handleRemove :: Elem -> Elem -> IO HandlerInfo
handleRemove ul li = do
onEvent li Click $ \_ -> do
deleteChild ul li
preventDefault
|
beni55/haste-compiler
|
examples/list/list.hs
|
bsd-3-clause
| 410
| 0
| 12
| 92
| 140
| 69
| 71
| 15
| 2
|
-- There was a lot of discussion about various ways of computing
-- Bernouilli numbers (whatever they are) on haskell-cafe in March 2003
-- Here's one of the programs.
-- It's not a very good test, I suspect, because it manipulates big integers,
-- and so probably spends most of its time in GMP.
import Ratio
import System
-- powers = [[r^n | r<-[2..]] | n<-1..]
powers = [2..] : map (zipWith (*) (head powers)) powers
-- powers = [[(-1)^r * r^n | r<-[2..]] | n<-1..]
neg_powers =
map (zipWith (\n x -> if n then x else -x) (iterate not True)) powers
pascal:: [[Integer]]
pascal = [1,2,1] : map (\line -> zipWith (+) (line++[0]) (0:line)) pascal
bernoulli 0 = 1
bernoulli 1 = -(1%2)
bernoulli n | odd n = 0
bernoulli n =
(-1)%2
+ sum [ fromIntegral ((sum $ zipWith (*) powers (tail $ tail combs)) -
fromIntegral k) %
fromIntegral (k+1)
| (k,combs)<- zip [2..n] pascal]
where powers = (neg_powers!!(n-1))
main = do
[arg] <- getArgs
let n = (read arg)::Int
putStr $ "Bernoulli of " ++ (show n) ++ " is "
putStrLn . filter (\c -> not (c `elem` "( )")) . show . bernoulli $ n
|
hvr/jhc
|
regress/tests/9_nofib/bernouilli.hs
|
mit
| 1,149
| 0
| 17
| 279
| 424
| 229
| 195
| 22
| 2
|
module Foo (foo) where
import Foreign.ForeignPtr
{-@ foo :: FinalizerPtr a -> a @-}
foo :: FinalizerPtr a -> a
foo = undefined
|
ssaavedra/liquidhaskell
|
tests/pos/mapTvCrash.hs
|
bsd-3-clause
| 129
| 0
| 6
| 25
| 32
| 19
| 13
| 4
| 1
|
-- !!! Illegal @ in expression
module M where
f x = x@1
|
urbanslug/ghc
|
testsuite/tests/module/mod69.hs
|
bsd-3-clause
| 56
| 0
| 6
| 13
| 18
| 10
| 8
| -1
| -1
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
-- | Futhark prettyprinter. This module defines 'Pretty' instances
-- for the AST defined in "Language.Futhark.Syntax".
module Language.Futhark.Pretty
( pretty
, prettyTuple
, leadingOperator
)
where
import Data.Array
import Data.Functor
import Data.Hashable
import qualified Data.Map.Strict as M
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Word
import Prelude
import Futhark.Util.Pretty
import Language.Futhark.Syntax
import Language.Futhark.Attributes
commastack :: [Doc] -> Doc
commastack = align . stack . punctuate comma
instance Pretty Value where
ppr (PrimValue bv) = ppr bv
ppr (ArrayValue a t)
| [] <- elems a = text "empty" <> parens (ppr t)
| Array{} <- t = brackets $ commastack $ map ppr $ elems a
| otherwise = brackets $ commasep $ map ppr $ elems a
instance Pretty PrimValue where
ppr (UnsignedValue (Int8Value v)) =
text (show (fromIntegral v::Word8)) <> text "u8"
ppr (UnsignedValue (Int16Value v)) =
text (show (fromIntegral v::Word16)) <> text "u16"
ppr (UnsignedValue (Int32Value v)) =
text (show (fromIntegral v::Word32)) <> text "u32"
ppr (UnsignedValue (Int64Value v)) =
text (show (fromIntegral v::Word64)) <> text "u64"
ppr (SignedValue v) = ppr v
ppr (BoolValue True) = text "true"
ppr (BoolValue False) = text "false"
ppr (FloatValue v) = ppr v
instance Pretty vn => Pretty (DimDecl vn) where
ppr AnyDim = mempty
ppr (NamedDim v) = ppr v
ppr (ConstDim n) = ppr n
instance Pretty vn => Pretty (ShapeDecl (DimDecl vn)) where
ppr (ShapeDecl ds) = mconcat (map (brackets . ppr) ds)
instance Pretty (ShapeDecl ()) where
ppr (ShapeDecl ds) = mconcat $ replicate (length ds) $ text "[]"
instance Pretty (ShapeDecl dim) => Pretty (RecordArrayElemTypeBase dim as) where
ppr (PrimArrayElem bt _) = ppr bt
ppr (PolyArrayElem bt targs _ u) = ppr u <> ppr (baseName <$> qualNameFromTypeName bt) <+>
spread (map ppr targs)
ppr (ArrayArrayElem at) = ppr at
ppr (RecordArrayElem fs)
| Just ts <- areTupleFields fs =
parens $ commasep $ map ppr ts
| otherwise =
braces $ commasep $ map ppField $ M.toList fs
where ppField (name, t) = text (nameToString name) <> colon <> ppr t
instance Pretty (ShapeDecl dim) => Pretty (ArrayTypeBase dim as) where
ppr (PrimArray et shape u _) =
ppr u <> ppr shape <> ppr et
ppr (PolyArray et targs shape u _) =
ppr u <> ppr shape <> ppr (baseName <$> qualNameFromTypeName et) <+> spread (map ppr targs)
ppr (RecordArray fs shape u)
| Just ts <- areTupleFields fs =
prefix <> parens (commasep $ map ppr ts)
| otherwise =
prefix <> braces (commasep $ map ppField $ M.toList fs)
where prefix = ppr u <> ppr shape
ppField (name, t) = text (nameToString name) <> colon <> ppr t
instance Pretty (ShapeDecl dim) => Pretty (TypeBase dim as) where
ppr (Prim et) = ppr et
ppr (TypeVar et targs) = ppr (baseName <$> qualNameFromTypeName et) <+> spread (map ppr targs)
ppr (Array at) = ppr at
ppr (Record fs)
| Just ts <- areTupleFields fs =
parens $ commasep $ map ppr ts
| otherwise =
braces $ commasep $ map ppField $ M.toList fs
where ppField (name, t) = text (nameToString name) <> colon <> ppr t
instance Pretty (ShapeDecl dim) => Pretty (TypeArg dim as) where
ppr (TypeArgDim d _) = ppr $ ShapeDecl [d]
ppr (TypeArgType t _) = ppr t
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (TypeExp vn) where
ppr (TEUnique t _) = text "*" <> ppr t
ppr (TEArray at d _) = ppr (ShapeDecl [d]) <> ppr at
ppr (TETuple ts _) = parens $ commasep $ map ppr ts
ppr (TERecord fs _) = braces $ commasep $ map ppField fs
where ppField (name, t) = text (nameToString name) <> colon <> ppr t
ppr (TEVar name _) = ppr name
ppr (TEApply t args _) = ppr t <+> spread (map ppr args)
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (TypeArgExp vn) where
ppr (TypeArgExpDim d _) = ppr $ ShapeDecl [d]
ppr (TypeArgExpType d) = ppr d
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (TypeDeclBase f vn) where
ppr = ppr . declaredType
instance Pretty vn => Pretty (QualName vn) where
ppr (QualName names name) =
mconcat $ punctuate (text ".") $ map ppr names ++ [ppr name]
instance Pretty vn => Pretty (IdentBase f vn) where
ppr = ppr . identName
hasArrayLit :: ExpBase ty vn -> Bool
hasArrayLit ArrayLit{} = True
hasArrayLit (TupLit es2 _) = any hasArrayLit es2
hasArrayLit _ = False
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (DimIndexBase ty vn) where
ppr (DimFix e) = ppr e
ppr (DimSlice i j s) = maybe mempty ppr i <> text ":" <>
maybe mempty ppr j <> text ":" <>
maybe mempty ppr s
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (ExpBase ty vn) where
ppr = pprPrec (-1)
pprPrec _ (Var name _ _) = ppr name
pprPrec _ (Parens e _) = align $ parens $ ppr e
pprPrec _ (QualParens v e _) = ppr v <> text "." <> align (parens $ ppr e)
pprPrec _ (Ascript e t _) = pprPrec 0 e <> pprPrec 0 t
pprPrec _ (Literal v _) = ppr v
pprPrec _ (TupLit es _)
| any hasArrayLit es = parens $ commastack $ map ppr es
| otherwise = parens $ commasep $ map ppr es
pprPrec _ (RecordLit fs _)
| any fieldArray fs = braces $ commastack $ map ppr fs
| otherwise = braces $ commasep $ map ppr fs
where fieldArray (RecordFieldExplicit _ e _) = hasArrayLit e
fieldArray RecordFieldImplicit{} = False
pprPrec _ (Empty (TypeDecl t _) _) =
text "empty" <> parens (ppr t)
pprPrec _ (ArrayLit es _ _) =
brackets $ commasep $ map ppr es
pprPrec _ (Range start maybe_step end _) =
brackets $
ppr start <>
maybe mempty ((text ".." <>) . ppr) maybe_step <>
case end of
DownToExclusive end' -> text "..>" <> ppr end'
ToInclusive end' -> text "..." <> ppr end'
UpToExclusive end' -> text "..<" <> ppr end'
pprPrec p (BinOp bop (x,_) (y,_) _ _) = prettyBinOp p bop x y
pprPrec _ (Project k e _ _) = ppr e <> text "." <> ppr k
pprPrec _ (If c t f _ _) = text "if" <+> ppr c </>
text "then" <+> align (ppr t) </>
text "else" <+> align (ppr f)
pprPrec _ (Apply fname args _ _) =
ppr fname <+> spread (map (ppr . fst) args)
pprPrec _ (Negate e _) = text "-" <> ppr e
pprPrec p (LetPat tparams pat e body _) =
mparens $ align $
text "let" <+> align (spread $ map ppr tparams ++ [ppr pat]) <+>
(if linebreak
then equals </> indent 2 (ppr e)
else equals <+> align (ppr e)) <+> text "in" </>
ppr body
where mparens = if p == -1 then id else parens
linebreak = case e of
Map{} -> True
Reduce{} -> True
Filter{} -> True
Scan{} -> True
DoLoop{} -> True
LetPat{} -> True
LetWith{} -> True
If{} -> True
ArrayLit{} -> False
_ -> hasArrayLit e
pprPrec _ (LetFun fname (tparams, params, retdecl, _, e) body _) =
text "let" <+> ppr fname <+> spread (map ppr tparams ++ map ppr params) <>
retdecl' <+> equals </> indent 2 (ppr e) <+> text "in" </>
ppr body
where retdecl' = case retdecl of
Just rettype -> text ":" <+> ppr rettype
Nothing -> mempty
pprPrec _ (LetWith dest src idxs ve body _)
| dest == src =
text "let" <+> ppr dest <+> list (map ppr idxs) <+>
equals <+> align (ppr ve) <+>
text "in" </> ppr body
| otherwise =
text "let" <+> ppr dest <+> equals <+> ppr src <+>
text "with" <+> brackets (commasep (map ppr idxs)) <+>
text "<-" <+> align (ppr ve) <+>
text "in" </> ppr body
pprPrec _ (Update src idxs ve _) =
ppr src <+> text "with" <+>
brackets (commasep (map ppr idxs)) <+>
text "<-" <+> align (ppr ve)
pprPrec _ (Index e idxs _) =
pprPrec 9 e <> brackets (commasep (map ppr idxs))
pprPrec _ (Reshape shape e _) =
text "reshape" <+> ppr shape <+> ppr e
pprPrec _ (Rearrange perm e _) =
text "rearrange" <> apply [apply (map ppr perm), ppr e]
pprPrec _ (Rotate d x e _) =
text "rotate@" <> ppr d <> apply [ppr x, ppr e]
pprPrec _ (Map lam as _) = ppSOAC "map" [lam] as
pprPrec _ (Reduce Commutative lam e a _) = ppSOAC "reduce_comm" [lam] [e, a]
pprPrec _ (Reduce Noncommutative lam e a _) = ppSOAC "reduce" [lam] [e, a]
pprPrec _ (Stream form lam arr _) =
case form of
MapLike o ->
let ord_str = if o == Disorder then "_per" else ""
in text ("stream_map"++ord_str) <>
ppr lam </> pprPrec 10 arr
RedLike o comm lam0 ->
let ord_str = if o == Disorder then "_per" else ""
comm_str = case comm of Commutative -> "_comm"
Noncommutative -> ""
in text ("stream_red"++ord_str++comm_str) <>
ppr lam0 </> ppr lam </> pprPrec 10 arr
pprPrec _ (Scan lam e a _) = ppSOAC "scan" [lam] [e, a]
pprPrec _ (Filter lam a _) = ppSOAC "filter" [lam] [a]
pprPrec _ (Partition lams a _) = ppSOAC "partition" lams [a]
pprPrec _ (Zip 0 e es _) = text "zip" <+> spread (map (pprPrec 10) (e:es))
pprPrec _ (Zip i e es _) = text "zip@" <> ppr i <+> spread (map (pprPrec 10) (e:es))
pprPrec _ (Unzip e _ _) = text "unzip" <> pprPrec 10 e
pprPrec _ (Unsafe e _) = text "unsafe" <+> pprPrec 10 e
pprPrec _ (Split i e a _) =
text "split@" <> ppr i <+> pprPrec 10 e <+> pprPrec 10 a
pprPrec _ (Concat i x y _) =
text "concat" <> text "@" <> ppr i <+> pprPrec 10 x <+> pprPrec 10 y
pprPrec _ (DoLoop tparams pat initexp form loopbody _) =
text "loop" <+> parens (spread (map ppr tparams ++ [ppr pat]) <+> equals
<+> ppr initexp) <+> equals <+>
ppr form <+>
text "do" </>
indent 2 (ppr loopbody)
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (FieldBase ty vn) where
ppr (RecordFieldExplicit name e _) = ppr name <> equals <> ppr e
ppr (RecordFieldImplicit name _ _) = ppr name
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (LoopFormBase ty vn) where
ppr (For i ubound) =
text "for" <+> ppr i <+> text "<" <+> align (ppr ubound)
ppr (ForIn x e) =
text "for" <+> ppr x <+> text "in" <+> ppr e
ppr (While cond) =
text "while" <+> ppr cond
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (PatternBase ty vn) where
ppr (PatternAscription p t) = ppr p <> text ":" <+> ppr t
ppr (PatternParens p _) = parens $ ppr p
ppr (Id v _ _) = ppr v
ppr (TuplePattern pats _) = parens $ commasep $ map ppr pats
ppr (RecordPattern fs _) = braces $ commasep $ map ppField fs
where ppField (name, t) = text (nameToString name) <> equals <> ppr t
ppr (Wildcard _ _) = text "_"
ppAscription :: (Eq vn, Hashable vn, Pretty vn) => Maybe (TypeDeclBase ty vn) -> Doc
ppAscription Nothing = mempty
ppAscription (Just t) = text ":" <> ppr t
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (LambdaBase ty vn) where
ppr (CurryFun fname [] _ _) = text $ pretty fname
ppr (CurryFun fname curryargs _ _) =
ppr fname <+> apply (map ppr curryargs)
ppr (AnonymFun tparams params body ascript _ _) =
text "fn" <+>
apply (map ppr tparams ++ map ppr params) <> ppAscription ascript <+>
text "=>" </> indent 2 (ppr body)
ppr (BinOpFun binop _ _ _ _) =
ppr binop
ppr (CurryBinOpLeft binop x _ _ _) =
ppr x <+> ppr binop
ppr (CurryBinOpRight binop x _ _ _) =
ppr binop <+> ppr x
ppr (CurryProject k _ _) = text "#" <> ppr k
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (ProgBase ty vn) where
ppr = stack . punctuate line . map ppr . progDecs
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (DecBase ty vn) where
ppr (ValDec dec) = ppr dec
ppr (FunDec dec) = ppr dec
ppr (TypeDec dec) = ppr dec
ppr (SigDec sig) = ppr sig
ppr (ModDec sd) = ppr sd
ppr (OpenDec x xs _ _) = text "open" <+> spread (map ppr (x:xs))
ppr (LocalDec dec _) = text "local" <+> ppr dec
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (ModExpBase ty vn) where
ppr (ModVar v _) = ppr v
ppr (ModParens e _) = parens $ ppr e
ppr (ModImport v _) = ppr $ show v
ppr (ModDecs ds _) = nestedBlock "{" "}" (stack $ punctuate line $ map ppr ds)
ppr (ModApply f a _ _ _) = parens $ ppr f <+> parens (ppr a)
ppr (ModAscript me se _ _) = ppr me <> colon <+> ppr se
ppr (ModLambda param maybe_sig body _) =
text "\\" <> ppr param <> maybe_sig' <+>
text "->" </> indent 2 (ppr body)
where maybe_sig' = case maybe_sig of Nothing -> mempty
Just (sig, _) -> colon <+> ppr sig
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (TypeBindBase ty vn) where
ppr (TypeBind name params usertype _ _) =
text "type" <+> ppr name <+> spread (map ppr params) <+> equals <+> ppr usertype
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (TypeParamBase vn) where
ppr (TypeParamDim name _) = brackets $ ppr name
ppr (TypeParamType name _) = text "'" <> ppr name
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (FunBindBase ty vn) where
ppr (FunBind entry name retdecl _ tparams args body _ _) =
text fun <+> ppr name <+>
spread (map ppr tparams ++ map ppr args) <> retdecl' <+> equals </>
indent 2 (ppr body)
where fun | entry = "entry"
| otherwise = "let"
retdecl' = case retdecl of
Just rettype -> text ":" <+> ppr rettype
Nothing -> mempty
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (ValBindBase ty vn) where
ppr (ValBind entry name maybe_t _ e _ _) =
text s <+> ppr name <> t' <+> text "=" <+> ppr e
where t' = case maybe_t of Just t -> text ":" <+> ppr t
Nothing -> mempty
s | entry = "entry"
| otherwise = "let"
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (ParamBase ty vn) where
ppr (NamedParam v t _) = parens $ ppr v <> colon <+> ppr t
ppr (UnnamedParam t) = ppr t
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (SpecBase ty vn) where
ppr (TypeAbbrSpec tpsig) = ppr tpsig
ppr (TypeSpec name ps _ _) = text "type" <+> ppr name <+> spread (map ppr ps)
ppr (ValSpec name tparams params rettype _ _) =
text "val" <+> ppr name <+> spread (map ppr tparams) <> colon <+>
mconcat (map (\p -> ppr p <+> text "-> ") params) <+> ppr rettype
ppr (ModSpec name sig _) =
text "module" <+> ppr name <> colon <+> ppr sig
ppr (IncludeSpec e _) =
text "include" <+> ppr e
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (SigExpBase ty vn) where
ppr (SigVar v _) = ppr v
ppr (SigParens e _) = parens $ ppr e
ppr (SigSpecs ss _) = nestedBlock "{" "}" (stack $ punctuate line $ map ppr ss)
ppr (SigWith s (TypeRef v td) _) =
ppr s <+> text "with" <+> ppr v <+> equals <+> ppr td
ppr (SigArrow (Just v) e1 e2 _) =
parens (ppr v <> colon <+> ppr e1) <+> text "->" <+> ppr e2
ppr (SigArrow Nothing e1 e2 _) =
ppr e1 <+> text "->" <+> ppr e2
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (SigBindBase ty vn) where
ppr (SigBind name e _ _) =
text "module type" <+> ppr name <+> equals <+> ppr e
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (ModParamBase ty vn) where
ppr (ModParam pname psig _) =
parens (ppr pname <> colon <+> ppr psig)
instance (Eq vn, Hashable vn, Pretty vn) => Pretty (ModBindBase ty vn) where
ppr (ModBind name ps sig e _ _) =
text "module" <+> ppr name <+> spread (map ppr ps) <+> sig' <+> equals <+> ppr e
where sig' = case sig of Nothing -> mempty
Just (s,_) -> colon <+> ppr s <> text " "
prettyBinOp :: (Eq vn, Hashable vn, Pretty vn) =>
Int -> QualName vn -> ExpBase ty vn -> ExpBase ty vn -> Doc
prettyBinOp p bop x y = parensIf (p > symPrecedence bop) $
pprPrec (symPrecedence bop) x <+/>
ppr bop <+>
pprPrec (symRPrecedence bop) y
where symPrecedence = precedence . leadingOperator . nameFromString . pretty
symRPrecedence = rprecedence . leadingOperator . nameFromString . pretty
precedence LogAnd = 0
precedence LogOr = 0
precedence Band = 1
precedence Bor = 1
precedence Xor = 1
precedence Equal = 2
precedence NotEqual = 2
precedence Less = 2
precedence Leq = 2
precedence Greater = 2
precedence Geq = 2
precedence ShiftL = 3
precedence ShiftR = 3
precedence ZShiftR = 3
precedence Plus = 4
precedence Minus = 4
precedence Times = 5
precedence Divide = 5
precedence Mod = 5
precedence Quot = 5
precedence Rem = 5
precedence Pow = 6
rprecedence Minus = 10
rprecedence Divide = 10
rprecedence op = precedence op
ppSOAC :: (Eq vn, Hashable vn, Pretty vn, Pretty fn) =>
String -> [fn] -> [ExpBase ty vn] -> Doc
ppSOAC name funs es =
text name <+> spread (map ppr funs) </> spread (map (pprPrec 10) es)
|
ihc/futhark
|
src/Language/Futhark/Pretty.hs
|
isc
| 17,794
| 0
| 19
| 5,324
| 7,810
| 3,775
| 4,035
| 379
| 24
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.