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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# OPTIONS -Wall #-}
{-# LANGUAGE ScopedTypeVariables #-}
main :: IO ()
main = do
depths :: [Int] <- map read . filter (not . null) . lines <$> getContents
let windows = map (\(a, b, c) -> a + b + c) $ zip3 depths (tail depths) (tail (tail depths))
let answer = length $ filter id $ zipWith (<) windows (tail windows)
print answer
| SamirTalwar/advent-of-code | 2021/AOC_01_2.hs | mit | 341 | 0 | 15 | 75 | 164 | 82 | 82 | 8 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ses-configurationseteventdestination.html
module Stratosphere.Resources.SESConfigurationSetEventDestination where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.SESConfigurationSetEventDestinationEventDestination
-- | Full data type definition for SESConfigurationSetEventDestination. See
-- 'sesConfigurationSetEventDestination' for a more convenient constructor.
data SESConfigurationSetEventDestination =
SESConfigurationSetEventDestination
{ _sESConfigurationSetEventDestinationConfigurationSetName :: Val Text
, _sESConfigurationSetEventDestinationEventDestination :: SESConfigurationSetEventDestinationEventDestination
} deriving (Show, Eq)
instance ToResourceProperties SESConfigurationSetEventDestination where
toResourceProperties SESConfigurationSetEventDestination{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::SES::ConfigurationSetEventDestination"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ (Just . ("ConfigurationSetName",) . toJSON) _sESConfigurationSetEventDestinationConfigurationSetName
, (Just . ("EventDestination",) . toJSON) _sESConfigurationSetEventDestinationEventDestination
]
}
-- | Constructor for 'SESConfigurationSetEventDestination' containing required
-- fields as arguments.
sesConfigurationSetEventDestination
:: Val Text -- ^ 'sescsedConfigurationSetName'
-> SESConfigurationSetEventDestinationEventDestination -- ^ 'sescsedEventDestination'
-> SESConfigurationSetEventDestination
sesConfigurationSetEventDestination configurationSetNamearg eventDestinationarg =
SESConfigurationSetEventDestination
{ _sESConfigurationSetEventDestinationConfigurationSetName = configurationSetNamearg
, _sESConfigurationSetEventDestinationEventDestination = eventDestinationarg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ses-configurationseteventdestination.html#cfn-ses-configurationseteventdestination-configurationsetname
sescsedConfigurationSetName :: Lens' SESConfigurationSetEventDestination (Val Text)
sescsedConfigurationSetName = lens _sESConfigurationSetEventDestinationConfigurationSetName (\s a -> s { _sESConfigurationSetEventDestinationConfigurationSetName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ses-configurationseteventdestination.html#cfn-ses-configurationseteventdestination-eventdestination
sescsedEventDestination :: Lens' SESConfigurationSetEventDestination SESConfigurationSetEventDestinationEventDestination
sescsedEventDestination = lens _sESConfigurationSetEventDestinationEventDestination (\s a -> s { _sESConfigurationSetEventDestinationEventDestination = a })
| frontrowed/stratosphere | library-gen/Stratosphere/Resources/SESConfigurationSetEventDestination.hs | mit | 2,939 | 0 | 15 | 255 | 273 | 159 | 114 | 32 | 1 |
{- |
Module : $Header$
Description : Sentence for HolLight logic
Copyright : (c) Jonathan von Schroeder, DFKI GmbH 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : jonathan.von_schroeder@dfki.de
Stability : experimental
Portability : portable
Definition of sentences for HolLight logic
Ref.
<http://www.cl.cam.ac.uk/~jrh13/hol-light/>
-}
module HolLight.Sentence where
import Common.DocUtils
import Common.Doc
import HolLight.Helper
import HolLight.Term
import Data.Maybe (fromJust, catMaybes, isNothing)
import qualified Data.Char as Char
data Sentence = Sentence {
term :: Term,
proof :: Maybe HolProof
} deriving (Eq, Ord, Show)
instance Pretty Sentence where
pretty = ppPrintTerm . term
ppPrintTerm :: Term -> Doc
ppPrintTerm = printTerm 0
precParens :: Int -> Doc -> Doc
precParens prec = if prec /= 0 then parens else id
replacePt :: Term -> HolParseType -> Term
replacePt tm pt = case tm of
Var s t _ -> Var s t (HolTermInfo (pt, Nothing))
Const s t _ -> Const s t (HolTermInfo (pt, Nothing))
_ -> tm
printTerm :: Int -> Term -> Doc
printTerm prec tm =
let _1 = case destNumeral tm of
Just i -> Just (text (show i))
_ -> Nothing in
let _2 = case destList tm of
Just tms -> case typeOf tm of
Just t -> case destType t of
Just (_, x : _) -> case destType x of
Just ("char", _) -> let cs = map codeOfTerm tms
in if any isNothing cs then Nothing
else Just (quotes (text (foldr ((:) . Char.chr) []
(catMaybes cs))))
_ -> Nothing
_ -> Nothing
_ -> Nothing
_ -> Nothing in
let _3 = if isNothing _2 then case destList tm of
Just tms -> Just (brackets (printTermSequence "; " 0 tms))
_ -> Nothing
else Nothing in
let _4 = if isGabs tm then Just (printBinder prec tm)
else Nothing in
let (s, _, args, hop) = case stripComb tm of
(hop', args') -> case fromJust (typeOf hop') of
{- not really sure in which cases (typeOf hop) == Nothing,
but shouldn't happen if i understand the original
ocaml code correctly -}
ty0' ->
let s0 = nameOf hop' in
case reverseInterface (s0, hop') of
(s', Just pt) -> (s', ty0', args', replacePt hop' pt)
_ -> (s0, ty0', args', hop') in
let _5 = case (s, isConst tm, null args) of
("EMPTY", True, True) -> Just (braces empty)
("UNIV", True, True) -> case typeOf tm of
Just t -> case destFunTy t of
Just (ty, _) -> Just (parens (hcat [text ":", ppPrintType ty]))
_ -> Nothing
_ -> Nothing
("INSERT", _, _) ->
let (mems, oth) = splitlist (destBinary' "INSERT") tm
in case (isConst oth, destConst oth) of
(True, Just ("EMPTY", _)) -> Just (braces (printTermSequence
", " 14 mems))
_ -> Nothing
("GSPEC", _, _) -> case rand tm of
Just rtm -> case body rtm of
Just b -> let (evs, bod) = stripExists b
in case destComb bod of
Nothing -> Nothing
Just (bod1, fabs) ->
case destComb bod1 of
Nothing -> Nothing
Just (bod2, babs) ->
case rator bod2 of
Nothing -> Nothing
Just c ->
case destConst c of
Just ("SETSPEC", _) ->
Just (braces (hcat [
printTerm 0 fabs,
text " | ",
printTermSequence "," 14 evs,
text " | ",
printTerm 0 babs
]))
_ -> Nothing
_ -> Nothing
_ -> Nothing
_ -> Nothing in
let _6 = case destLet tm of
Just (e : eqs, _) -> case mkEq e of
Just e' -> let eqs' = map (\ (v, t) -> mkEq (v, t)) eqs
in if elem Nothing eqs' then Nothing else
Just (precParens prec
(hcat [
text "let ",
printTerm 0 e',
vcat (map (\ eq -> hcat [
text "and ",
printTerm 0 eq]) (catMaybes eqs')
++ [text " in", text ""])
]))
_ -> Nothing
_ -> Nothing in
let _7 = if s == "DECIMAL" && length args > 2 then
case (destNumeral (head args), destNumeral (args !! 1)) of
(Just n_num, Just n_den) -> if not (powerof10 n_den) then Nothing
else let s_num = text (show (n_num `quot` n_den)) in
let s_den = text (concat (tail (map (: [])
(show (n_den + (n_num `mod` n_den)))
)))
in Just (hcat [text "#", s_num, if n_den == 1 then empty
else text ".",
s_den])
_ -> Nothing
else Nothing in
let _8 = if s == "_MATCH" && length args == 2 then
case destClauses (args !! 1) of
Just cls -> Just (precParens prec (vcat [
hcat [text "match ",
printTerm 0 (head args),
text " with"],
printClauses cls]))
_ -> Nothing
else Nothing in
let _9 = if s == "_FUNCTION" && length args == 1 then
case destClauses (head args) of
Just cls -> Just (precParens prec (vcat [
text "function",
printClauses cls
]))
_ -> Nothing
else Nothing in
let _10 = if s == "COND" && length args == 3 then
Just (precParens prec (vcat [
hcat [text "if ", printTerm 0 (head args)],
hcat [text " then ", printTerm 0 (args !! 1)],
hcat [text " else ", printTerm 0 (args !! 2)]
]))
else Nothing in
let _11 = if isPrefix hop && length args == 1 then
Just ((if prec == 1000 then parens else id)
(hcat $ if all Char.isAlphaNum s || s == "--"
|| (
case destComb (head args) of
Just (l, _) -> let (s0, _) = (nameOf l, typeOf l)
in fst (reverseInterface (s0, hop)) == "--"
|| (case destConst l of
Just (f, _) -> f `elem` ["real_of_num",
"int_of_num"]
_ -> False)
_ -> False)
|| s == "~" then
[text s, printTerm 999 (head args), text " "]
else [text s, printTerm 999 (head args)]))
else Nothing in
let _12 = if parsesAsBinder hop && length args == 1 && isGabs (head args)
then Just (printBinder prec tm)
else Nothing in
let _13 = if canGetInfixStatus hop && length args == 2 then
let bargs = if aright hop then
let (tms, tmt) = splitlist (destBinary hop) tm
in tms ++ [tmt]
else
let (tmt, tms) = revSplitlist (destBinary hop) tm
in tmt : tms in
let (newprec, unspaced_binops) = (getPrec hop, [",", "..", "$"])
in Just ((if newprec <= prec then parens else id) (hcat
(printTerm newprec (head bargs) :
map (\ x -> hcat $
if s `elem` unspaced_binops then [text s,
printTerm newprec x]
else
[text " ", text s, text " ", printTerm newprec x]
) (tail bargs)
)))
else Nothing in
let _14 = if (isConst hop || isVar hop) && null args then
let s' = if parsesAsBinder hop || canGetInfixStatus hop
|| isPrefix tm then parens (text s) else text s
in Just s'
else Nothing in
let _15 = case destComb tm of
Just (l, r) -> let mem = case destConst l of
Just (s', _) -> s' `elem`
["real_of_num", "int_of_num"]
_ -> False
in Just ((if prec == 1000 then parens else id)
(hcat $ if not mem
then [printTerm 999 l, text " ",
printTerm 1000 r]
else [printTerm 999 l,
printTerm 1000 r]))
_ -> Nothing
in head (catMaybes [_1, _2, _3, _4, _5, _6, _7, _8, _9,
_10, _11, _12, _13, _14, _15, Just empty])
printTermSequence :: String -> Int -> [Term] -> Doc
printTermSequence sep' prec tms =
if null tms then empty
else hcat (punctuate (text sep') (map (printTerm prec) tms))
printBinder :: Int -> Term -> Doc
printBinder prec tm =
let absf = isGabs tm in
let s' = if absf then Just "\\"
else case rator tm of
Just r -> Just (nameOf r)
Nothing -> Nothing in
case s' of
Just s -> let collectvs tm'
| absf =
if isAbs tm' then
case destAbs tm' of
Just (v, t) -> let (vs, bod) = collectvs t
in ((False, v) : vs, bod)
_ -> ([], tm')
else if isGabs tm' then
case destGabs tm' of
Just (v, t) -> let (vs, bod) = collectvs t
in ((True, v) : vs, bod)
_ -> ([], tm')
else ([], tm')
| isComb tm' =
case rator tm' of
Just r'' -> if nameOf r'' == s then
case rand tm' of
Just r'
| isAbs r' ->
case destAbs r' of
Just (v, t) -> let (vs, bod) = collectvs t
in ((False, v) : vs, bod)
_ -> ([], tm')
| isGabs r' ->
case destGabs r' of
Just (v, t) -> let (vs, bod) = collectvs t
in ((True, v) : vs, bod)
_ -> ([], tm')
| otherwise -> ([], tm')
_ -> ([], tm')
else ([], tm')
_ -> ([], tm')
| otherwise = ([], tm') in
let (vs, bod) = collectvs tm in
precParens prec (hcat ([
text s,
if all Char.isAlphaNum s then text " " else empty]
++ map (\ (b, x) -> hcat [
(if b then parens else id) (printTerm 0 x),
text " "] )
(init vs)
++ [
if fst (last vs) then text "(" else empty,
printTerm 0 (snd (last vs)),
if fst (last vs) then text ")" else empty,
text ".",
if length vs == 1 then text " " else empty,
printTerm 0 bod
]
))
_ -> empty
printClauses :: [[Term]] -> Doc
printClauses cls = case cls of
[] -> empty
c : cls' -> vcat (printClause c :
map (\ cl -> hcat [text "| ", printClause cl]) cls')
printClause :: [Term] -> Doc
printClause cl = case cl of
[p, g, r] -> hcat [printTerm 1 p,
text " when ",
printTerm 1 g,
text " -> ",
printTerm 1 r]
[p, r] -> hcat [printTerm 1 p,
text " -> ",
printTerm 1 r]
_ -> empty
| nevrenato/HetsAlloy | HolLight/Sentence.hs | gpl-2.0 | 12,890 | 2 | 43 | 6,388 | 4,078 | 2,087 | 1,991 | 266 | 52 |
{-# LANGUAGE TemplateHaskell #-}
{-| Lenses for Ganeti config objects
-}
{-
Copyright (C) 2014 Google Inc.
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., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Ganeti.Objects.Lens where
import qualified Data.Set as Set
import System.Time (ClockTime(..))
import Ganeti.Lens (makeCustomLenses, Lens')
import Ganeti.Objects
-- | Class of objects that have timestamps.
class TimeStampObject a => TimeStampObjectL a where
mTimeL :: Lens' a ClockTime
-- | Class of objects that have an UUID.
class UuidObject a => UuidObjectL a where
uuidL :: Lens' a String
-- | Class of object that have a serial number.
class SerialNoObject a => SerialNoObjectL a where
serialL :: Lens' a Int
-- | Class of objects that have tags.
class TagsObject a => TagsObjectL a where
tagsL :: Lens' a (Set.Set String)
$(makeCustomLenses ''AddressPool)
$(makeCustomLenses ''Network)
instance SerialNoObjectL Network where
serialL = networkSerialL
instance TagsObjectL Network where
tagsL = networkTagsL
instance UuidObjectL Network where
uuidL = networkUuidL
instance TimeStampObjectL Network where
mTimeL = networkMtimeL
$(makeCustomLenses ''PartialNic)
$(makeCustomLenses ''Disk)
$(makeCustomLenses ''Instance)
instance TimeStampObjectL Instance where
mTimeL = instMtimeL
instance UuidObjectL Instance where
uuidL = instUuidL
instance SerialNoObjectL Instance where
serialL = instSerialL
instance TagsObjectL Instance where
tagsL = instTagsL
$(makeCustomLenses ''MinMaxISpecs)
$(makeCustomLenses ''PartialIPolicy)
$(makeCustomLenses ''FilledIPolicy)
$(makeCustomLenses ''Node)
instance TimeStampObjectL Node where
mTimeL = nodeMtimeL
instance UuidObjectL Node where
uuidL = nodeUuidL
instance SerialNoObjectL Node where
serialL = nodeSerialL
instance TagsObjectL Node where
tagsL = nodeTagsL
$(makeCustomLenses ''NodeGroup)
instance TimeStampObjectL NodeGroup where
mTimeL = groupMtimeL
instance UuidObjectL NodeGroup where
uuidL = groupUuidL
instance SerialNoObjectL NodeGroup where
serialL = groupSerialL
instance TagsObjectL NodeGroup where
tagsL = groupTagsL
$(makeCustomLenses ''Cluster)
instance TimeStampObjectL Cluster where
mTimeL = clusterMtimeL
instance UuidObjectL Cluster where
uuidL = clusterUuidL
instance SerialNoObjectL Cluster where
serialL = clusterSerialL
instance TagsObjectL Cluster where
tagsL = clusterTagsL
$(makeCustomLenses ''ConfigData)
instance SerialNoObjectL ConfigData where
serialL = configSerialL
instance TimeStampObjectL ConfigData where
mTimeL = configMtimeL
| ribag/ganeti-experiments | src/Ganeti/Objects/Lens.hs | gpl-2.0 | 3,203 | 0 | 10 | 512 | 596 | 304 | 292 | 70 | 0 |
module Tokens where
data Token = A | B | C
deriving Eq
instance Show Token where
show A = "番"
show B = "茄"
show C = "干"
| brainbush/Tomato-Programming-Language | Tokens.hs | gpl-2.0 | 142 | 0 | 6 | 45 | 52 | 29 | 23 | 7 | 0 |
{-# LANGUAGE
FlexibleInstances
, FlexibleContexts
, UndecidableInstances
, TypeFamilies
#-}
module VirMat.Core.VoronoiMicro
( mkVoronoiMicro
, VoronoiMicro
) where
import Data.IntMap (IntMap)
import Hammer.MicroGraph
import Linear.Vect
import qualified Data.IntMap as IM
import DeUni.Dim2.Base2D (face2DPoints)
import DeUni.Dim3.Base3D (tetraPoints)
import DeUni.Types
class VoronoiMicroBuilder v where
type VoronoiMicro v
mkVoronoiMicro :: IntMap (S2 v) -> VoronoiMicro v
-- =======================================================================================
instance VoronoiMicroBuilder Vec3 where
type VoronoiMicro Vec3 = MicroGraph () () () Vec3D
mkVoronoiMicro = IM.foldl' (flip addS2) initMicroGraph
addS2 :: S2 Vec3 -> VoronoiMicro Vec3 -> VoronoiMicro Vec3
addS2 s2 = let
tetra@(a,b,c,d) = tetraPoints s2
vid = mkVertexID tetra
v = circumOrigin s2
fab = mkFaceID (a, b)
fbc = mkFaceID (b, c)
fca = mkFaceID (c, a)
fad = mkFaceID (a, d)
fbd = mkFaceID (b, d)
fcd = mkFaceID (c, d)
ea = mkEdgeID' (fbc, fbd, fcd)
eb = mkEdgeID' (fca, fad, fcd)
ec = mkEdgeID' (fab, fad, fbd)
ed = mkEdgeID' (fab, fbc, fca)
addV = insertNewVertex vid v [ea, eb, ec, ed]
addEa = insertEdgeConn ea [fbc, fbd, fcd]
addEb = insertEdgeConn eb [fca, fad, fcd]
addEc = insertEdgeConn ec [fab, fad, fbd]
addEd = insertEdgeConn ed [fab, fbc, fca]
addFab = insertFaceConn fab
addFbc = insertFaceConn fbc
addFca = insertFaceConn fca
addFad = insertFaceConn fad
addFbd = insertFaceConn fbd
addFcd = insertFaceConn fcd
in addV . addEa . addEb . addEc . addEd .
addFab . addFbc . addFca . addFad . addFbd . addFcd
-- =======================================================================================
instance VoronoiMicroBuilder Vec2 where
type VoronoiMicro Vec2 = MicroGraph () () Vec2D ()
mkVoronoiMicro = IM.foldl' (flip addS22D) initMicroGraph
addS22D :: S2 Vec2 -> VoronoiMicro Vec2 -> VoronoiMicro Vec2
addS22D s2 = let
(a, b, c) = face2DPoints s2
v = circumOrigin s2
fab = mkFaceID (a, b)
fbc = mkFaceID (b, c)
fca = mkFaceID (c, a)
e = mkEdgeID' (fab, fbc, fca)
addE = insertNewEdge e v [fab, fbc, fca]
addFab = insertFaceConn fab
addFbc = insertFaceConn fbc
addFca = insertFaceConn fca
in addE . addFab . addFbc . addFca
| lostbean/VirMat | src/VirMat/Core/VoronoiMicro.hs | gpl-3.0 | 2,345 | 0 | 16 | 463 | 801 | 437 | 364 | 65 | 1 |
module Utilities where
-- |Converts an amplitude value (between -1.0 to 1.0) to a dB value.
amplitude2db :: Double -> Double
amplitude2db x = 20.0 * logBase 10.0 x
-- |Converts a dB value (e.g. -6.0 for -6.0dB) to an amplitude value.
db2amplitude :: Double -> Double
db2amplitude x = 10.0 ** (x / 20.0)
-- |Renders an amplitude value to a string.
showAmplitude :: Double -> String
showAmplitude x = show (amplitude2db x) ++ "dB" ++ " (" ++ show x ++ ")"
-- |Renders a dB value to a string.
showDB :: Double -> String
showDB x = show x ++ "dB" ++ " (" ++ show (db2amplitude x) ++ ")"
-- |Renders an list of samples to a string.
showSamples :: [Double] -> String
showSamples [] = ""
showSamples (x:xs) = " " ++ showAmplitude x ++ "\n" ++ showSamples xs
| Jannis/haskell-dsp-experiments | utilities.hs | gpl-3.0 | 766 | 0 | 11 | 159 | 208 | 108 | 100 | 12 | 1 |
-- | Domain, any-Domain.
module Domains.Domain where
import Domains.Dimensionable
import Domains.DomainElement
-- | Defines a multi-component domain class.
class (Dimensionable a) => Domain a where
-- | Cardinal number of domain.
cardinality :: a -> Int
-- | Returns n-th component of domain.
getComponent :: a -> Int -> ADomain
-- | Return the ordinal number of an element of the domain.
indexOfElement :: a -> DomainElement -> Int
-- | Retrieves n-th element from the domain.
elementAtIndex :: a -> Int -> DomainElement
-- | Returns an iterator through all elements of domain, in order.
iterator :: a -> [DomainElement]
-- | Returns list of all components.
getAllComponents :: a -> [ADomain]
getAllComponents domain = map (getComponent domain) [0 .. dimension domain - 1]
-- | Returns first element of a domain.
minElement :: a -> DomainElement
minElement = head . iterator
-- | Returns last element of a domain.
maxElement :: a -> DomainElement
maxElement = last . iterator
-- | An "any" domain wrapper around the 'Domain' class.
data ADomain where
ADomain :: (Domain a) => a -> ADomain
-- | Show instance.
instance Show ADomain where
show (ADomain domain) = let
fromZero = [0 ..] :: [Int]
in unlines $ zipWith (++) (map ((++ "# element: ") . show) fromZero) (map show $ iterator domain)
-- | Equality instance.
instance Eq ADomain where
d1 == d2 = dimension d1 == dimension d2 && and (zipWith (==) (iterator d1) (iterator d2))
-- | "Any" domain instance.
instance Domain ADomain where
cardinality (ADomain a) = cardinality a
getComponent (ADomain a) = getComponent a
indexOfElement (ADomain a) = indexOfElement a
elementAtIndex (ADomain a) = elementAtIndex a
iterator (ADomain a) = iterator a
-- | Dimensionable instance.
instance Dimensionable ADomain where
dimension (ADomain a) = dimension a
| mrlovre/super-memory | Pro1/src/Domains/Domain.hs | gpl-3.0 | 1,955 | 0 | 14 | 453 | 477 | 255 | 222 | -1 | -1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
module While.Domain.Congruence.Semantics where
import Abstat.Interface.GaloisConnection
import Abstat.Interface.State
import Abstat.Interface.Lattice
import Abstat.Interface.AbstractDomain()
import While.AST
import While.AbstractSemantics
import While.Domain.Congruence.Domain
instance WhileAbstractSemantics Domain where
interpretAExpr expr state = case expr of
(Var var) -> load var state
(IntConst num) -> singleAbstraction num
(AUnary op x) -> case op of
Neg -> case interpretAExpr x state of
Bottom -> Bottom
(Val n) -> Val $ (-n) `mod` moduleVal
_ -> Top
(ABinary op a b) -> case op of
Add -> case (interpretAExpr a state, interpretAExpr b state) of
(_, Bottom) -> Bottom
(Bottom, _) -> Bottom
(Val x, Val y) -> Val $ (x + y) `mod` moduleVal
(_, _) -> Top
Subtract -> case (interpretAExpr a state, interpretAExpr b state) of
(_, Bottom) -> Bottom
(Bottom, _) -> Bottom
(Val x, Val y) -> Val $ (x - y) `mod` moduleVal
(_, _) -> Top
Multiply -> case (interpretAExpr a state, interpretAExpr b state) of
(_, Bottom) -> Bottom
(Bottom, _) -> Bottom
(Val 0, Top) -> Val 0
(Top, Val 0) -> Val 0
(Val x, Val y) -> Val $ (x * y) `mod` moduleVal
(_, _) -> Top
Divide -> case (interpretAExpr a state, interpretAExpr b state) of
(_, Bottom) -> Bottom
(Bottom, _) -> Bottom
(_, _) -> Top
interpretBExpr expr state = case expr of
(BoolConst True) -> state
(BoolConst False) -> bottom
(BUnary op x) -> case op of
Not -> interpretBExpr notExpr state where
notExpr = case x of
(BoolConst a) -> BoolConst $ not a
(BUnary Not a) -> a
(BBinary And a b) -> BBinary Or (BUnary Not a) (BUnary Not b)
(BBinary Or a b) -> BBinary And (BUnary Not a) (BUnary Not b)
(RBinary NotEqual a b) -> RBinary Equal a b
(RBinary Equal a b) -> RBinary NotEqual a b
(RBinary GreaterEqual a b) -> RBinary Less a b
(RBinary Greater a b) -> RBinary LessEqual a b
(RBinary LessEqual a b) -> RBinary Greater a b
(RBinary Less a b) -> RBinary GreaterEqual a b
(BBinary op a b) -> case op of
And -> meet (interpretBExpr a state) (interpretBExpr b state)
Or -> join (interpretBExpr a state) (interpretBExpr b state)
(RBinary op a b) -> case op of
Equal -> case (a, b, interpretAExpr a state, interpretAExpr b state) of
(_, _, Bottom, _) -> bottom
(_, _, _, Bottom) -> bottom
(Var var, _, _, Val y) -> store var (Val y) top `meet` state
(_, Var var, Val x, _) -> store var (Val x) top `meet` state
(_, _, Val x, Val y) ->
if x == y
then state
else bottom
(_, _, _, _) -> state
NotEqual -> case (interpretAExpr a state, interpretAExpr b state) of
(Bottom, _) -> bottom
(_, Bottom) -> bottom
(_, _) -> state
Less -> case (interpretAExpr a state, interpretAExpr b state) of
(Bottom, _) -> bottom
(_, Bottom) -> bottom
(_, _) -> state
LessEqual -> case (interpretAExpr a state, interpretAExpr b state) of
(Bottom, _) -> bottom
(_, Bottom) -> bottom
(_, _) -> state
Greater -> case (interpretAExpr a state, interpretAExpr b state) of
(Bottom, _) -> bottom
(_, Bottom) -> bottom
(_, _) -> state
GreaterEqual -> case (interpretAExpr a state, interpretAExpr b state) of
(Bottom, _) -> bottom
(_, Bottom) -> bottom
(_, _) -> state
| fpoli/abstat | src/While/Domain/Congruence/Semantics.hs | gpl-3.0 | 4,360 | 0 | 19 | 1,781 | 1,527 | 811 | 716 | 90 | 0 |
-- | Defines an abstraction for the game controller and the functions to read
-- it.
--
-- Lower-level devices replicate the higher-level API, and should accomodate to
-- it. Each device should:
--
-- - Upon initialisation, return any necessary information to poll it again.
--
-- - Update the controller with its own values upon sensing.
--
-- In this case, we only have one: mouse/keyboard combination.
--
module Input where
-- External imports
import Data.IORef
import Graphics.UI.SDL as SDL
-- Internal imports
import Control.Extra.Monad
import Graphics.UI.Extra.SDL
-- * Game controller
-- | Controller info at any given point.
data Controller = Controller
{ controllerPos :: (Double, Double)
, controllerClick :: Bool
, controllerPause :: Bool
, controllerExit :: Bool
, controllerFast :: Bool
, controllerSlow :: Bool
, controllerSuperSlow :: Bool
, controllerFullscreen :: Bool
}
-- | Controller info at any given point, plus a pointer
-- to poll the main device again. This is safe,
-- since there is only one writer at a time (the device itself).
newtype ControllerRef =
ControllerRef { controllerData :: (IORef Controller, Controller -> IO Controller) }
-- * General API
-- | Initialize the available input devices. This operation
-- returns a reference to a controller, which enables
-- getting its state as many times as necessary. It does
-- not provide any information about its nature, abilities, etc.
initializeInputDevices :: IO ControllerRef
initializeInputDevices = do
nr <- newIORef defaultInfo
return $ ControllerRef (nr, sdlGetController)
where defaultInfo = Controller (0,0) False False False False False False False
-- | Sense from the controller, providing its current
-- state. This should return a new Controller state
-- if available, or the last one there was.
--
-- It is assumed that the sensing function is always
-- callable, and that it knows how to update the
-- Controller info if necessary.
senseInput :: ControllerRef -> IO Controller
senseInput (ControllerRef (cref, sensor)) =
modifyIORefIO cref sensor
type ControllerDev = IO (Maybe (Controller -> IO Controller))
-- * SDL API (mid-level)
-- ** Sensing
-- | Sense the SDL keyboard and mouse and update
-- the controller. It only senses the mouse position,
-- the primary mouse button, and the p key to pause
-- the game.
--
-- We need a non-blocking controller-polling function.
-- TODO: Check http://gameprogrammer.com/fastevents/fastevents1.html
sdlGetController :: Controller -> IO Controller
sdlGetController info =
foldLoopM info pollEvent (not.isEmptyEvent) ((return .) . handleEvent)
handleEvent :: Controller -> SDL.Event -> Controller
handleEvent c e =
case e of
MouseMotion x y _ _ -> c { controllerPos = (fromIntegral x, fromIntegral y)}
MouseButtonDown _ _ ButtonLeft -> c { controllerClick = True }
MouseButtonUp _ _ ButtonLeft -> c { controllerClick = False}
KeyUp (Keysym { symKey = SDLK_p }) -> c { controllerPause = not (controllerPause c) }
KeyUp (Keysym { symKey = SDLK_f }) -> c { controllerFullscreen = not (controllerFullscreen c) }
KeyDown (Keysym { symKey = SDLK_w }) -> c { controllerSuperSlow = True }
KeyUp (Keysym { symKey = SDLK_w }) -> c { controllerSuperSlow = False }
KeyDown (Keysym { symKey = SDLK_s }) -> c { controllerSlow = True }
KeyUp (Keysym { symKey = SDLK_s }) -> c { controllerSlow = False }
KeyDown (Keysym { symKey = SDLK_x }) -> c { controllerFast = True }
KeyUp (Keysym { symKey = SDLK_x }) -> c { controllerFast = False }
KeyDown (Keysym { symKey = SDLK_SPACE }) -> c { controllerClick = True }
KeyUp (Keysym { symKey = SDLK_SPACE }) -> c { controllerClick = False }
KeyDown (Keysym { symKey = SDLK_ESCAPE}) -> c { controllerExit = True }
_ -> c
-- * Aux IOREf
modifyIORefIO :: IORef a -> (a -> IO a) -> IO a
modifyIORefIO ref modify = do
v <- readIORef ref
new <- modify v
writeIORef ref new
return new
| keera-studios/pang-a-lambda | Experiments/collisions/Input.hs | gpl-3.0 | 4,197 | 0 | 12 | 1,000 | 861 | 485 | 376 | 52 | 15 |
module Automatic.TextureTest where
import Graphics.UI.SDL2
import System.Mem(performGC)
windowWidth = 320
windowHeight = 240
mkWindowAndRenderer =
withWindowAndRenderer
"Test: drawLine"
WinPosCentered
WinPosCentered
windowWidth
windowHeight
[WindowShown]
(-1)
[RendererAccelerated]
textureTest =
withSdl [InitEverything] $
mkWindowAndRenderer $ \(window,renderer) -> do
t <- createTexture
renderer
PixelFormatARGB8888
TextureAccessTarget
320
240
renderDrawLine renderer 0 0 100 100
setRenderTarget renderer t
renderDrawLine renderer 0 0 100 100
performGC
renderDrawLine renderer 0 0 100 100
return True
| EJahren/haskell-sdl2 | Tests/Automatic/TextureTest.hs | gpl-3.0 | 680 | 0 | 10 | 143 | 172 | 87 | 85 | 30 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.SQLAdmin.Types.Sum
-- 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)
--
module Network.Google.SQLAdmin.Types.Sum where
import Network.Google.Prelude
| rueshyna/gogol | gogol-sqladmin/gen/Network/Google/SQLAdmin/Types/Sum.hs | mpl-2.0 | 600 | 0 | 4 | 109 | 29 | 25 | 4 | 8 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
-- | Data structures used for DCB computation.
module DCB.Structures where
import Data.Array.Repa as A hiding ((++))
import Data.Int
import Util
-- | a one-dimensional array
type Vector r e = Array r DIM1 e
-- | a two-dimensional array
type Matrix r e = Array r DIM2 e
-- | A 'Matrix' of attribute values assigned to a graph’s nodes.
-- Each row contains the corresponding node’s attribute values.
type Attr = Matrix A.U Double
-- | Adjacency-Matrix
type Adj = Matrix A.U Int8
-- | 'Matrix' storing the extent of a 'Graph'’s constraints fulfillment.
-- It stores the minimum (zeroth column) and maximum (first column) value of all
-- the 'Graph'’s nodes per attribute.
-- The 'Vector' stores values of @1@ if the bounds are within the allowed range
-- regarding the corresponding attribute, or @0@ if not.
type Constraints = (Vector A.U Int, Matrix A.U Double)
-- | A 'Vector' of weights indicating how much divergence is allowed in which dimension.
-- Each dimension represents an attribute.
type MaxDivergence = Vector A.U Double
-- | A graph’s density.
type Density = Double
-- | consists of a 'Vector' denoting which columns of the 'Matrix' represents which originating
-- column in the global adjancency-matrix, a 'Matrix' of 'Constraints' and a scalar denoting the graph’s 'Density'
type Graph = (Vector A.U Int, Constraints, Density)
-- | inverse sorting on graphs.
--
-- "smallest" graph has max number of Nodes
--
-- If Nodecount is identical we prioritize the number of fulfilled Constraints
instance Ord Graph where
(nodes, (const,_), _) `compare` (nodes', (const',_), _) =
let
s1 = (A.size $ A.extent nodes')
s2 = (A.size $ A.extent nodes)
in
if s1 == s2 then
let
const1 = (A.sumAllS const')
const2 = (A.sumAllS const)
in
const1 `compare` const2
else
s1 `compare` s2
| Drezil/hgraph | src/DCB/Structures.hs | agpl-3.0 | 2,326 | 0 | 15 | 734 | 328 | 199 | 129 | 26 | 0 |
{-# LANGUAGE
TypeFamilies,
FlexibleInstances #-}
module OrdSet where
import Set
data Extended x = NegInf | PosInf | Finite x
deriving(Show,Eq)
isFinite :: Extended x -> Bool
isFinite (Finite a) = True
isFinite _ = False
instance Ord x => Ord (Extended x) where
NegInf <= _ = True
_ <= PosInf = True
PosInf <= _ = False
_ <= NegInf = False
Finite a1 <= Finite a2 = a1 <= a2
-- A type `OrdSet (Extended x)' denotes open, closed, or half-open intervals of type `x'.
-- WARNING: Do not use the `Ivl' constructor! See PairSet.hs for reasons.
data OrdSet x = EmptyIvl | UnivIvl | Ivl (Extended x) (Extended x) Bool Bool
deriving(Eq)
closedIvl :: Ord x => x -> x -> OrdSet x
closedIvl a1 a2 = finiteIvl a1 a2 True True
finiteIvl :: Ord x => x -> x -> Bool -> Bool -> OrdSet x
finiteIvl a1 a2 c1 c2 = ivl (Finite a1) (Finite a2) c1 c2
ivl :: Ord x => Extended x -> Extended x -> Bool -> Bool -> OrdSet x
ivl NegInf PosInf _ _ = UnivIvl
ivl a1 a2 c1 c2 =
let c1' = c1 && isFinite a1
c2' = c2 && isFinite a2
in if a1 < a2
then Ivl a1 a2 c1' c2'
else if a1 > a2
then EmptyIvl
else if c1' && c2'
then Ivl a1 a2 c1' c2'
else EmptyIvl
instance Show x => Show (OrdSet x) where
showsPrec d EmptyIvl = showString "EmptyIvl"
showsPrec d UnivIvl = showString "UnivIvl"
showsPrec d (Ivl (Finite a1) (Finite a2) True True) =
let app_prec = 10
in showParen (d > app_prec) $
showString "closedIvl " . showsPrec (app_prec+1) a1 .
showString " " . showsPrec (app_prec+1) a2
showsPrec d (Ivl (Finite a1) (Finite a2) c1 c2) =
let app_prec = 10
in showParen (d > app_prec) $
showString "finiteIvl " . showsPrec (app_prec+1) a1 .
showString " " . showsPrec (app_prec+1) a2 .
showString " " . showsPrec (app_prec+1) c1 .
showString " " . showsPrec (app_prec+1) c2
showsPrec d (Ivl a1 a2 c1 c2) =
let app_prec = 10
in showParen (d > app_prec) $
showString "ivl " . showsPrec (app_prec+1) a1 .
showString " " . showsPrec (app_prec+1) a2 .
showString " " . showsPrec (app_prec+1) c1 .
showString " " . showsPrec (app_prec+1) c2
instance Ord x => LatticeSet (OrdSet x) where
type MemberType (OrdSet x) = x
empty = EmptyIvl
univ = UnivIvl
EmptyIvl /\ _ = EmptyIvl
_ /\ EmptyIvl = EmptyIvl
UnivIvl /\ a = a
a /\ UnivIvl = a
Ivl a1 a2 c1 c2 /\ Ivl b1 b2 d1 d2 =
let (e1,f1) = if a1 > b1 then (a1,c1) else if a1 < b1 then (b1,d1) else (a1, c1 && d1)
(e2,f2) = if a2 < b2 then (a2,c2) else if a2 > b2 then (b2,d2) else (a2, c2 && d2)
in ivl e1 e2 f1 f2
EmptyIvl \/ a = a
a \/ EmptyIvl = a
UnivIvl \/ _ = UnivIvl
_ \/ UnivIvl = UnivIvl
Ivl a1 a2 c1 c2 \/ Ivl b1 b2 d1 d2 =
let (e1,f1) = if a1 < b1 then (a1,c1) else if a1 > b1 then (b1,d1) else (a1, c1 || d1)
(e2,f2) = if a2 > b2 then (a2,c2) else if a2 < b2 then (b2,d2) else (a2, c2 || d2)
in ivl e1 e2 f1 f2
member EmptyIvl _ = False
member UnivIvl _ = True
member (Ivl a1 a2 c1 c2) a =
let a' = Finite a
in (a1 < a' || (a1 == a' && c1)) && (a' < a2 || (a' == a2 && c2))
singleton a = closedIvl a a
instance Ord x => MeasurableSet (OrdSet x) where
EmptyIvl \\ _ = []
a \\ EmptyIvl = [a]
_ \\ UnivIvl = []
UnivIvl \\ a = Ivl NegInf PosInf False False \\ a
Ivl a1 b1 c1 d1 \\ Ivl a2 b2 c2 d2 =
if (Ivl a1 b1 c1 d1 /\ Ivl a2 b2 c2 d2) == empty
then [Ivl a1 b1 c1 d1]
else
if a1 < a2 || (a1 == a2 && c1 && not c2)
then if b2 < b1 || (b2 == b1 && not d2 && d1)
-- ======
-- ==
then [ivl a1 a2 c1 (not c2), ivl b2 b1 (not d2) d1]
-- ====== ======
-- ====== or ===
else [ivl a1 a2 c1 (not c2)]
else if b2 < b1 || (b2 == b1 && not d2 && d1)
-- ====== ======
-- ====== or ===
then [ivl b2 b1 (not d2) d1]
-- == === === ======
-- ====== or ====== or ====== or ======
else []
instance (Num x, Ord x) => LebesgueMeasurableSet (OrdSet x) where
type MeasureType (OrdSet x) = Extended x
measure EmptyIvl = Finite (fromInteger 0)
measure (Ivl (Finite a1) (Finite a2) _ _) = Finite (a2 - a1)
measure _ = PosInf
type RealSet = OrdSet Float
| ntoronto/drbayes | drbayes/direct/haskell-impl/OrdSet.hs | lgpl-3.0 | 4,466 | 0 | 18 | 1,463 | 1,926 | 976 | 950 | 103 | 4 |
module ViperVM.Platform.Proc (
Proc(..), wrapProc, procInfo, procCapabilities,
procName, procVendor, procSupports
) where
import ViperVM.Platform.Memory
import ViperVM.Platform.ProcessorCapabilities
import qualified ViperVM.Platform.Peer.ProcPeer as Peer
import Data.Set (Set, member)
import qualified Data.Set as Set
import Data.Maybe (maybeToList)
import Text.Printf
-- | A processing unit
data Proc = Proc {
procId :: Int,
procPeer :: Peer.ProcPeer,
procMemories :: Set Memory
}
instance Eq Proc where
(==) p1 p2 = procId p1 == procId p2
instance Ord Proc where
compare p1 p2 = compare (procId p1) (procId p2)
instance Show Proc where
show p = "Proc " ++ show (procId p)
-- | Wrap a peer proc
wrapProc :: [Memory] -> Peer.ProcPeer -> Int -> IO Proc
wrapProc mems peer pId = do
peerMems <- Peer.procMemories peer
let
mems' = fmap (\m -> (memoryPeer m, m)) mems
ms = Set.fromList $ concatMap (\m -> maybeToList (lookup m mems')) peerMems
return (Proc pId peer ms)
-- | Return processor name
procName :: Proc -> String
procName = Peer.procName . procPeer
-- | Return processor vendor
procVendor :: Proc -> String
procVendor = Peer.procVendor . procPeer
-- | Retrieve processor capabilities
procCapabilities :: Proc -> Set ProcessorCapability
procCapabilities = Peer.procCapabilities . procPeer
-- | Get processor information string
procInfo :: Proc -> String
procInfo proc = printf "[Proc %d] %s (%s)" (procId proc) (procName proc) (procVendor proc)
-- | Indicates if a processor supports a given capability
procSupports :: Proc -> ProcessorCapability -> Bool
procSupports p cap = cap `member` procCapabilities p
| hsyl20/HViperVM | lib/ViperVM/Platform/Proc.hs | lgpl-3.0 | 1,688 | 0 | 16 | 319 | 495 | 272 | 223 | 37 | 1 |
data BookInfo = Book Int String [String]
deriving (Show)
data MagazineInfo = Magazine Int String [String]
deriving (Show)
type CustomerID = Int --- Type synonym
type ReviewBody = String
data BookReview = BookReview BookInfo CustomerID String
data BetterReviw = BetterReviw BookInfo CustomerID ReviewBody
type BookRecord = (BookInfo, BookReview)
bookID (Book id title authors) = id
bookTitle (Book id title authors) = title
bookAuthors (Book id title authors) = authors
myInfo = Book 9780135072455 "Algebra of Programming"
["Richard Bird", "Oege de Moor"]
| caiorss/Functional-Programming | haskell/rwh/ch03/BookStore3.hs | unlicense | 636 | 0 | 7 | 162 | 170 | 94 | 76 | 14 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module MT.Class (
MonadT(..)
) where
import Monad
class MonadT t where
lift :: (Monad m) => m a -> t m a
| seckcoder/lang-learn | haskell/lambda-calculus/src/MT/Class.hs | unlicense | 200 | 0 | 9 | 52 | 55 | 31 | 24 | 7 | 0 |
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE RebindableSyntax #-}
module RebindableSyntax where
import Prelude hiding (return, (>>), (>>=))
concatNums :: String
concatNums = do
"80"
"60"
"10"
where
(>>) = (++)
return x = x
addNums :: Num a => a
addNums = do
80
60
10
where
(>>) = (+)
return x = x
| haroldcarr/learn-haskell-coq-ml-etc | haskell/playpen/misc/src/RebindableSyntax.hs | unlicense | 405 | 0 | 7 | 110 | 109 | 65 | 44 | 19 | 1 |
class Node a where
children::(Node a)=>a->[a]
--data LatticePoint a b = LatticePoint a b deriving Show
type LatticePoint = (Int, Int)
instance Node Int where
--children::(LatticePoint Int Int)->[LatticePoint Int Int]
--children (LatticePoint a b) = [(LatticePoint (a+1) b), (LatticePoint (a-1) b), (LatticePoint a (b+1)), (LatticePoint a (b-1))]
--children (a,b) = [(a+1,b), (a,b+1)]
children a = (succ a):[]
instance (Num a, Num b)=>(Node (a,b)) where
children (a,b) = [(a+1,b), (a,b+1), (a-1,b), (a,b-1)]
{-}
data TicTacToePoint = Empty | Player1 | Player2
type TicTacToeBoard = ((TicTacToePoint,TicTacToePoint,TicTacToePoint),(TicTacToePoint,TicTacToePoint,TicTacToePoint),(TicTacToePoint,TicTacToePoint,TicTacToePoint))
-}
| Crazycolorz5/Haskell-Code | searchAlgorithms.hs | unlicense | 756 | 2 | 9 | 114 | 176 | 101 | 75 | 7 | 0 |
module L2ARP where
import L2
import L3Address
instance L2Message L2ARP where
msgType _ = L2PacketType
instance L2Packet L2ARP where
pktType _ = L2PacketTypeARP
data L2ARP = L2ARPRequest L3Address | L2ARPResponse L3Address
-- note: 'MAC' address is not in the message body, it should be obtained from the envelope
| hdb3/FPR2 | L2ARP.hs | apache-2.0 | 324 | 0 | 6 | 59 | 57 | 32 | 25 | 8 | 0 |
module S2E6 where
import Data.List
sublist :: (Eq a) => [a] -> [a] -> Bool
sublist xs ys = any (sublist' xs) (tails ys)
sublist' :: (Eq a) => [a] -> [a] -> Bool
sublist' [] _ = True
sublist' _ [] = False
sublist' (x:xs) (y:ys) = x == y && sublist' xs ys
partial :: (Eq a) => [a] -> [a] -> Bool
partial [] _ = True
partial _ [] = False
partial (x:xs) (y:ys) | x == y = partial xs ys
| otherwise = partial (x:xs) ys
| wouwouwou/module_8 | src/main/haskell/series2/exercise6.hs | apache-2.0 | 439 | 0 | 8 | 117 | 265 | 139 | 126 | 13 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ParallelListComp #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ViewPatterns #-}
{-
Copyright 2018 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module CodeWorld.CollaborationUI
( UIState
, SetupPhase(..)
, Step(..)
, initial
, step
, event
, picture
, startWaiting
, updatePlayers
) where
import CodeWorld.Color
import CodeWorld.Event
import CodeWorld.Picture
import Data.Char
import Data.Monoid
import qualified Data.Text as T
import Data.Text (Text)
-- | The enumeration type contains all the high-level states that the game UI
-- can be in. It is used as a type-index to 'UIState' to ensure that the UI
-- state matches the abstract state.
--
-- The possible UI-triggered transitions of this state are described by
-- 'Step'.
data SetupPhase
= SMain
| SConnect
| SWait
-- | Possible steps taken from a given setup phase
data family Step :: (SetupPhase -> *) -> SetupPhase -> *
data instance Step f SMain = ContinueMain (f SMain)
| Create (f SConnect)
| Join Text (f SConnect)
data instance Step f SConnect = ContinueConnect (f SConnect)
| CancelConnect (f SMain)
data instance Step f SWait = ContinueWait (f SWait)
| CancelWait (f SMain)
-- | The UI state, indexed by the 'SetupPhase'
data UIState (s :: SetupPhase) where
MainMenu :: Double -> Point -> UIState SMain
Joining :: Double -> Point -> Text -> UIState SMain
Connecting :: Double -> Point -> UIState SConnect
Waiting
:: Double
-> Point
-> Text
-> Int
-> Int {- numPlayers :: -}
{- present -}
-> UIState SWait
continueUIState :: UIState s -> Step UIState s
continueUIState s@MainMenu {} = ContinueMain s
continueUIState s@Joining {} = ContinueMain s
continueUIState s@Connecting {} = ContinueConnect s
continueUIState s@Waiting {} = ContinueWait s
time :: UIState s -> Double
time (MainMenu t _) = t
time (Joining t _ _) = t
time (Connecting t _) = t
time (Waiting t _ _ _ _) = t
mousePos :: UIState s -> Point
mousePos (MainMenu _ p) = p
mousePos (Joining _ p _) = p
mousePos (Connecting _ p) = p
mousePos (Waiting _ p _ _ _) = p
-- Takes an absolute time, not a delta. A bit easier.
step :: Double -> UIState s -> UIState s
step t (MainMenu _ p) = MainMenu t p
step t (Joining _ p c) = Joining t p c
step t (Connecting _ p) = Connecting t p
step t (Waiting _ p c n m) = Waiting t p c n m
setMousePos :: Point -> UIState s -> UIState s
setMousePos p (MainMenu t _) = MainMenu t p
setMousePos p (Joining t _ c) = Joining t p c
setMousePos p (Connecting t _) = Connecting t p
setMousePos p (Waiting t _ c n m) = Waiting t p c n m
initial :: UIState SMain
initial = MainMenu 0 (0, 0)
startWaiting :: Text -> UIState a -> UIState SWait
startWaiting code s = Waiting (time s) (mousePos s) code 0 0
updatePlayers :: Int -> Int -> UIState SWait -> UIState SWait
updatePlayers n m (Waiting time mousePos code _ _) =
Waiting time mousePos code n m
-- | Handling a UI event. May change the phase.
event :: Event -> UIState s -> Step UIState s
event (MouseMovement p) s = continueUIState (setMousePos p s)
event CreateClick (MainMenu t p) = Create (Connecting t p)
event JoinClick (MainMenu t p) = ContinueMain (Joining t p "")
event (LetterPress k) (Joining t p code)
| T.length code < 4 = ContinueMain (Joining t p (code <> k))
event BackSpace (Joining t p code)
| T.length code > 0 = ContinueMain (Joining t p (T.init code))
event ConnectClick (Joining t p code)
| T.length code == 4 = Join code (Connecting t p)
event CancelClick (Joining t p code) = ContinueMain (MainMenu t p)
event CancelClick (Connecting t p) = CancelConnect (MainMenu t p)
event CancelClick (Waiting t p c n m) = CancelWait (MainMenu t p)
event _ s = continueUIState s
pattern CreateClick <-
MousePress LeftButton (inButton 0 1.5 8 2 -> True)
pattern JoinClick <-
MousePress LeftButton (inButton 0 (-1.5) 8 2 -> True)
pattern ConnectClick <-
MousePress LeftButton (inButton 0 (-3.0) 8 2 -> True)
pattern LetterPress c <- (isLetterPress -> Just c)
pattern BackSpace <- KeyPress "Backspace"
pattern CancelClick <- (isCancelClick -> True)
isLetterPress :: Event -> Maybe Text
isLetterPress (KeyPress k)
| T.length k == 1
, isLetter (T.head k) = Just (T.toUpper k)
isLetterPress _ = Nothing
isCancelClick :: Event -> Bool
isCancelClick (KeyPress "Esc") = True
isCancelClick (MousePress LeftButton point) = inButton 0 (-3) 8 2 point
isCancelClick _ = False
picture :: UIState s -> Picture
picture (MainMenu time mousePos) =
button "New" (dull green) 0 1.5 8 2 mousePos &
button "Join" (dull green) 0 (-1.5) 8 2 mousePos &
connectScreen "Main Menu" time
picture (Joining time mousePos code) =
translated 0 2 (text "Enter the game key:") & letterBoxes white code &
(if T.length code < 4
then button "Cancel" (dull yellow) 0 (-3) 8 2 mousePos
else button "Join" (dull green) 0 (-3) 8 2 mousePos) &
connectScreen "Join Game" time
picture (Connecting time mousePos) =
button "Cancel" (dull yellow) 0 (-3) 8 2 mousePos &
connectScreen "Connecting..." time
picture (Waiting time mousePos code numPlayers present) =
translated 0 2 (text "Share this key with other players:") &
translated 0 4 (playerDots numPlayers present) &
letterBoxes (gray 0.8) code &
button "Cancel" (dull yellow) 0 (-3) 8 2 mousePos &
connectScreen "Waiting" time
letterBoxes :: Color -> Text -> Picture
letterBoxes color txt =
pictures
[ translated x 0 (letterBox color (T.singleton c))
| c <- pad 4 ' ' (take 4 (T.unpack txt))
| x <- [-3, -1, 1, 3]
]
letterBox :: Color -> Text -> Picture
letterBox c t =
thickRectangle 0.1 1.5 1.5 & text t & colored c (solidRectangle 1.5 1.5)
pad :: Int -> a -> [a] -> [a]
pad 0 _ xs = xs
pad n v (x:xs) = x : pad (n - 1) v xs
pad n v [] = v : pad (n - 1) v []
inButton :: Double -> Double -> Double -> Double -> Point -> Bool
inButton x y w h (mx, my) =
mx >= x - w / 2 && mx <= x + w / 2 && my >= y - h / 2 && my <= y + h / 2
button ::
Text -> Color -> Double -> Double -> Double -> Double -> Point -> Picture
button txt btnColor x y w h (mx, my) =
translated x y $
colored white (styledText Plain SansSerif txt) &
colored color (roundRect w h)
where
color
| inButton x y w h (mx, my) = btnColor
| otherwise = dark btnColor
roundRect :: Double -> Double -> Picture
roundRect w h =
solidRectangle w (h - 0.5) & solidRectangle (w - 0.5) h &
pictures
[ translated x y (solidCircle 0.25)
| x <- [-w / 2 + 0.25, w / 2 - 0.25]
, y <- [-h / 2 + 0.25, h / 2 - 0.25]
]
playerDots n m
| n > 8 = text $ T.pack $ show m ++ " / " ++ show n
playerDots n m =
pictures
[ translated
(size * fromIntegral i - size * fromIntegral n / 2)
0
(dot (i <= m))
| i <- [1 .. n]
]
where
dot True = solidCircle (0.4 * size)
dot False = circle (0.4 * size)
size = 1
connectScreen :: Text -> Double -> Picture
connectScreen hdr t =
translated 0 7 connectBox & translated 0 (-7) codeWorldLogo &
colored (RGBA 0.85 0.86 0.9 1) (solidRectangle 20 20)
where
connectBox =
scaled 2 2 (text hdr) & rectangle 14 3 &
colored connectColor (solidRectangle 14 3)
connectColor =
let k = (1 + sin (3 * t)) / 5
in fromHSL (k + 0.5) 0.8 0.7
| tgdavies/codeworld | codeworld-api/src/CodeWorld/CollaborationUI.hs | apache-2.0 | 8,286 | 1 | 19 | 2,111 | 3,016 | 1,519 | 1,497 | 186 | 2 |
module Y15.D18 where
import qualified Data.Vector.Unboxed as VU
import Data.Vector.Unboxed.Mutable (MVector)
import qualified Data.Vector.Unboxed.Mutable as VUM
import Util
import Imports
data YX = YX Int Int
data Board m = Board
{ bounds :: (YX, YX) -- (min,max) coords (inclusive)
, vector :: MVector (PrimState m) Bool
}
type TickFn = (YX,YX) -> YX -> Bool -> Int -> Bool
lights :: Parser [[Bool]]
lights =
rowOfLights `endBy` eol
where
rowOfLights :: Parser [Bool]
rowOfLights = many light
light :: Parser Bool
light = char '#' $> True
<|> char '.' $> False
mkLights :: PrimMonad m => [[Bool]] -> m (Board m)
mkLights xs =
let h = length xs - 1
w = (length . head $ xs) - 1
in Board (YX 0 0, YX h w) <$> (VU.thaw . VU.fromList $ join xs)
unLights :: PrimMonad m => Board m -> m [[Bool]]
unLights Board{bounds,vector} = do
let (_, YX _ x0) = bounds -- NOTE no # of rows check
chunksOf (x0 + 1) . VU.toList <$> VU.freeze vector
getOr :: PrimMonad m => Bool -> Board m -> YX -> m Bool
getOr orV Board{bounds, vector} (YX y x) =
let (YX y0 x0, YX y1 x1) = bounds
in if y < y0 || y > y1
|| x < x0 || x > x1
then return orV
else VUM.read vector (y * (x1 + 1) + x)
neighborsOnAround :: PrimMonad m => Board m -> YX -> m Int
neighborsOnAround b (YX y x) =
length . filter id <$> mapM (getOr False b)
[ YX (y-1) (x-1), YX (y-1) x, YX (y-1) (x+1)
, YX y (x-1), YX y (x+1)
, YX (y+1) (x-1), YX (y+1) x, YX (y+1) (x+1)
]
tickLights :: PrimMonad m => TickFn -> Board m -> Board m -> m ()
tickLights f src@Board{bounds} dst = do
let (YX y0 x0, YX y1 x1) = bounds
forM_ [ (YX y x, y * (x1 + 1) + x)
| y <- [y0..y1]
, x <- [x0..x1]
] $ \(yx, i) -> do
v <- VUM.read (vector src) i
n <- neighborsOnAround src yx
VUM.write (vector dst) i (f bounds yx v n)
tickTimes :: PrimMonad m => TickFn -> Board m -> Int -> m ()
tickTimes tick b n = do
dstVector <- VUM.replicate (VUM.length (vector b)) False
let bb = b {vector = dstVector}
stepTimes_ n b bb
when (odd n) $
VUM.copy (vector b) (vector bb)
where
stepTimes_ :: PrimMonad m => Int -> Board m -> Board m -> m ()
stepTimes_ 0 _ _ = return ()
stepTimes_ i src dst = do
tickLights tick src dst
stepTimes_ (i-1) dst src
solve :: TickFn -> String -> IO Int
solve tick s = do
b <- mkLights (parseOrDie lights s)
tickTimes tick b 100
VUM.foldl' (\a x -> a + bool 0 1 x) 0 (vector b)
-- A light which is on stays on when 2 or 3 neighbors are on, and turns off otherwise.
-- A light which is off turns on if exactly 3 neighbors are on, and stays off otherwise.
tick1 :: TickFn
tick1 _ _ v n =
(v && (n == 2 || n == 3))
|| (not v && n == 3)
-- four lights, one in each corner, are stuck on and can't be turned off.
tick2 :: TickFn
tick2 bounds@(YX ya xa, YX yz xz) yx@(YX y x) v n =
((y == ya || y == yz) && (x == xa || x == xz))
|| tick1 bounds yx v n
solve1, solve2 :: String -> IO Int
solve1 = solve tick1
solve2 = solve tick2
| oshyshko/adventofcode | src/Y15/D18.hs | bsd-3-clause | 3,238 | 0 | 14 | 996 | 1,510 | 771 | 739 | -1 | -1 |
------------------------------------------------------------------------------
-- |
-- Module : GGTD.Relation
-- Copyright : (C) 2016 Samuli Thomasson
-- License : %% (see the file LICENSE)
-- Maintainer : Samuli Thomasson <samuli.thomasson@paivola.fi>
-- Stability : experimental
-- Portability : non-portable
--
-- We call the edges of the graph relations. Relations basically define the
-- structure of the graph and with different relations (different labels on
-- the edges) we can define kind-of subgraphs, like groups with "relGroup",
-- contexts with "relLink". The most common relation is "relChild",
------------------------------------------------------------------------------
module GGTD.Relation where
import GGTD.Base
-- | In a kind of main hierarchial view, where root (node 0) is at the top,
-- there are groups at the middle and "relChild"'s at the leaves.
relGroup :: Relation
relGroup = "group"
-- | Single item that could be actionable; i.e. it may have a waiting- or
-- done-flag set, but if it didn't it would qualify as something to do.
relChild :: Relation
relChild = "child"
-- | A reference is some kind of resource that is relevant to what links to
-- it.
relRef :: Relation
relRef = "ref"
-- | A link is somewhat like a 'relGroup', with the exception that the
-- successors of a node that is linked to will not be considered by any
-- traversal. (The direct target of a link edge itself is.) Links are a way
-- to make different projections of the graph, for example to separate
-- contexts for at home, at work etc.
relLink :: Relation
relLink = "link"
-- | List of all relations we use.
relations :: [Relation]
relations = [relGroup, relChild, relLink, relRef]
| SimSaladin/ggtd | src/GGTD/Relation.hs | bsd-3-clause | 1,730 | 0 | 5 | 309 | 102 | 73 | 29 | 12 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Web.Server (
runServer
) where
import Control.Concurrent.Async (mapConcurrently)
import Control.Monad (forM_)
import Control.Monad.IO.Class (liftIO)
import Data.List (nub, sort)
import qualified Data.Text.Lazy as TL
import Text.Blaze.Html.Renderer.Text
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import Web.Scotty
import Data.ConfigParser
import Web.Scraper
runServer :: [Feed] -> IO ()
runServer feeds = scotty 3000 $ do
get "/" $ do
videos <- fmap (sort . nub . concat) . liftIO $
mapConcurrently scrapeChannel feeds
html . renderVideos $ take 50 videos
get "/video/:id" $ do
vid <- param "id" :: ActionM String
html $ renderVideo vid
get "/style.css" $
file "static/style.css"
notFound $
text "Four-Oh-Four"
renderVideos :: [Video] -> TL.Text
renderVideos videos = renderHtml $ do
H.head $ do
H.title "TinfoilSub"
H.link H.! A.rel "stylesheet" H.! A.href "/style.css"
H.body $ do
H.h1 "TinfoilSub"
H.ol . forM_ videos $ H.li . H.preEscapedToHtml . showVideo
renderVideo :: String -> TL.Text
renderVideo vid = renderHtml $ do
H.head $ do
H.title "TinfoilSub"
H.link H.! A.rel "stylesheet" H.! A.href "/style.css"
let url = "<iframe src='https://youtube.com/embed/" ++ vid ++ "'></iframe>"
H.body $ H.preEscapedToHtml url
| sulami/tinfoilsub | src/Web/Server.hs | bsd-3-clause | 1,483 | 0 | 17 | 354 | 473 | 239 | 234 | 42 | 1 |
module Process.PeerChan
( PeerEventMessage
, PeerEventChannel
) where
import Control.Concurrent
import Control.Concurrent.STM
import qualified Data.ByteString as B
import Data.Word (Word8)
import Torrent
type BitField = B.ByteString
data PeerMessage
= KeepAlive
| Choke
| Unchoke
| Interested
| NotInterested
| Have PieceNum
| BitField BitField
| Request PieceNum PieceBlock
| Piece PieceNum Int B.ByteString
| Cancel PieceNum PieceBlock
| Port Integer
| HaveAll
| HaveNone
| Suggest PieceNum
| RejectRequest PieceNum PieceBlock
| AllowedFast PieceNum
| Extended Word8 B.ByteString
deriving (Eq, Show)
data PeerChokeMessage
= ChokePeer
| UnchokePeer
| PieceCompleted PieceNum
| CancelBlock PieceNum PieceBlock
data PeerProcessMessage
= FromPeer (PeerMessage, Int)
| FromSender Int
| FromChokeManager PeerChokeMessage
| PeerProcessTick
type PeerProcessChannel = TChan PeerProcessMessage
data PeerEventMessage
= PeerConnect InfoHash ThreadId PeerProcessChannel
| PeerDisconnect ThreadId
type PeerEventChannel = TChan PeerEventMessage
| artems/htorr | src/Process/PeerChan.hs | bsd-3-clause | 1,174 | 0 | 7 | 270 | 242 | 145 | 97 | 43 | 0 |
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls #-}
{-# OPTIONS_GHC -fno-cse -fno-full-laziness #-}
-- | Low-level interface to Expat. Unless speed is paramount, this should
-- normally be avoided in favour of the interfaces provided by
-- 'Text.XML.Expat.SAX' and 'Text.XML.Expat.Tree', etc.
module Text.XML.Expat.Internal.IO (
HParser,
hexpatNewParser,
encodingToString,
Encoding(..),
XMLParseError(..),
XMLParseLocation(..)
) where
import Control.Applicative
import Control.DeepSeq
import qualified Data.ByteString as B
import qualified Data.ByteString.Internal as I
import Data.Int
import Data.Word
import Foreign
import Foreign.C
data Parser_struct
type ParserPtr = Ptr Parser_struct
data Encoding = ASCII | UTF8 | UTF16 | ISO88591
encodingToString :: Encoding -> String
encodingToString ASCII = "US-ASCII"
encodingToString UTF8 = "UTF-8"
encodingToString UTF16 = "UTF-16"
encodingToString ISO88591 = "ISO-8859-1"
withOptEncoding :: Maybe Encoding -> (CString -> IO a) -> IO a
withOptEncoding Nothing f = f nullPtr
withOptEncoding (Just enc) f = withCString (encodingToString enc) f
-- ByteString.useAsCStringLen is almost what we need, but C2HS wants a CInt
-- instead of an Int.
withBStringLen :: B.ByteString -> ((CString, CInt) -> IO a) -> IO a
withBStringLen bs f = do
B.useAsCStringLen bs $ \(str, len) -> f (str, fromIntegral len)
unStatus :: CInt -> Bool
unStatus 0 = False
unStatus _ = True
getError :: ParserPtr -> IO XMLParseError
getError pp = do
code <- xmlGetErrorCode pp
cerr <- xmlErrorString code
err <- peekCString cerr
loc <- getParseLocation pp
return $ XMLParseError err loc
-- |Obtain C value from Haskell 'Bool'.
--
cFromBool :: Num a => Bool -> a
cFromBool = fromBool
-- | Parse error, consisting of message text and error location
data XMLParseError = XMLParseError String XMLParseLocation deriving (Eq, Show)
instance NFData XMLParseError where
rnf (XMLParseError msg loc) = rnf (msg, loc)
-- | Specifies a location of an event within the input text
data XMLParseLocation = XMLParseLocation {
xmlLineNumber :: Int64, -- ^ Line number of the event
xmlColumnNumber :: Int64, -- ^ Column number of the event
xmlByteIndex :: Int64, -- ^ Byte index of event from start of document
xmlByteCount :: Int64 -- ^ The number of bytes in the event
}
deriving (Eq, Show)
instance NFData XMLParseLocation where
rnf (XMLParseLocation lin col ind cou) = rnf (lin, col, ind, cou)
getParseLocation :: ParserPtr -> IO XMLParseLocation
getParseLocation pp = do
line <- xmlGetCurrentLineNumber pp
col <- xmlGetCurrentColumnNumber pp
index <- xmlGetCurrentByteIndex pp
count <- xmlGetCurrentByteCount pp
return $ XMLParseLocation {
xmlLineNumber = fromIntegral line,
xmlColumnNumber = fromIntegral col,
xmlByteIndex = fromIntegral index,
xmlByteCount = fromIntegral count
}
-- Note on word sizes:
--
-- on expat 2.0:
-- XML_GetCurrentLineNumber returns XML_Size
-- XML_GetCurrentColumnNumber returns XML_Size
-- XML_GetCurrentByteIndex returns XML_Index
-- These are defined in expat_external.h
--
-- debian-i386 says XML_Size and XML_Index are 4 bytes.
-- ubuntu-amd64 says XML_Size and XML_Index are 8 bytes.
-- These two systems do NOT define XML_LARGE_SIZE, which would force these types
-- to be 64-bit.
--
-- If we guess the word size too small, it shouldn't matter: We will just discard
-- the most significant part. If we get the word size too large, we will get
-- garbage (very bad).
--
-- So - what I will do is use CLong and CULong, which correspond to what expat
-- is using when XML_LARGE_SIZE is disabled, and give the correct sizes on the
-- two machines mentioned above. At the absolute worst the word size will be too
-- short.
foreign import ccall unsafe "expat.h XML_GetErrorCode" xmlGetErrorCode
:: ParserPtr -> IO CInt
foreign import ccall unsafe "expat.h XML_GetCurrentLineNumber" xmlGetCurrentLineNumber
:: ParserPtr -> IO CULong
foreign import ccall unsafe "expat.h XML_GetCurrentColumnNumber" xmlGetCurrentColumnNumber
:: ParserPtr -> IO CULong
foreign import ccall unsafe "expat.h XML_GetCurrentByteIndex" xmlGetCurrentByteIndex
:: ParserPtr -> IO CLong
foreign import ccall unsafe "expat.h XML_GetCurrentByteCount" xmlGetCurrentByteCount
:: ParserPtr -> IO CInt
foreign import ccall unsafe "expat.h XML_ErrorString" xmlErrorString
:: CInt -> IO CString
type HParser = B.ByteString -> Bool -> IO (ForeignPtr Word8, CInt, Maybe XMLParseError)
foreign import ccall unsafe "hexpatNewParser"
_hexpatNewParser :: Ptr CChar -> CInt -> IO MyParserPtr
foreign import ccall unsafe "hexpatGetParser"
_hexpatGetParser :: MyParserPtr -> ParserPtr
data MyParser_struct
type MyParserPtr = Ptr MyParser_struct
foreign import ccall "&hexpatFreeParser" hexpatFreeParser :: FunPtr (MyParserPtr -> IO ())
hexpatNewParser :: Maybe Encoding
-> Maybe (B.ByteString -> Maybe B.ByteString) -- ^ Entity decoder
-> Bool -- ^ Whether to include input locations
-> IO (HParser, IO XMLParseLocation)
hexpatNewParser enc mDecoder locations =
withOptEncoding enc $ \cEnc -> do
parser <- newForeignPtr hexpatFreeParser =<< _hexpatNewParser cEnc (cFromBool locations)
return (parse parser, withForeignPtr parser $ \mp -> getParseLocation $ _hexpatGetParser mp)
where
parse parser = case mDecoder of
Nothing -> \text final ->
alloca $ \ppData ->
alloca $ \pLen ->
withBStringLen text $ \(textBuf, textLen) ->
withForeignPtr parser $ \pp -> do
ok <- unStatus <$> _hexpatParseUnsafe pp textBuf textLen (cFromBool final) ppData pLen
pData <- peek ppData
len <- peek pLen
err <- if ok
then return Nothing
else Just <$> getError (_hexpatGetParser pp)
fpData <- newForeignPtr funPtrFree pData
return (fpData, len, err)
Just decoder -> \text final ->
alloca $ \ppData ->
alloca $ \pLen ->
withBStringLen text $ \(textBuf, textLen) ->
withForeignPtr parser $ \pp -> do
eh <- mkCEntityHandler . wrapCEntityHandler $ decoder
_hexpatSetEntityHandler pp eh
ok <- unStatus <$> _hexpatParseSafe pp textBuf textLen (cFromBool final) ppData pLen
freeHaskellFunPtr eh
pData <- peek ppData
len <- peek pLen
err <- if ok
then return Nothing
else Just <$> getError (_hexpatGetParser pp)
fpData <- newForeignPtr funPtrFree pData
return (fpData, len, err)
foreign import ccall unsafe "hexpatParse"
_hexpatParseUnsafe :: MyParserPtr -> Ptr CChar -> CInt -> CInt -> Ptr (Ptr Word8) -> Ptr CInt -> IO CInt
foreign import ccall safe "hexpatParse"
_hexpatParseSafe :: MyParserPtr -> Ptr CChar -> CInt -> CInt -> Ptr (Ptr Word8) -> Ptr CInt -> IO CInt
type CEntityHandler = Ptr CChar -> IO (Ptr CChar)
foreign import ccall safe "wrapper"
mkCEntityHandler :: CEntityHandler
-> IO (FunPtr CEntityHandler)
peekByteStringLen :: CStringLen -> IO B.ByteString
{-# INLINE peekByteStringLen #-}
peekByteStringLen (cstr, len) =
I.create (fromIntegral len) $ \ptr ->
I.memcpy ptr (castPtr cstr) (fromIntegral len)
wrapCEntityHandler :: (B.ByteString -> Maybe B.ByteString) -> CEntityHandler
wrapCEntityHandler handler = h
where
h cname = do
sz <- fromIntegral <$> I.c_strlen cname
name <- peekByteStringLen (cname, sz)
case handler name of
Just text -> do
let (fp, offset, len) = I.toForeignPtr text
withForeignPtr fp $ \ctextBS -> do
ctext <- mallocBytes (len + 1) :: IO CString
I.memcpy (castPtr ctext) (ctextBS `plusPtr` offset) (fromIntegral len)
poke (ctext `plusPtr` len) (0 :: CChar)
return ctext
Nothing -> return nullPtr
foreign import ccall unsafe "hexpatSetEntityHandler"
_hexpatSetEntityHandler :: MyParserPtr -> FunPtr CEntityHandler -> IO ()
foreign import ccall "&free" funPtrFree :: FunPtr (Ptr Word8 -> IO ())
| the-real-blackh/hexpat | Text/XML/Expat/Internal/IO.hs | bsd-3-clause | 8,465 | 0 | 26 | 2,065 | 1,983 | 1,026 | 957 | -1 | -1 |
-- |
-- Maintainer : Ralf Laemmel, Joost Visser
-- Stability : experimental
-- Portability : portable
--
-- This module is part of 'StrategyLib', a library of functional strategy
-- combinators, including combinators for generic traversal. In this module, we
-- define path combinator to constrain selection and transformation of nodes or
-- subtrees by path conditions.
-----------------------------------------------------------------------------}
module PathTheme where
import StrategyPrelude
import OverloadingTheme
import FlowTheme
import TraversalTheme
import Monad
------------------------------------------------------------------------------
-- * Below
-- ** Strictly below
-- | Select or transform a node below a node where a condition holds.
-- We find the top-most node which admits selection or transformation
-- below the top-most node which meets the condition. Thus, the
-- distance between guard and application node is minimized.
belowS :: (MonadPlus m, Strategy s m, StrategyPlus s m)
=> s m -> TU () m -> s m
s `belowS` s' = (oneS s) `beloweqS` s'
-- ** Below or at the same height
-- | Select or transform a node below or at a node where a condition holds.
beloweqS :: (MonadPlus m, Strategy s m, StrategyPlus s m)
=> s m -> TU () m -> s m
s `beloweqS` s' = once_td (ifthenS s' (once_td s))
-- ** Type-specialised versions
-- | Apply a transformation strictly below a node where a condition holds.
belowTP :: MonadPlus m => TP m -> TU () m -> TP m
belowTP = belowS
-- | Apply a transformation below or at a node where a condition holds.
beloweqTP :: MonadPlus m => TP m -> TU () m -> TP m
beloweqTP = beloweqS
------------------------------------------------------------------------------
-- * Above
-- ** Strictly above
-- | Select or transform a node above a node where a condition holds. The
-- distance between guard and application node is minimized.
aboveS :: (MonadPlus m, Strategy s m, StrategyPlus s m)
=> s m -> TU () m -> s m
s `aboveS` s' = s `aboveeqS` (oneTU s')
-- ** Above or at the same height
-- | Select or transform a node above or at a node where a condition holds.
aboveeqS :: (MonadPlus m, Strategy s m, StrategyPlus s m)
=> s m -> TU () m -> s m
s `aboveeqS` s' = once_bu (ifthenS (once_tdTU s') s)
-- ** Type-specialised versions
-- | Apply a transformation strictly above a node where a condition holds.
aboveTP :: MonadPlus m => TP m -> TU () m -> TP m
aboveTP = aboveS
-- | Apply a transformation above or at a node where a condition holds.
aboveeqTP :: MonadPlus m => TP m -> TU () m -> TP m
aboveeqTP = aboveeqS
------------------------------------------------------------------------------
| forste/haReFork | StrategyLib-4.0-beta/library/PathTheme.hs | bsd-3-clause | 2,864 | 2 | 9 | 672 | 520 | 277 | 243 | 26 | 1 |
{-# LANGUAGE CPP #-}
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE Trustworthy #-}
#endif
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses, TypeOperators, FlexibleContexts, FlexibleInstances, UndecidableInstances #-}
-------------------------------------------------------------------------------------------
-- |
-- Module : Control.Category.Cartesian
-- Copyright : 2008-2010 Edward Kmett
-- License : BSD
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : non-portable (class-associated types)
--
-------------------------------------------------------------------------------------------
module Control.Category.Cartesian
(
-- * (Co)Cartesian categories
Cartesian(..)
, bimapProduct, braidProduct, associateProduct, disassociateProduct
, CoCartesian(..)
, bimapSum, braidSum, associateSum, disassociateSum
) where
import Control.Category.Braided
import Control.Category.Monoidal
import Prelude hiding (Functor, map, (.), id, fst, snd, curry, uncurry)
import qualified Prelude (fst,snd)
import Control.Categorical.Bifunctor
import Control.Category
infixr 3 &&&
infixr 2 |||
{- |
Minimum definition:
> fst, snd, diag
> fst, snd, (&&&)
-}
class (Symmetric k (Product k), Monoidal k (Product k)) => Cartesian k where
type Product k :: * -> * -> *
fst :: Product k a b `k` a
snd :: Product k a b `k` b
diag :: a `k` Product k a a
(&&&) :: (a `k` b) -> (a `k` c) -> a `k` Product k b c
diag = id &&& id
f &&& g = bimap f g . diag
{-- RULES
"fst . diag" fst . diag = id
"snd . diag" snd . diag = id
"fst . f &&& g" forall f g. fst . (f &&& g) = f
"snd . f &&& g" forall f g. snd . (f &&& g) = g
--}
instance Cartesian (->) where
type Product (->) = (,)
fst = Prelude.fst
snd = Prelude.snd
diag a = (a,a)
(f &&& g) a = (f a, g a)
-- | free construction of 'Bifunctor' for the product 'Bifunctor' @Product k@ if @(&&&)@ is known
bimapProduct :: Cartesian k => k a c -> k b d -> Product k a b `k` Product k c d
bimapProduct f g = (f . fst) &&& (g . snd)
-- | free construction of 'Braided' for the product 'Bifunctor' @Product k@
braidProduct :: Cartesian k => k (Product k a b) (Product k b a)
braidProduct = snd &&& fst
-- | free construction of 'Associative' for the product 'Bifunctor' @Product k@
associateProduct :: Cartesian k => Product k (Product k a b) c `k` Product k a (Product k b c)
associateProduct = (fst . fst) &&& first snd
-- | free construction of 'Disassociative' for the product 'Bifunctor' @Product k@
disassociateProduct:: Cartesian k => Product k a (Product k b c) `k` Product k (Product k a b) c
disassociateProduct= braid . second braid . associateProduct . first braid . braid
-- * Co-Cartesian categories
-- a category that has finite coproducts, weakened the same way as PreCartesian above was weakened
class (Monoidal k (Sum k), Symmetric k (Sum k)) => CoCartesian k where
type Sum k :: * -> * -> *
inl :: a `k` Sum k a b
inr :: b `k` Sum k a b
codiag :: Sum k a a `k` a
(|||) :: k a c -> k b c -> Sum k a b `k` c
codiag = id ||| id
f ||| g = codiag . bimap f g
{-- RULES
"codiag . inl" codiag . inl = id
"codiag . inr" codiag . inr = id
"(f ||| g) . inl" forall f g. (f ||| g) . inl = f
"(f ||| g) . inr" forall f g. (f ||| g) . inr = g
--}
instance CoCartesian (->) where
type Sum (->) = Either
inl = Left
inr = Right
codiag (Left a) = a
codiag (Right a) = a
(f ||| _) (Left a) = f a
(_ ||| g) (Right a) = g a
-- | free construction of 'Bifunctor' for the coproduct 'Bifunctor' @Sum k@ if @(|||)@ is known
bimapSum :: CoCartesian k => k a c -> k b d -> Sum k a b `k` Sum k c d
bimapSum f g = (inl . f) ||| (inr . g)
-- | free construction of 'Braided' for the coproduct 'Bifunctor' @Sum k@
braidSum :: CoCartesian k => Sum k a b `k` Sum k b a
braidSum = inr ||| inl
-- | free construction of 'Associative' for the coproduct 'Bifunctor' @Sum k@
associateSum :: CoCartesian k => Sum k (Sum k a b) c `k` Sum k a (Sum k b c)
associateSum = braid . first braid . disassociateSum . second braid . braid
-- | free construction of 'Disassociative' for the coproduct 'Bifunctor' @Sum k@
disassociateSum :: CoCartesian k => Sum k a (Sum k b c) `k` Sum k (Sum k a b) c
disassociateSum = (inl . inl) ||| first inr
| ekmett/categories | old/src/Control/Category/Cartesian.hs | bsd-3-clause | 4,380 | 43 | 11 | 967 | 1,199 | 652 | 547 | 62 | 1 |
{-# LANGUAGE RankNTypes #-}
module Prisms where
import Control.Lens hiding (elements)
import Control.Lens.Properties
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
import Ceilometer.Types
import SampleData
suite :: Spec
suite = do
-- Optics for raw payloads aren't required to be proper, since we are
-- ignoring some bits of the serialised format (Word64), depending on
-- the raw payload type.
--
-- They should still satisfy prism identity since that is concerned with
-- the RHS of the prism only, but they don't need to satisfy the "suffcient"
-- law.
-- does what it says it does
describe "CHECK: prism for RAW payload: " $ do
prop "obey the identity prism law" $ prismIdentity prCompoundEvent
prop "obey the identity prism law" $ prismIdentity prCompoundPollster
describe "CHECK: prism for DECODED PAYLOAD FIELD: " $ do
prop "ENDPOINT - is a proper prism" $ isPrism pfEndpoint
prop "VOLUME STATUS - is a proper prism" $ isPrism pfVolumeStatus
prop "VOLUME VERB - is a proper prism" $ isPrism pfVolumeVerb
prop "IMAGE STATUS - is a proper prism" $ isPrism pfImageStatus
prop "IMAGE VERB - is a proper prism" $ isPrism pfImageVerb
prop "SNAPSHOT STATUS - is a proper prism" $ isPrism pfSnapshotStatus
prop "SNAPSHOT VERB - is a proper prism" $ isPrism pfSnapshotVerb
prop "IP STATUS - is a proper prism" $ isPrism pfIPStatus
prop "IP VERB - is a proper prism" $ isPrism pfIPVerb
describe "CHECK: prism for DECODED PAYLOAD: " $ do
prop "VOLUME - is a proper prism" $ isPrism pdVolume
prop "SSD - is a proper prism" $ isPrism pdSSD
prop "CPU - is a proper prism" $ isPrism pdCPU
prop "VCPU - is a proper prism" $ isPrism pdInstanceVCPU
prop "RAM - is a proper prism" $ isPrism pdInstanceRAM
prop "DISK - is a proper prism" $ isPrism pdInstanceDisk
prop "FLAVOR - is a proper prism" $ isPrism $ pdInstanceFlavor testFlavors
prop "IMAGE - is a proper prism" $ isPrism pdImage
prop "SNAPSHOT - is a proper prism" $ isPrism pdSnapshot
prop "IP - is a proper prism" $ isPrism pdIP
-- what it does is what we expect
describe "REFINE: prism:" $ do
it "parses/prints values correct to spec for: VOLUME" $
shouldAllBe (preview pdVolume . view prCompoundEvent) volumePRs volumePDs
it "parses/prints values correct to spec for: SSD" $
shouldAllBe (preview pdSSD . view prCompoundEvent) ssdPRs ssdPDs
it "parses/prints values correct to spec for: INSTANCE FLAVOR" $
shouldAllBe (preview (pdInstanceFlavor testFlavors) . view prCompoundPollster) flavorPRs flavorPDs
it "parses/prints values correct to spec for: IMAGE" $
shouldAllBe (preview pdImage . view prCompoundEvent) imagePRs imagePDs
it "parses/prints values correct to spec for: SNAPSHOT" $
shouldAllBe (preview pdSnapshot . view prCompoundEvent) snapshotPRs snapshotPDs
it "parses/prints values correct to spec for: IP" $
shouldAllBe (preview pdIP . view prCompoundEvent) ipPRs ipPDs
where shouldAllBe f xs ys = map f xs `shouldBe` map Just ys
prismIdentity :: Eq b => Prism' a b -> b -> Property
prismIdentity l b = property $ preview l (review l b) == Just b
| anchor/ceilometer-common | tests/Prisms.hs | bsd-3-clause | 3,383 | 1 | 17 | 846 | 657 | 292 | 365 | 51 | 1 |
-- | Make a 'Stream' of media a segmented stream by using that has content which is an instance of 'CanSegment'.
-- TODO move or merge - after deciding howto proceed with the package structure in general
module Data.MediaBus.Conduit.Segment
( segmentC,
forgetSegmentationC,
)
where
import Conduit (ConduitT, await, awaitForever, evalStateC)
import Control.Lens
( makeLenses,
(.=),
(<<+=),
(<<.=),
(^.),
)
import Control.Monad (when)
import Data.Default (Default)
import Data.MediaBus.Basics.Series (Series (Next, Start))
import Data.MediaBus.Basics.Ticks
( CanBeTicks,
HasDuration (..),
Ticks,
)
import Data.MediaBus.Conduit.Stream
( mapFrameContentC,
yieldNextFrame,
yieldStartFrameCtx,
)
import Data.MediaBus.Media.Segment (CanSegment (..), Segment (..))
import Data.MediaBus.Media.Stream
( Frame (MkFrame),
Stream (MkStream),
frameCtxSeqNumRef,
frameCtxTimestampRef,
frameSeqNum,
frameTimestamp
)
import Data.Time (NominalDiffTime)
data SegmenterState s t c = SegSt
{ _nextSeq :: s,
_timeOffset :: t,
_segRest :: Maybe c
}
mkSegmenterState :: s -> t -> SegmenterState s t c
mkSegmenterState s t = SegSt s t Nothing
makeLenses ''SegmenterState
-- | The packetizer recombines incoming packets into 'Segment's of the given
-- size. Sequence numbers start with the sequence number of the first frame
-- or the last start frame, the same holds for timestamps.
segmentC ::
forall i s r t p c m.
( Num s,
Monad m,
CanSegment c,
Monoid c,
Default i,
HasDuration c,
CanBeTicks r t
) =>
NominalDiffTime ->
ConduitT
(Stream i s (Ticks r t) p c)
(Stream i s (Ticks r t) p (Segment c))
m
()
segmentC segmentDuration =
when (segmentDuration > 0) $
await >>= \case
Nothing -> return ()
Just x -> do
let (seq0, ts0) =
case x of
MkStream (Start xStart) ->
( xStart ^. frameCtxSeqNumRef,
xStart ^. frameCtxTimestampRef
)
MkStream (Next xNext) ->
( xNext ^. frameSeqNum,
xNext ^. frameTimestamp
)
evalStateC (mkSegmenterState seq0 ts0) $ do
go x
awaitForever go
yieldRest
where
go (MkStream (Next (MkFrame _ _ !cIn))) =
yieldLoop cIn
go (MkStream (Start !frmCtx)) = do
yieldRest
let (seq0, ts0) =
( frmCtx ^. frameCtxSeqNumRef,
frmCtx ^. frameCtxTimestampRef
)
nextSeq .= seq0
timeOffset .= ts0
yieldStartFrameCtx frmCtx
yieldLoop !cIn = do
!cRest <- segRest <<.= Nothing
let !c = maybe cIn (<> cIn) cRest
if getDuration c == segmentDuration
then yieldWithAdaptedSeqNumAndTimestamp c
else case splitAfterDuration segmentDuration c of
Just (!packet, !rest) -> do
yieldWithAdaptedSeqNumAndTimestamp packet
yieldLoop rest
Nothing ->
segRest .= Just c
yieldWithAdaptedSeqNumAndTimestamp !p = do
!s <- nextSeq <<+= 1
!t <- timeOffset <<+= getDurationTicks p
yieldNextFrame (MkFrame t s (MkSegment p))
yieldRest = do
!cRest <- segRest <<.= Nothing
mapM_ yieldWithAdaptedSeqNumAndTimestamp cRest
-- | Simply drop the 'Segment' wrap around the 'Frame' content.
forgetSegmentationC :: (Monad m) => ConduitT (Stream i s t p (Segment c)) (Stream i s t p c) m ()
forgetSegmentationC = mapFrameContentC _segmentContent
-- | Yield each 'Segment' like 'forgetSegmentationC' followed by a 'Start' value if the segment is
-- not the last segment.
--
| lindenbaum/mediabus | src/Data/MediaBus/Conduit/Segment.hs | bsd-3-clause | 3,700 | 0 | 19 | 1,049 | 962 | 514 | 448 | -1 | -1 |
{-
(c) The AQUA Project, Glasgow University, 1993-1998
\section[SimplMonad]{The simplifier Monad}
-}
{-# LANGUAGE DeriveFunctor #-}
module SimplMonad (
-- The monad
SimplM,
initSmpl, traceSmpl,
getSimplRules, getFamEnvs,
-- Unique supply
MonadUnique(..), newId, newJoinId,
-- Counting
SimplCount, tick, freeTick, checkedTick,
getSimplCount, zeroSimplCount, pprSimplCount,
plusSimplCount, isZeroSimplCount
) where
import GhcPrelude
import Var ( Var, isId, mkLocalVar )
import Name ( mkSystemVarName )
import Id ( Id, mkSysLocalOrCoVar )
import IdInfo ( IdDetails(..), vanillaIdInfo, setArityInfo )
import Type ( Type, mkLamTypes )
import FamInstEnv ( FamInstEnv )
import CoreSyn ( RuleEnv(..) )
import UniqSupply
import DynFlags
import CoreMonad
import Outputable
import FastString
import MonadUtils
import ErrUtils as Err
import Util ( count )
import Panic (throwGhcExceptionIO, GhcException (..))
import BasicTypes ( IntWithInf, treatZeroAsInf, mkIntWithInf )
import Control.Monad ( ap )
{-
************************************************************************
* *
\subsection{Monad plumbing}
* *
************************************************************************
For the simplifier monad, we want to {\em thread} a unique supply and a counter.
(Command-line switches move around through the explicitly-passed SimplEnv.)
-}
newtype SimplM result
= SM { unSM :: SimplTopEnv -- Envt that does not change much
-> UniqSupply -- We thread the unique supply because
-- constantly splitting it is rather expensive
-> SimplCount
-> IO (result, UniqSupply, SimplCount)}
-- we only need IO here for dump output
deriving (Functor)
data SimplTopEnv
= STE { st_flags :: DynFlags
, st_max_ticks :: IntWithInf -- Max #ticks in this simplifier run
, st_rules :: RuleEnv
, st_fams :: (FamInstEnv, FamInstEnv) }
initSmpl :: DynFlags -> RuleEnv -> (FamInstEnv, FamInstEnv)
-> UniqSupply -- No init count; set to 0
-> Int -- Size of the bindings, used to limit
-- the number of ticks we allow
-> SimplM a
-> IO (a, SimplCount)
initSmpl dflags rules fam_envs us size m
= do (result, _, count) <- unSM m env us (zeroSimplCount dflags)
return (result, count)
where
env = STE { st_flags = dflags, st_rules = rules
, st_max_ticks = computeMaxTicks dflags size
, st_fams = fam_envs }
computeMaxTicks :: DynFlags -> Int -> IntWithInf
-- Compute the max simplifier ticks as
-- (base-size + pgm-size) * magic-multiplier * tick-factor/100
-- where
-- magic-multiplier is a constant that gives reasonable results
-- base-size is a constant to deal with size-zero programs
computeMaxTicks dflags size
= treatZeroAsInf $
fromInteger ((toInteger (size + base_size)
* toInteger (tick_factor * magic_multiplier))
`div` 100)
where
tick_factor = simplTickFactor dflags
base_size = 100
magic_multiplier = 40
-- MAGIC NUMBER, multiplies the simplTickFactor
-- We can afford to be generous; this is really
-- just checking for loops, and shouldn't usually fire
-- A figure of 20 was too small: see #5539.
{-# INLINE thenSmpl #-}
{-# INLINE thenSmpl_ #-}
{-# INLINE returnSmpl #-}
instance Applicative SimplM where
pure = returnSmpl
(<*>) = ap
(*>) = thenSmpl_
instance Monad SimplM where
(>>) = (*>)
(>>=) = thenSmpl
returnSmpl :: a -> SimplM a
returnSmpl e = SM (\_st_env us sc -> return (e, us, sc))
thenSmpl :: SimplM a -> (a -> SimplM b) -> SimplM b
thenSmpl_ :: SimplM a -> SimplM b -> SimplM b
thenSmpl m k
= SM $ \st_env us0 sc0 -> do
(m_result, us1, sc1) <- unSM m st_env us0 sc0
unSM (k m_result) st_env us1 sc1
thenSmpl_ m k
= SM $ \st_env us0 sc0 -> do
(_, us1, sc1) <- unSM m st_env us0 sc0
unSM k st_env us1 sc1
-- TODO: this specializing is not allowed
-- {-# SPECIALIZE mapM :: (a -> SimplM b) -> [a] -> SimplM [b] #-}
-- {-# SPECIALIZE mapAndUnzipM :: (a -> SimplM (b, c)) -> [a] -> SimplM ([b],[c]) #-}
-- {-# SPECIALIZE mapAccumLM :: (acc -> b -> SimplM (acc,c)) -> acc -> [b] -> SimplM (acc, [c]) #-}
traceSmpl :: String -> SDoc -> SimplM ()
traceSmpl herald doc
= do { dflags <- getDynFlags
; liftIO $ Err.dumpIfSet_dyn dflags Opt_D_dump_simpl_trace "Simpl Trace"
FormatText
(hang (text herald) 2 doc) }
{-
************************************************************************
* *
\subsection{The unique supply}
* *
************************************************************************
-}
instance MonadUnique SimplM where
getUniqueSupplyM
= SM (\_st_env us sc -> case splitUniqSupply us of
(us1, us2) -> return (us1, us2, sc))
getUniqueM
= SM (\_st_env us sc -> case takeUniqFromSupply us of
(u, us') -> return (u, us', sc))
getUniquesM
= SM (\_st_env us sc -> case splitUniqSupply us of
(us1, us2) -> return (uniqsFromSupply us1, us2, sc))
instance HasDynFlags SimplM where
getDynFlags = SM (\st_env us sc -> return (st_flags st_env, us, sc))
instance MonadIO SimplM where
liftIO m = SM $ \_ us sc -> do
x <- m
return (x, us, sc)
getSimplRules :: SimplM RuleEnv
getSimplRules = SM (\st_env us sc -> return (st_rules st_env, us, sc))
getFamEnvs :: SimplM (FamInstEnv, FamInstEnv)
getFamEnvs = SM (\st_env us sc -> return (st_fams st_env, us, sc))
newId :: FastString -> Type -> SimplM Id
newId fs ty = do uniq <- getUniqueM
return (mkSysLocalOrCoVar fs uniq ty)
newJoinId :: [Var] -> Type -> SimplM Id
newJoinId bndrs body_ty
= do { uniq <- getUniqueM
; let name = mkSystemVarName uniq (fsLit "$j")
join_id_ty = mkLamTypes bndrs body_ty -- Note [Funky mkLamTypes]
arity = count isId bndrs
-- arity: See Note [Invariants on join points] invariant 2b, in CoreSyn
join_arity = length bndrs
details = JoinId join_arity
id_info = vanillaIdInfo `setArityInfo` arity
-- `setOccInfo` strongLoopBreaker
; return (mkLocalVar details name join_id_ty id_info) }
{-
************************************************************************
* *
\subsection{Counting up what we've done}
* *
************************************************************************
-}
getSimplCount :: SimplM SimplCount
getSimplCount = SM (\_st_env us sc -> return (sc, us, sc))
tick :: Tick -> SimplM ()
tick t = SM (\st_env us sc -> let sc' = doSimplTick (st_flags st_env) t sc
in sc' `seq` return ((), us, sc'))
checkedTick :: Tick -> SimplM ()
-- Try to take a tick, but fail if too many
checkedTick t
= SM (\st_env us sc ->
if st_max_ticks st_env <= mkIntWithInf (simplCountN sc)
then throwGhcExceptionIO $
PprProgramError "Simplifier ticks exhausted" (msg sc)
else let sc' = doSimplTick (st_flags st_env) t sc
in sc' `seq` return ((), us, sc'))
where
msg sc = vcat
[ text "When trying" <+> ppr t
, text "To increase the limit, use -fsimpl-tick-factor=N (default 100)."
, space
, text "If you need to increase the limit substantially, please file a"
, text "bug report and indicate the factor you needed."
, space
, text "If GHC was unable to complete compilation even"
<+> text "with a very large factor"
, text "(a thousand or more), please consult the"
<+> doubleQuotes (text "Known bugs or infelicities")
, text "section in the Users Guide before filing a report. There are a"
, text "few situations unlikely to occur in practical programs for which"
, text "simplifier non-termination has been judged acceptable."
, space
, pp_details sc
, pprSimplCount sc ]
pp_details sc
| hasDetailedCounts sc = empty
| otherwise = text "To see detailed counts use -ddump-simpl-stats"
freeTick :: Tick -> SimplM ()
-- Record a tick, but don't add to the total tick count, which is
-- used to decide when nothing further has happened
freeTick t
= SM (\_st_env us sc -> let sc' = doFreeSimplTick t sc
in sc' `seq` return ((), us, sc'))
| sdiehl/ghc | compiler/simplCore/SimplMonad.hs | bsd-3-clause | 9,198 | 0 | 15 | 2,895 | 1,901 | 1,046 | 855 | 157 | 2 |
module Main where
import Data.Array.MArray
import Data.Array.Storable
import Foreign.Ptr
import Graphics.UI.GLFW as GLFW
import Graphics.Rendering.OpenGL.GL as GL
import LOGL.Application
vertices = [-0.5, -0.5, 0.0,
0.5, -0.5, 0.0,
0.0, 0.5, 0.0]
-- Shaders
vertexShaderSource = "#version 330 core\n"
++ "layout (location = 0) in vec3 position;\n"
++ "void main()\n"
++ "{\n"
++ "gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
++ "}\n"
fragmentShaderSource = "#version 330 core\n"
++ "out vec4 color;\n"
++ "void main()\n"
++ "{\n"
++ "color = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
++ "}\n"
main :: IO ()
main = do
GLFW.init
w <- createAppWindow 800 600 "LearnOpenGL"
prg <- createShaderProgram
(vao, vbo) <- createVAO 9 vertices
runAppLoop w $ do
pollEvents
clearColor $= Color4 0.2 0.3 0.3 1.0
clear [ColorBuffer]
-- Draw our first triangle
currentProgram $= Just prg
bindVertexArrayObject $= Just vao
drawArrays Triangles 0 3
bindVertexArrayObject $= Nothing
swap w
deleteObjectName vao
deleteObjectName vbo
terminate
createShaderProgram :: IO Program
createShaderProgram = do
vShader <- createShader VertexShader
shaderSourceBS vShader $= packUtf8 vertexShaderSource
compileShader vShader
vsuccess <- get $ compileStatus vShader
print vsuccess
vlog <- get $ shaderInfoLog vShader
print vlog
fShader <- createShader FragmentShader
shaderSourceBS fShader $= packUtf8 fragmentShaderSource
compileShader fShader
fsuccess <- get $ compileStatus fShader
print fsuccess
flog <- get $ shaderInfoLog fShader
print flog
prg <- createProgram
attachShader prg vShader
attachShader prg fShader
linkProgram prg
return prg
createVAO :: Int -> [GLfloat] -> IO (VertexArrayObject, BufferObject)
createVAO size elems = do
vao <- genObjectName
bindVertexArrayObject $= Just vao
vbo <-createVBO size elems
vertexAttribPointer (AttribLocation 0) $= (ToFloat, VertexArrayDescriptor 3 Float (3*4) nullPtr)
vertexAttribArray (AttribLocation 0) $= Enabled
bindBuffer ArrayBuffer $= Nothing
bindVertexArrayObject $= Nothing
return (vao, vbo)
createVBO :: Int -> [GLfloat] -> IO BufferObject
createVBO size elems = do
let ptrsize = toEnum $ size * 4
vbo <- genObjectName
bindBuffer ArrayBuffer $= Just vbo
arr <- newListArray (0, size - 1) elems
withStorableArray arr $ \ptr -> bufferData ArrayBuffer $= (ptrsize, ptr, StaticDraw)
return vbo
| atwupack/LearnOpenGL | app/1_Getting-started/2_Hello-triangle/Hello-triangle.hs | bsd-3-clause | 2,626 | 0 | 11 | 615 | 746 | 352 | 394 | 79 | 1 |
{-# LANGUAGE DataKinds #-}
module Main where
import Protolude
import Network.Wai.Test
import GraphQL.API
import GraphQL.Wai
import GraphQL.Resolver
type Cat = Object "Cat" '[] '[Field "name" Text]
catHandler :: Handler IO Cat
catHandler = pure (pure "Felix")
test1 :: Session ()
test1 = do
r <- request $ setPath defaultRequest "/?query={ name }"
assertStatus 200 r
assertBody "{\"data\":{\"name\":\"Felix\"}}" r
main :: IO ()
main = do
void $ runSession test1 (toApplication @Cat catHandler)
| jml/graphql-api | graphql-wai/tests/Tests.hs | bsd-3-clause | 507 | 0 | 11 | 86 | 164 | 84 | 80 | -1 | -1 |
-- | This module defines `WindowHandler`, a source of GLFW Events that are
-- received through a particular `GLFW.Window`. It is not necessary to
-- import this module unless you need to register callbacks outside of
-- reactive-banana.
--
-- This module should usually be imported qualified because it exports
-- names that conflict with the rest of the library.
module Reactive.Banana.GLFW.WindowHandler
(
module Reactive.Banana.GLFW.Types,
-- * WindowHandlers
WindowHandler(..),
windowHandler,
)
where
import Graphics.UI.GLFW as GLFW
import Reactive.Banana hiding ( Identity )
import Reactive.Banana.Frameworks
import Reactive.Banana.GLFW.Types
import Control.Event.Handler
data WindowHandler = WindowHandler
{ window :: GLFW.Window
, refresh :: AddHandler ()
, close :: AddHandler ()
, focus :: AddHandler Bool
, iconify :: AddHandler Bool
, move :: AddHandler (Int, Int)
, resize :: AddHandler (Int, Int)
, char :: AddHandler Char
, keyEvent :: AddHandler KeyEvent
, mouseEvent :: AddHandler MouseEvent
, cursorMove :: AddHandler (Double, Double)
, cursorEnter :: AddHandler Bool
, scroll :: AddHandler (Double, Double)
}
-- | Obtain a `WindowHandler` for a `GLFW.Window`.
--
-- This will register every GLFW callback for this window. When you create
-- a WindowHandler for a Window, you invalidate every WindowHandler that
-- was previously created for that Window.
--
windowHandler :: GLFW.Window -> IO WindowHandler
windowHandler w = WindowHandler w
<$> hc1 (GLFW.setWindowRefreshCallback w)
<*> hc1 (GLFW.setWindowCloseCallback w)
<*> (fmap (== FocusState'Focused)
<$> hc2 (GLFW.setWindowFocusCallback w))
<*> (fmap (== IconifyState'Iconified)
<$> hc2 (GLFW.setWindowIconifyCallback w))
<*> hc3 (GLFW.setWindowPosCallback w)
<*> hc3 (GLFW.setWindowSizeCallback w)
<*> hc2 (GLFW.setCharCallback w)
<*> handleCallback (\f _ k i s m -> f $ ButtonEvent (k, SC i) s (listModKeys m))
(GLFW.setKeyCallback w)
<*> handleCallback (\f _ mb s m -> f $ ButtonEvent mb s (listModKeys m))
(GLFW.setMouseButtonCallback w)
<*> hc3 (GLFW.setCursorPosCallback w)
<*> (fmap (== CursorState'InWindow)
<$> hc2 (GLFW.setCursorEnterCallback w))
<*> hc3 (GLFW.setScrollCallback w)
where
hc1 = handleCallback $ \fire _ -> fire ()
hc2 = handleCallback $ \fire _ a -> fire a
hc3 = handleCallback $ \fire _ a b -> fire (a, b)
listModKeys :: ModifierKeys -> [ModKey]
listModKeys (ModifierKeys sh c a s) = map snd $ filter fst
[ (sh, Shift)
, (c, Ctrl)
, (a, Alt)
, (s, Super)
]
-- | Create an `AddHandler'` for a callback in the shape provided by GLFW-b
handleCallback
:: ((a -> IO ()) -> cb)
-> (Maybe cb -> IO ())
-> IO (AddHandler a)
handleCallback f cb = do
(ah, fire) <- newAddHandler
liftIO $ cb $ Just $ f fire
return ah
| cdxr/reactive-banana-glfw | Reactive/Banana/GLFW/WindowHandler.hs | bsd-3-clause | 3,004 | 0 | 20 | 711 | 819 | 447 | 372 | 60 | 1 |
module Main (main) where
-- This examples contains a simple Characteristic which only allows encrypted
-- authenticated reads. If the device pairing was not authenticated and
-- encrypted, the characteristic cannot be read. The default bluetooth agent
-- can handle PIN authentication. Check that the relevant device is setup to
-- use encryption and authentication:
--
-- hciconfig <dev> -- e.g hciconfig hci0
--
-- Or change it with e.g.:
--
-- hciconfig <dev> auth
--
import Bluetooth
import Control.Concurrent (threadDelay)
main :: IO ()
main = do
conn <- connect
x <- runBluetoothM (registerAndAdvertiseApplication app) conn
case x of
Right _ -> putStrLn "Started BLE auth application!"
Left e -> error $ "Error starting application " ++ show e
threadDelay maxBound
app :: Application
app
= "/com/turingjump/example/auth"
& services .~ [auth]
auth :: Service 'Local
auth
= "18b2e7ec-2706-429e-a021-ab5e8158477b"
& characteristics .~ [secret]
secret :: CharacteristicBS 'Local
secret
= "5bf24762-d9d1-445f-b81d-87069cc35e36"
& readValue ?~ encodeRead (return ("Juke/19" :: String))
& properties .~ [CPEncryptAuthenticatedRead]
| plow-technologies/ble | examples/Auth.hs | bsd-3-clause | 1,182 | 0 | 11 | 213 | 215 | 116 | 99 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
import qualified System.EtCetera.CollectdSpec as CollectdSpec
import qualified System.EtCetera.InternalSpec as InternalSpec
import qualified System.EtCetera.InterfacesSpec as InterfacesSpec
import qualified System.EtCetera.LxcSpec as LxcSpec
import qualified System.EtCetera.RedisSpec as RedisSpec
import Test.Hspec (hspec)
main :: IO ()
main = hspec $ do
InternalSpec.suite
RedisSpec.suite
LxcSpec.suite
InterfacesSpec.suite
CollectdSpec.suite
| paluh/et-cetera | test/Spec.hs | bsd-3-clause | 502 | 0 | 8 | 68 | 101 | 62 | 39 | 14 | 1 |
{-# LANGUAGE BangPatterns, CPP, NondecreasingIndentation, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
-- NB: we specifically ignore deprecations. GHC 7.6 marks the .QSem module as
-- deprecated, although it became un-deprecated later. As a result, using 7.6
-- as your bootstrap compiler throws annoying warnings.
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2011
--
-- This module implements multi-module compilation, and is used
-- by --make and GHCi.
--
-- -----------------------------------------------------------------------------
module GhcMake(
depanal,
load, LoadHowMuch(..),
topSortModuleGraph,
ms_home_srcimps, ms_home_imps,
noModError, cyclicModuleErr
) where
#include "HsVersions.h"
#ifdef GHCI
import qualified Linker ( unload )
#endif
import DriverPhases
import DriverPipeline
import DynFlags
import ErrUtils
import Finder
import GhcMonad
import HeaderInfo
import HscTypes
import Module
import TcIface ( typecheckIface )
import TcRnMonad ( initIfaceCheck )
import Bag ( listToBag )
import BasicTypes
import Digraph
import Exception ( tryIO, gbracket, gfinally )
import FastString
import Maybes ( expectJust )
import Name
import MonadUtils ( allM, MonadIO )
import Outputable
import Panic
import SrcLoc
import StringBuffer
import SysTools
import UniqFM
import Util
import qualified GHC.LanguageExtensions as LangExt
import Data.Either ( rights, partitionEithers )
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import qualified FiniteMap as Map ( insertListWith )
import Control.Concurrent ( forkIOWithUnmask, killThread )
import qualified GHC.Conc as CC
import Control.Concurrent.MVar
import Control.Concurrent.QSem
import Control.Exception
import Control.Monad
import Data.IORef
import Data.List
import qualified Data.List as List
import Data.Maybe
import Data.Ord ( comparing )
import Data.Time
import System.Directory
import System.FilePath
import System.IO ( fixIO )
import System.IO.Error ( isDoesNotExistError )
import GHC.Conc ( getNumProcessors, getNumCapabilities, setNumCapabilities )
label_self :: String -> IO ()
label_self thread_name = do
self_tid <- CC.myThreadId
CC.labelThread self_tid thread_name
-- -----------------------------------------------------------------------------
-- Loading the program
-- | Perform a dependency analysis starting from the current targets
-- and update the session with the new module graph.
--
-- Dependency analysis entails parsing the @import@ directives and may
-- therefore require running certain preprocessors.
--
-- Note that each 'ModSummary' in the module graph caches its 'DynFlags'.
-- These 'DynFlags' are determined by the /current/ session 'DynFlags' and the
-- @OPTIONS@ and @LANGUAGE@ pragmas of the parsed module. Thus if you want
-- changes to the 'DynFlags' to take effect you need to call this function
-- again.
--
depanal :: GhcMonad m =>
[ModuleName] -- ^ excluded modules
-> Bool -- ^ allow duplicate roots
-> m ModuleGraph
depanal excluded_mods allow_dup_roots = do
hsc_env <- getSession
let
dflags = hsc_dflags hsc_env
targets = hsc_targets hsc_env
old_graph = hsc_mod_graph hsc_env
withTiming (pure dflags) (text "Chasing dependencies") (const ()) $ do
liftIO $ debugTraceMsg dflags 2 (hcat [
text "Chasing modules from: ",
hcat (punctuate comma (map pprTarget targets))])
mod_graphE <- liftIO $ downsweep hsc_env old_graph
excluded_mods allow_dup_roots
mod_graph <- reportImportErrors mod_graphE
setSession hsc_env { hsc_mod_graph = mod_graph }
return mod_graph
-- | Describes which modules of the module graph need to be loaded.
data LoadHowMuch
= LoadAllTargets
-- ^ Load all targets and its dependencies.
| LoadUpTo ModuleName
-- ^ Load only the given module and its dependencies.
| LoadDependenciesOf ModuleName
-- ^ Load only the dependencies of the given module, but not the module
-- itself.
-- | Try to load the program. See 'LoadHowMuch' for the different modes.
--
-- This function implements the core of GHC's @--make@ mode. It preprocesses,
-- compiles and loads the specified modules, avoiding re-compilation wherever
-- possible. Depending on the target (see 'DynFlags.hscTarget') compiling
-- and loading may result in files being created on disk.
--
-- Calls the 'defaultWarnErrLogger' after each compiling each module, whether
-- successful or not.
--
-- Throw a 'SourceError' if errors are encountered before the actual
-- compilation starts (e.g., during dependency analysis). All other errors
-- are reported using the 'defaultWarnErrLogger'.
--
load :: GhcMonad m => LoadHowMuch -> m SuccessFlag
load how_much = do
mod_graph <- depanal [] False
guessOutputFile
hsc_env <- getSession
let hpt1 = hsc_HPT hsc_env
let dflags = hsc_dflags hsc_env
-- The "bad" boot modules are the ones for which we have
-- B.hs-boot in the module graph, but no B.hs
-- The downsweep should have ensured this does not happen
-- (see msDeps)
let all_home_mods = [ms_mod_name s
| s <- mod_graph, not (isBootSummary s)]
-- TODO: Figure out what the correct form of this assert is. It's violated
-- when you have HsBootMerge nodes in the graph: then you'll have hs-boot
-- files without corresponding hs files.
-- bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
-- not (ms_mod_name s `elem` all_home_mods)]
-- ASSERT( null bad_boot_mods ) return ()
-- check that the module given in HowMuch actually exists, otherwise
-- topSortModuleGraph will bomb later.
let checkHowMuch (LoadUpTo m) = checkMod m
checkHowMuch (LoadDependenciesOf m) = checkMod m
checkHowMuch _ = id
checkMod m and_then
| m `elem` all_home_mods = and_then
| otherwise = do
liftIO $ errorMsg dflags (text "no such module:" <+>
quotes (ppr m))
return Failed
checkHowMuch how_much $ do
-- mg2_with_srcimps drops the hi-boot nodes, returning a
-- graph with cycles. Among other things, it is used for
-- backing out partially complete cycles following a failed
-- upsweep, and for removing from hpt all the modules
-- not in strict downwards closure, during calls to compile.
let mg2_with_srcimps :: [SCC ModSummary]
mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
-- If we can determine that any of the {-# SOURCE #-} imports
-- are definitely unnecessary, then emit a warning.
warnUnnecessarySourceImports mg2_with_srcimps
let
-- check the stability property for each module.
stable_mods@(stable_obj,stable_bco)
= checkStability hpt1 mg2_with_srcimps all_home_mods
-- prune bits of the HPT which are definitely redundant now,
-- to save space.
pruned_hpt = pruneHomePackageTable hpt1
(flattenSCCs mg2_with_srcimps)
stable_mods
_ <- liftIO $ evaluate pruned_hpt
-- before we unload anything, make sure we don't leave an old
-- interactive context around pointing to dead bindings. Also,
-- write the pruned HPT to allow the old HPT to be GC'd.
setSession $ discardIC $ hsc_env { hsc_HPT = pruned_hpt }
liftIO $ debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
text "Stable BCO:" <+> ppr stable_bco)
-- Unload any modules which are going to be re-linked this time around.
let stable_linkables = [ linkable
| m <- stable_obj++stable_bco,
Just hmi <- [lookupUFM pruned_hpt m],
Just linkable <- [hm_linkable hmi] ]
liftIO $ unload hsc_env stable_linkables
-- We could at this point detect cycles which aren't broken by
-- a source-import, and complain immediately, but it seems better
-- to let upsweep_mods do this, so at least some useful work gets
-- done before the upsweep is abandoned.
--hPutStrLn stderr "after tsort:\n"
--hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
-- Now do the upsweep, calling compile for each module in
-- turn. Final result is version 3 of everything.
-- Topologically sort the module graph, this time including hi-boot
-- nodes, and possibly just including the portion of the graph
-- reachable from the module specified in the 2nd argument to load.
-- This graph should be cycle-free.
-- If we're restricting the upsweep to a portion of the graph, we
-- also want to retain everything that is still stable.
let full_mg :: [SCC ModSummary]
full_mg = topSortModuleGraph False mod_graph Nothing
maybe_top_mod = case how_much of
LoadUpTo m -> Just m
LoadDependenciesOf m -> Just m
_ -> Nothing
partial_mg0 :: [SCC ModSummary]
partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
-- LoadDependenciesOf m: we want the upsweep to stop just
-- short of the specified module (unless the specified module
-- is stable).
partial_mg
| LoadDependenciesOf _mod <- how_much
= ASSERT( case last partial_mg0 of
AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
List.init partial_mg0
| otherwise
= partial_mg0
stable_mg =
[ AcyclicSCC ms
| AcyclicSCC ms <- full_mg,
ms_mod_name ms `elem` stable_obj++stable_bco ]
-- the modules from partial_mg that are not also stable
-- NB. also keep cycles, we need to emit an error message later
unstable_mg = filter not_stable partial_mg
where not_stable (CyclicSCC _) = True
not_stable (AcyclicSCC ms)
= ms_mod_name ms `notElem` stable_obj++stable_bco
-- Load all the stable modules first, before attempting to load
-- an unstable module (#7231).
mg = stable_mg ++ unstable_mg
-- clean up between compilations
let cleanup hsc_env = intermediateCleanTempFiles (hsc_dflags hsc_env)
(flattenSCCs mg2_with_srcimps)
hsc_env
liftIO $ debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
2 (ppr mg))
n_jobs <- case parMakeCount dflags of
Nothing -> liftIO getNumProcessors
Just n -> return n
let upsweep_fn | n_jobs > 1 = parUpsweep n_jobs
| otherwise = upsweep
setSession hsc_env{ hsc_HPT = emptyHomePackageTable }
(upsweep_ok, modsUpswept)
<- upsweep_fn pruned_hpt stable_mods cleanup mg
-- Make modsDone be the summaries for each home module now
-- available; this should equal the domain of hpt3.
-- Get in in a roughly top .. bottom order (hence reverse).
let modsDone = reverse modsUpswept
-- Try and do linking in some form, depending on whether the
-- upsweep was completely or only partially successful.
if succeeded upsweep_ok
then
-- Easy; just relink it all.
do liftIO $ debugTraceMsg dflags 2 (text "Upsweep completely successful.")
-- Clean up after ourselves
hsc_env1 <- getSession
liftIO $ intermediateCleanTempFiles dflags modsDone hsc_env1
-- Issue a warning for the confusing case where the user
-- said '-o foo' but we're not going to do any linking.
-- We attempt linking if either (a) one of the modules is
-- called Main, or (b) the user said -no-hs-main, indicating
-- that main() is going to come from somewhere else.
--
let ofile = outputFile dflags
let no_hs_main = gopt Opt_NoHsMain dflags
let
main_mod = mainModIs dflags
a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
do_linking = a_root_is_Main || no_hs_main || ghcLink dflags == LinkDynLib || ghcLink dflags == LinkStaticLib
-- link everything together
linkresult <- liftIO $ link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
if ghcLink dflags == LinkBinary && isJust ofile && not do_linking
then do
liftIO $ errorMsg dflags $ text
("output was redirected with -o, " ++
"but no output will be generated\n" ++
"because there is no " ++
moduleNameString (moduleName main_mod) ++ " module.")
-- This should be an error, not a warning (#10895).
loadFinish Failed linkresult
else
loadFinish Succeeded linkresult
else
-- Tricky. We need to back out the effects of compiling any
-- half-done cycles, both so as to clean up the top level envs
-- and to avoid telling the interactive linker to link them.
do liftIO $ debugTraceMsg dflags 2 (text "Upsweep partially successful.")
let modsDone_names
= map ms_mod modsDone
let mods_to_zap_names
= findPartiallyCompletedCycles modsDone_names
mg2_with_srcimps
let mods_to_keep
= filter ((`notElem` mods_to_zap_names).ms_mod)
modsDone
hsc_env1 <- getSession
let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
(hsc_HPT hsc_env1)
-- Clean up after ourselves
liftIO $ intermediateCleanTempFiles dflags mods_to_keep hsc_env1
-- there should be no Nothings where linkables should be, now
let just_linkables =
isNoLink (ghcLink dflags)
|| all (isJust.hm_linkable)
(filter ((== HsSrcFile).mi_hsc_src.hm_iface)
(eltsUFM hpt4))
ASSERT( just_linkables ) do
-- Link everything together
linkresult <- liftIO $ link (ghcLink dflags) dflags False hpt4
modifySession $ \hsc_env -> hsc_env{ hsc_HPT = hpt4 }
loadFinish Failed linkresult
-- | Finish up after a load.
loadFinish :: GhcMonad m => SuccessFlag -> SuccessFlag -> m SuccessFlag
-- If the link failed, unload everything and return.
loadFinish _all_ok Failed
= do hsc_env <- getSession
liftIO $ unload hsc_env []
modifySession discardProg
return Failed
-- Empty the interactive context and set the module context to the topmost
-- newly loaded module, or the Prelude if none were loaded.
loadFinish all_ok Succeeded
= do modifySession discardIC
return all_ok
-- | Forget the current program, but retain the persistent info in HscEnv
discardProg :: HscEnv -> HscEnv
discardProg hsc_env
= discardIC $ hsc_env { hsc_mod_graph = emptyMG
, hsc_HPT = emptyHomePackageTable }
-- | Discard the contents of the InteractiveContext, but keep the DynFlags.
-- It will also keep ic_int_print and ic_monad if their names are from
-- external packages.
discardIC :: HscEnv -> HscEnv
discardIC hsc_env
= hsc_env { hsc_IC = empty_ic { ic_int_print = new_ic_int_print
, ic_monad = new_ic_monad } }
where
-- Force the new values for ic_int_print and ic_monad to avoid leaking old_ic
!new_ic_int_print = keep_external_name ic_int_print
!new_ic_monad = keep_external_name ic_monad
dflags = ic_dflags old_ic
old_ic = hsc_IC hsc_env
empty_ic = emptyInteractiveContext dflags
keep_external_name ic_name
| nameIsFromExternalPackage this_pkg old_name = old_name
| otherwise = ic_name empty_ic
where
this_pkg = thisPackage dflags
old_name = ic_name old_ic
intermediateCleanTempFiles :: DynFlags -> [ModSummary] -> HscEnv -> IO ()
intermediateCleanTempFiles dflags summaries hsc_env
= do notIntermediate <- readIORef (filesToNotIntermediateClean dflags)
cleanTempFilesExcept dflags (notIntermediate ++ except)
where
except =
-- Save preprocessed files. The preprocessed file *might* be
-- the same as the source file, but that doesn't do any
-- harm.
map ms_hspp_file summaries ++
-- Save object files for loaded modules. The point of this
-- is that we might have generated and compiled a stub C
-- file, and in the case of GHCi the object file will be a
-- temporary file which we must not remove because we need
-- to load/link it later.
hptObjs (hsc_HPT hsc_env)
-- | If there is no -o option, guess the name of target executable
-- by using top-level source file name as a base.
guessOutputFile :: GhcMonad m => m ()
guessOutputFile = modifySession $ \env ->
let dflags = hsc_dflags env
-- Force mod_graph to avoid leaking env
!mod_graph = hsc_mod_graph env
mainModuleSrcPath :: Maybe String
mainModuleSrcPath = do
let isMain = (== mainModIs dflags) . ms_mod
[ms] <- return (filter isMain mod_graph)
ml_hs_file (ms_location ms)
name = fmap dropExtension mainModuleSrcPath
name_exe = do
#if defined(mingw32_HOST_OS)
-- we must add the .exe extention unconditionally here, otherwise
-- when name has an extension of its own, the .exe extension will
-- not be added by DriverPipeline.exeFileName. See #2248
name' <- fmap (<.> "exe") name
#else
name' <- name
#endif
mainModuleSrcPath' <- mainModuleSrcPath
-- #9930: don't clobber input files (unless they ask for it)
if name' == mainModuleSrcPath'
then throwGhcException . UsageError $
"default output name would overwrite the input file; " ++
"must specify -o explicitly"
else Just name'
in
case outputFile dflags of
Just _ -> env
Nothing -> env { hsc_dflags = dflags { outputFile = name_exe } }
-- -----------------------------------------------------------------------------
--
-- | Prune the HomePackageTable
--
-- Before doing an upsweep, we can throw away:
--
-- - For non-stable modules:
-- - all ModDetails, all linked code
-- - all unlinked code that is out of date with respect to
-- the source file
--
-- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
-- space at the end of the upsweep, because the topmost ModDetails of the
-- old HPT holds on to the entire type environment from the previous
-- compilation.
pruneHomePackageTable :: HomePackageTable
-> [ModSummary]
-> ([ModuleName],[ModuleName])
-> HomePackageTable
pruneHomePackageTable hpt summ (stable_obj, stable_bco)
= mapUFM prune hpt
where prune hmi
| is_stable modl = hmi'
| otherwise = hmi'{ hm_details = emptyModDetails }
where
modl = moduleName (mi_module (hm_iface hmi))
hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
= hmi{ hm_linkable = Nothing }
| otherwise
= hmi
where ms = expectJust "prune" (lookupUFM ms_map modl)
ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
is_stable m = m `elem` stable_obj || m `elem` stable_bco
-- -----------------------------------------------------------------------------
--
-- | Return (names of) all those in modsDone who are part of a cycle as defined
-- by theGraph.
findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
findPartiallyCompletedCycles modsDone theGraph
= chew theGraph
where
chew [] = []
chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
chew ((CyclicSCC vs):rest)
= let names_in_this_cycle = nub (map ms_mod vs)
mods_in_this_cycle
= nub ([done | done <- modsDone,
done `elem` names_in_this_cycle])
chewed_rest = chew rest
in
if notNull mods_in_this_cycle
&& length mods_in_this_cycle < length names_in_this_cycle
then mods_in_this_cycle ++ chewed_rest
else chewed_rest
-- ---------------------------------------------------------------------------
--
-- | Unloading
unload :: HscEnv -> [Linkable] -> IO ()
unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
= case ghcLink (hsc_dflags hsc_env) of
#ifdef GHCI
LinkInMemory -> Linker.unload hsc_env stable_linkables
#else
LinkInMemory -> panic "unload: no interpreter"
-- urgh. avoid warnings:
hsc_env stable_linkables
#endif
_other -> return ()
-- -----------------------------------------------------------------------------
{- |
Stability tells us which modules definitely do not need to be recompiled.
There are two main reasons for having stability:
- avoid doing a complete upsweep of the module graph in GHCi when
modules near the bottom of the tree have not changed.
- to tell GHCi when it can load object code: we can only load object code
for a module when we also load object code fo all of the imports of the
module. So we need to know that we will definitely not be recompiling
any of these modules, and we can use the object code.
The stability check is as follows. Both stableObject and
stableBCO are used during the upsweep phase later.
@
stable m = stableObject m || stableBCO m
stableObject m =
all stableObject (imports m)
&& old linkable does not exist, or is == on-disk .o
&& date(on-disk .o) > date(.hs)
stableBCO m =
all stable (imports m)
&& date(BCO) > date(.hs)
@
These properties embody the following ideas:
- if a module is stable, then:
- if it has been compiled in a previous pass (present in HPT)
then it does not need to be compiled or re-linked.
- if it has not been compiled in a previous pass,
then we only need to read its .hi file from disk and
link it to produce a 'ModDetails'.
- if a modules is not stable, we will definitely be at least
re-linking, and possibly re-compiling it during the 'upsweep'.
All non-stable modules can (and should) therefore be unlinked
before the 'upsweep'.
- Note that objects are only considered stable if they only depend
on other objects. We can't link object code against byte code.
-}
checkStability
:: HomePackageTable -- HPT from last compilation
-> [SCC ModSummary] -- current module graph (cyclic)
-> [ModuleName] -- all home modules
-> ([ModuleName], -- stableObject
[ModuleName]) -- stableBCO
checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
where
checkSCC (stable_obj, stable_bco) scc0
| stableObjects = (scc_mods ++ stable_obj, stable_bco)
| stableBCOs = (stable_obj, scc_mods ++ stable_bco)
| otherwise = (stable_obj, stable_bco)
where
scc = flattenSCC scc0
scc_mods = map ms_mod_name scc
home_module m = m `elem` all_home_mods && m `notElem` scc_mods
scc_allimps = nub (filter home_module (concatMap ms_home_allimps scc))
-- all imports outside the current SCC, but in the home pkg
stable_obj_imps = map (`elem` stable_obj) scc_allimps
stable_bco_imps = map (`elem` stable_bco) scc_allimps
stableObjects =
and stable_obj_imps
&& all object_ok scc
stableBCOs =
and (zipWith (||) stable_obj_imps stable_bco_imps)
&& all bco_ok scc
object_ok ms
| gopt Opt_ForceRecomp (ms_hspp_opts ms) = False
| Just t <- ms_obj_date ms = t >= ms_hs_date ms
&& same_as_prev t
| otherwise = False
where
same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
Just hmi | Just l <- hm_linkable hmi
-> isObjectLinkable l && t == linkableTime l
_other -> True
-- why '>=' rather than '>' above? If the filesystem stores
-- times to the nearset second, we may occasionally find that
-- the object & source have the same modification time,
-- especially if the source was automatically generated
-- and compiled. Using >= is slightly unsafe, but it matches
-- make's behaviour.
--
-- But see #5527, where someone ran into this and it caused
-- a problem.
bco_ok ms
| gopt Opt_ForceRecomp (ms_hspp_opts ms) = False
| otherwise = case lookupUFM hpt (ms_mod_name ms) of
Just hmi | Just l <- hm_linkable hmi ->
not (isObjectLinkable l) &&
linkableTime l >= ms_hs_date ms
_other -> False
{- Parallel Upsweep
-
- The parallel upsweep attempts to concurrently compile the modules in the
- compilation graph using multiple Haskell threads.
-
- The Algorithm
-
- A Haskell thread is spawned for each module in the module graph, waiting for
- its direct dependencies to finish building before it itself begins to build.
-
- Each module is associated with an initially empty MVar that stores the
- result of that particular module's compile. If the compile succeeded, then
- the HscEnv (synchronized by an MVar) is updated with the fresh HMI of that
- module, and the module's HMI is deleted from the old HPT (synchronized by an
- IORef) to save space.
-
- Instead of immediately outputting messages to the standard handles, all
- compilation output is deferred to a per-module TQueue. A QSem is used to
- limit the number of workers that are compiling simultaneously.
-
- Meanwhile, the main thread sequentially loops over all the modules in the
- module graph, outputting the messages stored in each module's TQueue.
-}
-- | Each module is given a unique 'LogQueue' to redirect compilation messages
-- to. A 'Nothing' value contains the result of compilation, and denotes the
-- end of the message queue.
data LogQueue = LogQueue !(IORef [Maybe (WarnReason, Severity, SrcSpan, PprStyle, MsgDoc)])
!(MVar ())
-- | The graph of modules to compile and their corresponding result 'MVar' and
-- 'LogQueue'.
type CompilationGraph = [(ModSummary, MVar SuccessFlag, LogQueue)]
-- | Build a 'CompilationGraph' out of a list of strongly-connected modules,
-- also returning the first, if any, encountered module cycle.
buildCompGraph :: [SCC ModSummary] -> IO (CompilationGraph, Maybe [ModSummary])
buildCompGraph [] = return ([], Nothing)
buildCompGraph (scc:sccs) = case scc of
AcyclicSCC ms -> do
mvar <- newEmptyMVar
log_queue <- do
ref <- newIORef []
sem <- newEmptyMVar
return (LogQueue ref sem)
(rest,cycle) <- buildCompGraph sccs
return ((ms,mvar,log_queue):rest, cycle)
CyclicSCC mss -> return ([], Just mss)
-- A Module and whether it is a boot module.
type BuildModule = (Module, IsBoot)
-- | 'Bool' indicating if a module is a boot module or not. We need to treat
-- boot modules specially when building compilation graphs, since they break
-- cycles. Regular source files and signature files are treated equivalently.
data IsBoot = IsBoot | NotBoot
deriving (Ord, Eq, Show, Read)
-- | Tests if an 'HscSource' is a boot file, primarily for constructing
-- elements of 'BuildModule'.
hscSourceToIsBoot :: HscSource -> IsBoot
hscSourceToIsBoot HsBootFile = IsBoot
hscSourceToIsBoot _ = NotBoot
mkBuildModule :: ModSummary -> BuildModule
mkBuildModule ms = (ms_mod ms, if isBootSummary ms then IsBoot else NotBoot)
-- | The entry point to the parallel upsweep.
--
-- See also the simpler, sequential 'upsweep'.
parUpsweep
:: GhcMonad m
=> Int
-- ^ The number of workers we wish to run in parallel
-> HomePackageTable
-> ([ModuleName],[ModuleName])
-> (HscEnv -> IO ())
-> [SCC ModSummary]
-> m (SuccessFlag,
[ModSummary])
parUpsweep n_jobs old_hpt stable_mods cleanup sccs = do
hsc_env <- getSession
let dflags = hsc_dflags hsc_env
-- The bits of shared state we'll be using:
-- The global HscEnv is updated with the module's HMI when a module
-- successfully compiles.
hsc_env_var <- liftIO $ newMVar hsc_env
-- The old HPT is used for recompilation checking in upsweep_mod. When a
-- module successfully gets compiled, its HMI is pruned from the old HPT.
old_hpt_var <- liftIO $ newIORef old_hpt
-- What we use to limit parallelism with.
par_sem <- liftIO $ newQSem n_jobs
let updNumCapabilities = liftIO $ do
n_capabilities <- getNumCapabilities
unless (n_capabilities /= 1) $ setNumCapabilities n_jobs
return n_capabilities
-- Reset the number of capabilities once the upsweep ends.
let resetNumCapabilities orig_n = liftIO $ setNumCapabilities orig_n
gbracket updNumCapabilities resetNumCapabilities $ \_ -> do
-- Sync the global session with the latest HscEnv once the upsweep ends.
let finallySyncSession io = io `gfinally` do
hsc_env <- liftIO $ readMVar hsc_env_var
setSession hsc_env
finallySyncSession $ do
-- Build the compilation graph out of the list of SCCs. Module cycles are
-- handled at the very end, after some useful work gets done. Note that
-- this list is topologically sorted (by virtue of 'sccs' being sorted so).
(comp_graph,cycle) <- liftIO $ buildCompGraph sccs
let comp_graph_w_idx = zip comp_graph [1..]
-- The list of all loops in the compilation graph.
-- NB: For convenience, the last module of each loop (aka the module that
-- finishes the loop) is prepended to the beginning of the loop.
let comp_graph_loops = go (map fstOf3 (reverse comp_graph))
where
go [] = []
go (ms:mss) | Just loop <- getModLoop ms (ms:mss)
= map mkBuildModule (ms:loop) : go mss
| otherwise
= go mss
-- Build a Map out of the compilation graph with which we can efficiently
-- look up the result MVar associated with a particular home module.
let home_mod_map :: Map BuildModule (MVar SuccessFlag, Int)
home_mod_map =
Map.fromList [ (mkBuildModule ms, (mvar, idx))
| ((ms,mvar,_),idx) <- comp_graph_w_idx ]
liftIO $ label_self "main --make thread"
-- For each module in the module graph, spawn a worker thread that will
-- compile this module.
let { spawnWorkers = forM comp_graph_w_idx $ \((mod,!mvar,!log_queue),!mod_idx) ->
forkIOWithUnmask $ \unmask -> do
liftIO $ label_self $ unwords
[ "worker --make thread"
, "for module"
, show (moduleNameString (ms_mod_name mod))
, "number"
, show mod_idx
]
-- Replace the default log_action with one that writes each
-- message to the module's log_queue. The main thread will
-- deal with synchronously printing these messages.
--
-- Use a local filesToClean var so that we can clean up
-- intermediate files in a timely fashion (as soon as
-- compilation for that module is finished) without having to
-- worry about accidentally deleting a simultaneous compile's
-- important files.
lcl_files_to_clean <- newIORef []
let lcl_dflags = dflags { log_action = parLogAction log_queue
, filesToClean = lcl_files_to_clean }
-- Unmask asynchronous exceptions and perform the thread-local
-- work to compile the module (see parUpsweep_one).
m_res <- try $ unmask $ prettyPrintGhcErrors lcl_dflags $
parUpsweep_one mod home_mod_map comp_graph_loops
lcl_dflags cleanup
par_sem hsc_env_var old_hpt_var
stable_mods mod_idx (length sccs)
res <- case m_res of
Right flag -> return flag
Left exc -> do
-- Don't print ThreadKilled exceptions: they are used
-- to kill the worker thread in the event of a user
-- interrupt, and the user doesn't have to be informed
-- about that.
when (fromException exc /= Just ThreadKilled)
(errorMsg lcl_dflags (text (show exc)))
return Failed
-- Populate the result MVar.
putMVar mvar res
-- Write the end marker to the message queue, telling the main
-- thread that it can stop waiting for messages from this
-- particular compile.
writeLogQueue log_queue Nothing
-- Add the remaining files that weren't cleaned up to the
-- global filesToClean ref, for cleanup later.
files_kept <- readIORef (filesToClean lcl_dflags)
addFilesToClean dflags files_kept
-- Kill all the workers, masking interrupts (since killThread is
-- interruptible). XXX: This is not ideal.
; killWorkers = uninterruptibleMask_ . mapM_ killThread }
-- Spawn the workers, making sure to kill them later. Collect the results
-- of each compile.
results <- liftIO $ bracket spawnWorkers killWorkers $ \_ ->
-- Loop over each module in the compilation graph in order, printing
-- each message from its log_queue.
forM comp_graph $ \(mod,mvar,log_queue) -> do
printLogs dflags log_queue
result <- readMVar mvar
if succeeded result then return (Just mod) else return Nothing
-- Collect and return the ModSummaries of all the successful compiles.
-- NB: Reverse this list to maintain output parity with the sequential upsweep.
let ok_results = reverse (catMaybes results)
-- Handle any cycle in the original compilation graph and return the result
-- of the upsweep.
case cycle of
Just mss -> do
liftIO $ fatalErrorMsg dflags (cyclicModuleErr mss)
return (Failed,ok_results)
Nothing -> do
let success_flag = successIf (all isJust results)
return (success_flag,ok_results)
where
writeLogQueue :: LogQueue -> Maybe (WarnReason,Severity,SrcSpan,PprStyle,MsgDoc) -> IO ()
writeLogQueue (LogQueue ref sem) msg = do
atomicModifyIORef' ref $ \msgs -> (msg:msgs,())
_ <- tryPutMVar sem ()
return ()
-- The log_action callback that is used to synchronize messages from a
-- worker thread.
parLogAction :: LogQueue -> LogAction
parLogAction log_queue _dflags !reason !severity !srcSpan !style !msg = do
writeLogQueue log_queue (Just (reason,severity,srcSpan,style,msg))
-- Print each message from the log_queue using the log_action from the
-- session's DynFlags.
printLogs :: DynFlags -> LogQueue -> IO ()
printLogs !dflags (LogQueue ref sem) = read_msgs
where read_msgs = do
takeMVar sem
msgs <- atomicModifyIORef' ref $ \xs -> ([], reverse xs)
print_loop msgs
print_loop [] = read_msgs
print_loop (x:xs) = case x of
Just (reason,severity,srcSpan,style,msg) -> do
log_action dflags dflags reason severity srcSpan style msg
print_loop xs
-- Exit the loop once we encounter the end marker.
Nothing -> return ()
-- The interruptible subset of the worker threads' work.
parUpsweep_one
:: ModSummary
-- ^ The module we wish to compile
-> Map BuildModule (MVar SuccessFlag, Int)
-- ^ The map of home modules and their result MVar
-> [[BuildModule]]
-- ^ The list of all module loops within the compilation graph.
-> DynFlags
-- ^ The thread-local DynFlags
-> (HscEnv -> IO ())
-- ^ The callback for cleaning up intermediate files
-> QSem
-- ^ The semaphore for limiting the number of simultaneous compiles
-> MVar HscEnv
-- ^ The MVar that synchronizes updates to the global HscEnv
-> IORef HomePackageTable
-- ^ The old HPT
-> ([ModuleName],[ModuleName])
-- ^ Lists of stable objects and BCOs
-> Int
-- ^ The index of this module
-> Int
-- ^ The total number of modules
-> IO SuccessFlag
-- ^ The result of this compile
parUpsweep_one mod home_mod_map comp_graph_loops lcl_dflags cleanup par_sem
hsc_env_var old_hpt_var stable_mods mod_index num_mods = do
let this_build_mod = mkBuildModule mod
let home_imps = map unLoc $ ms_home_imps mod
let home_src_imps = map unLoc $ ms_home_srcimps mod
-- All the textual imports of this module.
let textual_deps = Set.fromList $ mapFst (mkModule (thisPackage lcl_dflags)) $
zip home_imps (repeat NotBoot) ++
zip home_src_imps (repeat IsBoot)
-- Dealing with module loops
-- ~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- Not only do we have to deal with explicit textual dependencies, we also
-- have to deal with implicit dependencies introduced by import cycles that
-- are broken by an hs-boot file. We have to ensure that:
--
-- 1. A module that breaks a loop must depend on all the modules in the
-- loop (transitively or otherwise). This is normally always fulfilled
-- by the module's textual dependencies except in degenerate loops,
-- e.g.:
--
-- A.hs imports B.hs-boot
-- B.hs doesn't import A.hs
-- C.hs imports A.hs, B.hs
--
-- In this scenario, getModLoop will detect the module loop [A,B] but
-- the loop finisher B doesn't depend on A. So we have to explicitly add
-- A in as a dependency of B when we are compiling B.
--
-- 2. A module that depends on a module in an external loop can't proceed
-- until the entire loop is re-typechecked.
--
-- These two invariants have to be maintained to correctly build a
-- compilation graph with one or more loops.
-- The loop that this module will finish. After this module successfully
-- compiles, this loop is going to get re-typechecked.
let finish_loop = listToMaybe
[ tail loop | loop <- comp_graph_loops
, head loop == this_build_mod ]
-- If this module finishes a loop then it must depend on all the other
-- modules in that loop because the entire module loop is going to be
-- re-typechecked once this module gets compiled. These extra dependencies
-- are this module's "internal" loop dependencies, because this module is
-- inside the loop in question.
let int_loop_deps = Set.fromList $
case finish_loop of
Nothing -> []
Just loop -> filter (/= this_build_mod) loop
-- If this module depends on a module within a loop then it must wait for
-- that loop to get re-typechecked, i.e. it must wait on the module that
-- finishes that loop. These extra dependencies are this module's
-- "external" loop dependencies, because this module is outside of the
-- loop(s) in question.
let ext_loop_deps = Set.fromList
[ head loop | loop <- comp_graph_loops
, any (`Set.member` textual_deps) loop
, this_build_mod `notElem` loop ]
let all_deps = foldl1 Set.union [textual_deps, int_loop_deps, ext_loop_deps]
-- All of the module's home-module dependencies.
let home_deps_with_idx =
[ home_dep | dep <- Set.toList all_deps
, Just home_dep <- [Map.lookup dep home_mod_map] ]
-- Sort the list of dependencies in reverse-topological order. This way, by
-- the time we get woken up by the result of an earlier dependency,
-- subsequent dependencies are more likely to have finished. This step
-- effectively reduces the number of MVars that each thread blocks on.
let home_deps = map fst $ sortBy (flip (comparing snd)) home_deps_with_idx
-- Wait for the all the module's dependencies to finish building.
deps_ok <- allM (fmap succeeded . readMVar) home_deps
-- We can't build this module if any of its dependencies failed to build.
if not deps_ok
then return Failed
else do
-- Any hsc_env at this point is OK to use since we only really require
-- that the HPT contains the HMIs of our dependencies.
hsc_env <- readMVar hsc_env_var
old_hpt <- readIORef old_hpt_var
let logger err = printBagOfErrors lcl_dflags (srcErrorMessages err)
-- Limit the number of parallel compiles.
let withSem sem = bracket_ (waitQSem sem) (signalQSem sem)
mb_mod_info <- withSem par_sem $
handleSourceError (\err -> do logger err; return Nothing) $ do
-- Have the ModSummary and HscEnv point to our local log_action
-- and filesToClean var.
let lcl_mod = localize_mod mod
let lcl_hsc_env = localize_hsc_env hsc_env
-- Compile the module.
mod_info <- upsweep_mod lcl_hsc_env old_hpt stable_mods lcl_mod
mod_index num_mods
return (Just mod_info)
case mb_mod_info of
Nothing -> return Failed
Just mod_info -> do
let this_mod = ms_mod_name mod
-- Prune the old HPT unless this is an hs-boot module.
unless (isBootSummary mod) $
atomicModifyIORef' old_hpt_var $ \old_hpt ->
(delFromUFM old_hpt this_mod, ())
-- Update and fetch the global HscEnv.
lcl_hsc_env' <- modifyMVar hsc_env_var $ \hsc_env -> do
let hsc_env' = hsc_env { hsc_HPT = addToUFM (hsc_HPT hsc_env)
this_mod mod_info }
-- If this module is a loop finisher, now is the time to
-- re-typecheck the loop.
hsc_env'' <- case finish_loop of
Nothing -> return hsc_env'
Just loop -> typecheckLoop lcl_dflags hsc_env' $
map (moduleName . fst) loop
return (hsc_env'', localize_hsc_env hsc_env'')
-- Clean up any intermediate files.
cleanup lcl_hsc_env'
return Succeeded
where
localize_mod mod
= mod { ms_hspp_opts = (ms_hspp_opts mod)
{ log_action = log_action lcl_dflags
, filesToClean = filesToClean lcl_dflags } }
localize_hsc_env hsc_env
= hsc_env { hsc_dflags = (hsc_dflags hsc_env)
{ log_action = log_action lcl_dflags
, filesToClean = filesToClean lcl_dflags } }
-- -----------------------------------------------------------------------------
--
-- | The upsweep
--
-- This is where we compile each module in the module graph, in a pass
-- from the bottom to the top of the graph.
--
-- There better had not be any cyclic groups here -- we check for them.
upsweep
:: GhcMonad m
=> HomePackageTable -- ^ HPT from last time round (pruned)
-> ([ModuleName],[ModuleName]) -- ^ stable modules (see checkStability)
-> (HscEnv -> IO ()) -- ^ How to clean up unwanted tmp files
-> [SCC ModSummary] -- ^ Mods to do (the worklist)
-> m (SuccessFlag,
[ModSummary])
-- ^ Returns:
--
-- 1. A flag whether the complete upsweep was successful.
-- 2. The 'HscEnv' in the monad has an updated HPT
-- 3. A list of modules which succeeded loading.
upsweep old_hpt stable_mods cleanup sccs = do
(res, done) <- upsweep' old_hpt [] sccs 1 (length sccs)
return (res, reverse done)
where
upsweep' _old_hpt done
[] _ _
= return (Succeeded, done)
upsweep' _old_hpt done
(CyclicSCC ms:_) _ _
= do dflags <- getSessionDynFlags
liftIO $ fatalErrorMsg dflags (cyclicModuleErr ms)
return (Failed, done)
upsweep' old_hpt done
(AcyclicSCC mod:mods) mod_index nmods
= do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
-- show (map (moduleUserString.moduleName.mi_module.hm_iface)
-- (moduleEnvElts (hsc_HPT hsc_env)))
let logger _mod = defaultWarnErrLogger
hsc_env <- getSession
-- Remove unwanted tmp files between compilations
liftIO (cleanup hsc_env)
mb_mod_info
<- handleSourceError
(\err -> do logger mod (Just err); return Nothing) $ do
mod_info <- liftIO $ upsweep_mod hsc_env old_hpt stable_mods
mod mod_index nmods
logger mod Nothing -- log warnings
return (Just mod_info)
case mb_mod_info of
Nothing -> return (Failed, done)
Just mod_info -> do
let this_mod = ms_mod_name mod
-- Add new info to hsc_env
hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
hsc_env1 = hsc_env { hsc_HPT = hpt1 }
-- Space-saving: delete the old HPT entry
-- for mod BUT if mod is a hs-boot
-- node, don't delete it. For the
-- interface, the HPT entry is probaby for the
-- main Haskell source file. Deleting it
-- would force the real module to be recompiled
-- every time.
old_hpt1 | isBootSummary mod = old_hpt
| otherwise = delFromUFM old_hpt this_mod
done' = mod:done
-- fixup our HomePackageTable after we've finished compiling
-- a mutually-recursive loop. See reTypecheckLoop, below.
hsc_env2 <- liftIO $ reTypecheckLoop hsc_env1 mod done'
setSession hsc_env2
upsweep' old_hpt1 done' mods (mod_index+1) nmods
maybeGetIfaceDate :: DynFlags -> ModLocation -> IO (Maybe UTCTime)
maybeGetIfaceDate dflags location
| writeInterfaceOnlyMode dflags
-- Minor optimization: it should be harmless to check the hi file location
-- always, but it's better to avoid hitting the filesystem if possible.
= modificationTimeIfExists (ml_hi_file location)
| otherwise
= return Nothing
-- | Compile a single module. Always produce a Linkable for it if
-- successful. If no compilation happened, return the old Linkable.
upsweep_mod :: HscEnv
-> HomePackageTable
-> ([ModuleName],[ModuleName])
-> ModSummary
-> Int -- index of module
-> Int -- total number of modules
-> IO HomeModInfo
upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
= let
this_mod_name = ms_mod_name summary
this_mod = ms_mod summary
mb_obj_date = ms_obj_date summary
mb_if_date = ms_iface_date summary
obj_fn = ml_obj_file (ms_location summary)
hs_date = ms_hs_date summary
is_stable_obj = this_mod_name `elem` stable_obj
is_stable_bco = this_mod_name `elem` stable_bco
old_hmi = lookupUFM old_hpt this_mod_name
-- We're using the dflags for this module now, obtained by
-- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
dflags = ms_hspp_opts summary
prevailing_target = hscTarget (hsc_dflags hsc_env)
local_target = hscTarget dflags
-- If OPTIONS_GHC contains -fasm or -fllvm, be careful that
-- we don't do anything dodgy: these should only work to change
-- from -fllvm to -fasm and vice-versa, otherwise we could
-- end up trying to link object code to byte code.
target = if prevailing_target /= local_target
&& (not (isObjectTarget prevailing_target)
|| not (isObjectTarget local_target))
then prevailing_target
else local_target
-- store the corrected hscTarget into the summary
summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
-- The old interface is ok if
-- a) we're compiling a source file, and the old HPT
-- entry is for a source file
-- b) we're compiling a hs-boot file
-- Case (b) allows an hs-boot file to get the interface of its
-- real source file on the second iteration of the compilation
-- manager, but that does no harm. Otherwise the hs-boot file
-- will always be recompiled
mb_old_iface
= case old_hmi of
Nothing -> Nothing
Just hm_info | isBootSummary summary -> Just iface
| not (mi_boot iface) -> Just iface
| otherwise -> Nothing
where
iface = hm_iface hm_info
compile_it :: Maybe Linkable -> SourceModified -> IO HomeModInfo
compile_it mb_linkable src_modified =
compileOne hsc_env summary' mod_index nmods
mb_old_iface mb_linkable src_modified
compile_it_discard_iface :: Maybe Linkable -> SourceModified
-> IO HomeModInfo
compile_it_discard_iface mb_linkable src_modified =
compileOne hsc_env summary' mod_index nmods
Nothing mb_linkable src_modified
-- With the HscNothing target we create empty linkables to avoid
-- recompilation. We have to detect these to recompile anyway if
-- the target changed since the last compile.
is_fake_linkable
| Just hmi <- old_hmi, Just l <- hm_linkable hmi =
null (linkableUnlinked l)
| otherwise =
-- we have no linkable, so it cannot be fake
False
implies False _ = True
implies True x = x
in
case () of
_
-- Regardless of whether we're generating object code or
-- byte code, we can always use an existing object file
-- if it is *stable* (see checkStability).
| is_stable_obj, Just hmi <- old_hmi -> do
liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
(text "skipping stable obj mod:" <+> ppr this_mod_name)
return hmi
-- object is stable, and we have an entry in the
-- old HPT: nothing to do
| is_stable_obj, isNothing old_hmi -> do
liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
(text "compiling stable on-disk mod:" <+> ppr this_mod_name)
linkable <- liftIO $ findObjectLinkable this_mod obj_fn
(expectJust "upsweep1" mb_obj_date)
compile_it (Just linkable) SourceUnmodifiedAndStable
-- object is stable, but we need to load the interface
-- off disk to make a HMI.
| not (isObjectTarget target), is_stable_bco,
(target /= HscNothing) `implies` not is_fake_linkable ->
ASSERT(isJust old_hmi) -- must be in the old_hpt
let Just hmi = old_hmi in do
liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
(text "skipping stable BCO mod:" <+> ppr this_mod_name)
return hmi
-- BCO is stable: nothing to do
| not (isObjectTarget target),
Just hmi <- old_hmi,
Just l <- hm_linkable hmi,
not (isObjectLinkable l),
(target /= HscNothing) `implies` not is_fake_linkable,
linkableTime l >= ms_hs_date summary -> do
liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
(text "compiling non-stable BCO mod:" <+> ppr this_mod_name)
compile_it (Just l) SourceUnmodified
-- we have an old BCO that is up to date with respect
-- to the source: do a recompilation check as normal.
-- When generating object code, if there's an up-to-date
-- object file on the disk, then we can use it.
-- However, if the object file is new (compared to any
-- linkable we had from a previous compilation), then we
-- must discard any in-memory interface, because this
-- means the user has compiled the source file
-- separately and generated a new interface, that we must
-- read from the disk.
--
| isObjectTarget target,
Just obj_date <- mb_obj_date,
obj_date >= hs_date -> do
case old_hmi of
Just hmi
| Just l <- hm_linkable hmi,
isObjectLinkable l && linkableTime l == obj_date -> do
liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
(text "compiling mod with new on-disk obj:" <+> ppr this_mod_name)
compile_it (Just l) SourceUnmodified
_otherwise -> do
liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
(text "compiling mod with new on-disk obj2:" <+> ppr this_mod_name)
linkable <- liftIO $ findObjectLinkable this_mod obj_fn obj_date
compile_it_discard_iface (Just linkable) SourceUnmodified
-- See Note [Recompilation checking when typechecking only]
| writeInterfaceOnlyMode dflags,
Just if_date <- mb_if_date,
if_date >= hs_date -> do
liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
(text "skipping tc'd mod:" <+> ppr this_mod_name)
compile_it Nothing SourceUnmodified
_otherwise -> do
liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
(text "compiling mod:" <+> ppr this_mod_name)
compile_it Nothing SourceModified
-- Note [Recompilation checking when typechecking only]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- If we are compiling with -fno-code -fwrite-interface, there won't
-- be any object code that we can compare against, nor should there
-- be: we're *just* generating interface files. In this case, we
-- want to check if the interface file is new, in lieu of the object
-- file. See also Trac #9243.
-- Filter modules in the HPT
retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
retainInTopLevelEnvs keep_these hpt
= listToUFM [ (mod, expectJust "retain" mb_mod_info)
| mod <- keep_these
, let mb_mod_info = lookupUFM hpt mod
, isJust mb_mod_info ]
-- ---------------------------------------------------------------------------
-- Typecheck module loops
{-
See bug #930. This code fixes a long-standing bug in --make. The
problem is that when compiling the modules *inside* a loop, a data
type that is only defined at the top of the loop looks opaque; but
after the loop is done, the structure of the data type becomes
apparent.
The difficulty is then that two different bits of code have
different notions of what the data type looks like.
The idea is that after we compile a module which also has an .hs-boot
file, we re-generate the ModDetails for each of the modules that
depends on the .hs-boot file, so that everyone points to the proper
TyCons, Ids etc. defined by the real module, not the boot module.
Fortunately re-generating a ModDetails from a ModIface is easy: the
function TcIface.typecheckIface does exactly that.
Picking the modules to re-typecheck is slightly tricky. Starting from
the module graph consisting of the modules that have already been
compiled, we reverse the edges (so they point from the imported module
to the importing module), and depth-first-search from the .hs-boot
node. This gives us all the modules that depend transitively on the
.hs-boot module, and those are exactly the modules that we need to
re-typecheck.
Following this fix, GHC can compile itself with --make -O2.
-}
reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
reTypecheckLoop hsc_env ms graph
| Just loop <- getModLoop ms graph
, let non_boot = filter (not.isBootSummary) loop
= typecheckLoop (hsc_dflags hsc_env) hsc_env (map ms_mod_name non_boot)
| otherwise
= return hsc_env
getModLoop :: ModSummary -> ModuleGraph -> Maybe [ModSummary]
getModLoop ms graph
| not (isBootSummary ms)
, any (\m -> ms_mod m == this_mod && isBootSummary m) graph
, let mss = reachableBackwards (ms_mod_name ms) graph
= Just mss
| otherwise
= Nothing
where
this_mod = ms_mod ms
typecheckLoop :: DynFlags -> HscEnv -> [ModuleName] -> IO HscEnv
typecheckLoop dflags hsc_env mods = do
debugTraceMsg dflags 2 $
text "Re-typechecking loop: " <> ppr mods
new_hpt <-
fixIO $ \new_hpt -> do
let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
mds <- initIfaceCheck new_hsc_env $
mapM (typecheckIface . hm_iface) hmis
let new_hpt = addListToUFM old_hpt
(zip mods [ hmi{ hm_details = details }
| (hmi,details) <- zip hmis mds ])
return new_hpt
return hsc_env{ hsc_HPT = new_hpt }
where
old_hpt = hsc_HPT hsc_env
hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
reachableBackwards mod summaries
= [ ms | (ms,_,_) <- reachableG (transposeG graph) root ]
where -- the rest just sets up the graph:
(graph, lookup_node) = moduleGraphNodes False summaries
root = expectJust "reachableBackwards" (lookup_node HsBootFile mod)
-- ---------------------------------------------------------------------------
--
-- | Topological sort of the module graph
topSortModuleGraph
:: Bool
-- ^ Drop hi-boot nodes? (see below)
-> [ModSummary]
-> Maybe ModuleName
-- ^ Root module name. If @Nothing@, use the full graph.
-> [SCC ModSummary]
-- ^ Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
-- The resulting list of strongly-connected-components is in topologically
-- sorted order, starting with the module(s) at the bottom of the
-- dependency graph (ie compile them first) and ending with the ones at
-- the top.
--
-- Drop hi-boot nodes (first boolean arg)?
--
-- - @False@: treat the hi-boot summaries as nodes of the graph,
-- so the graph must be acyclic
--
-- - @True@: eliminate the hi-boot nodes, and instead pretend
-- the a source-import of Foo is an import of Foo
-- The resulting graph has no hi-boot nodes, but can be cyclic
topSortModuleGraph drop_hs_boot_nodes summaries mb_root_mod
= map (fmap summaryNodeSummary) $ stronglyConnCompG initial_graph
where
(graph, lookup_node) = moduleGraphNodes drop_hs_boot_nodes summaries
initial_graph = case mb_root_mod of
Nothing -> graph
Just root_mod ->
-- restrict the graph to just those modules reachable from
-- the specified module. We do this by building a graph with
-- the full set of nodes, and determining the reachable set from
-- the specified node.
let root | Just node <- lookup_node HsSrcFile root_mod, graph `hasVertexG` node = node
| otherwise = throwGhcException (ProgramError "module does not exist")
in graphFromEdgedVertices (seq root (reachableG graph root))
type SummaryNode = (ModSummary, Int, [Int])
summaryNodeKey :: SummaryNode -> Int
summaryNodeKey (_, k, _) = k
summaryNodeSummary :: SummaryNode -> ModSummary
summaryNodeSummary (s, _, _) = s
moduleGraphNodes :: Bool -> [ModSummary]
-> (Graph SummaryNode, HscSource -> ModuleName -> Maybe SummaryNode)
moduleGraphNodes drop_hs_boot_nodes summaries = (graphFromEdgedVertices nodes, lookup_node)
where
numbered_summaries = zip summaries [1..]
lookup_node :: HscSource -> ModuleName -> Maybe SummaryNode
lookup_node hs_src mod = Map.lookup (mod, hscSourceToIsBoot hs_src) node_map
lookup_key :: HscSource -> ModuleName -> Maybe Int
lookup_key hs_src mod = fmap summaryNodeKey (lookup_node hs_src mod)
node_map :: NodeMap SummaryNode
node_map = Map.fromList [ ((moduleName (ms_mod s),
hscSourceToIsBoot (ms_hsc_src s)), node)
| node@(s, _, _) <- nodes ]
-- We use integers as the keys for the SCC algorithm
nodes :: [SummaryNode]
nodes = [ (s, key, out_keys)
| (s, key) <- numbered_summaries
-- Drop the hi-boot ones if told to do so
, not (isBootSummary s && drop_hs_boot_nodes)
, let out_keys = out_edge_keys hs_boot_key (map unLoc (ms_home_srcimps s)) ++
out_edge_keys HsSrcFile (map unLoc (ms_home_imps s)) ++
(-- see [boot-edges] below
if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
then []
else case lookup_key HsBootFile (ms_mod_name s) of
Nothing -> []
Just k -> [k]) ]
-- [boot-edges] if this is a .hs and there is an equivalent
-- .hs-boot, add a link from the former to the latter. This
-- has the effect of detecting bogus cases where the .hs-boot
-- depends on the .hs, by introducing a cycle. Additionally,
-- it ensures that we will always process the .hs-boot before
-- the .hs, and so the HomePackageTable will always have the
-- most up to date information.
-- Drop hs-boot nodes by using HsSrcFile as the key
hs_boot_key | drop_hs_boot_nodes = HsSrcFile
| otherwise = HsBootFile
out_edge_keys :: HscSource -> [ModuleName] -> [Int]
out_edge_keys hi_boot ms = mapMaybe (lookup_key hi_boot) ms
-- If we want keep_hi_boot_nodes, then we do lookup_key with
-- IsBoot; else NotBoot
-- The nodes of the graph are keyed by (mod, is boot?) pairs
-- NB: hsig files show up as *normal* nodes (not boot!), since they don't
-- participate in cycles (for now)
type NodeKey = (ModuleName, IsBoot)
type NodeMap a = Map.Map NodeKey a
msKey :: ModSummary -> NodeKey
msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot })
= (moduleName mod, hscSourceToIsBoot boot)
mkNodeMap :: [ModSummary] -> NodeMap ModSummary
mkNodeMap summaries = Map.fromList [ (msKey s, s) | s <- summaries]
nodeMapElts :: NodeMap a -> [a]
nodeMapElts = Map.elems
-- | If there are {-# SOURCE #-} imports between strongly connected
-- components in the topological sort, then those imports can
-- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
-- were necessary, then the edge would be part of a cycle.
warnUnnecessarySourceImports :: GhcMonad m => [SCC ModSummary] -> m ()
warnUnnecessarySourceImports sccs = do
dflags <- getDynFlags
when (wopt Opt_WarnUnusedImports dflags)
(logWarnings (listToBag (concatMap (check dflags . flattenSCC) sccs)))
where check dflags ms =
let mods_in_this_cycle = map ms_mod_name ms in
[ warn dflags i | m <- ms, i <- ms_home_srcimps m,
unLoc i `notElem` mods_in_this_cycle ]
warn :: DynFlags -> Located ModuleName -> WarnMsg
warn dflags (L loc mod) =
mkPlainErrMsg dflags loc
(text "Warning: {-# SOURCE #-} unnecessary in import of "
<+> quotes (ppr mod))
reportImportErrors :: MonadIO m => [Either ErrMsg b] -> m [b]
reportImportErrors xs | null errs = return oks
| otherwise = throwManyErrors errs
where (errs, oks) = partitionEithers xs
throwManyErrors :: MonadIO m => [ErrMsg] -> m ab
throwManyErrors errs = liftIO $ throwIO $ mkSrcErr $ listToBag errs
-----------------------------------------------------------------------------
--
-- | Downsweep (dependency analysis)
--
-- Chase downwards from the specified root set, returning summaries
-- for all home modules encountered. Only follow source-import
-- links.
--
-- We pass in the previous collection of summaries, which is used as a
-- cache to avoid recalculating a module summary if the source is
-- unchanged.
--
-- The returned list of [ModSummary] nodes has one node for each home-package
-- module, plus one for any hs-boot files. The imports of these nodes
-- are all there, including the imports of non-home-package modules.
downsweep :: HscEnv
-> [ModSummary] -- Old summaries
-> [ModuleName] -- Ignore dependencies on these; treat
-- them as if they were package modules
-> Bool -- True <=> allow multiple targets to have
-- the same module name; this is
-- very useful for ghc -M
-> IO [Either ErrMsg ModSummary]
-- The elts of [ModSummary] all have distinct
-- (Modules, IsBoot) identifiers, unless the Bool is true
-- in which case there can be repeats
downsweep hsc_env old_summaries excl_mods allow_dup_roots
= do
rootSummaries <- mapM getRootSummary roots
rootSummariesOk <- reportImportErrors rootSummaries
let root_map = mkRootMap rootSummariesOk
checkDuplicates root_map
summs <- loop (concatMap calcDeps rootSummariesOk) root_map
return summs
where
-- When we're compiling a signature file, we have an implicit
-- dependency on what-ever the signature's implementation is.
-- (But not when we're type checking!)
calcDeps summ
| HsigFile <- ms_hsc_src summ
, Just m <- getSigOf (hsc_dflags hsc_env) (moduleName (ms_mod summ))
, moduleUnitId m == thisPackage (hsc_dflags hsc_env)
= (noLoc (moduleName m), NotBoot) : msDeps summ
| otherwise = msDeps summ
dflags = hsc_dflags hsc_env
roots = hsc_targets hsc_env
old_summary_map :: NodeMap ModSummary
old_summary_map = mkNodeMap old_summaries
getRootSummary :: Target -> IO (Either ErrMsg ModSummary)
getRootSummary (Target (TargetFile file mb_phase) obj_allowed maybe_buf)
= do exists <- liftIO $ doesFileExist file
if exists
then Right `fmap` summariseFile hsc_env old_summaries file mb_phase
obj_allowed maybe_buf
else return $ Left $ mkPlainErrMsg dflags noSrcSpan $
text "can't find file:" <+> text file
getRootSummary (Target (TargetModule modl) obj_allowed maybe_buf)
= do maybe_summary <- summariseModule hsc_env old_summary_map NotBoot
(L rootLoc modl) obj_allowed
maybe_buf excl_mods
case maybe_summary of
Nothing -> return $ Left $ packageModErr dflags modl
Just s -> return s
rootLoc = mkGeneralSrcSpan (fsLit "<command line>")
-- In a root module, the filename is allowed to diverge from the module
-- name, so we have to check that there aren't multiple root files
-- defining the same module (otherwise the duplicates will be silently
-- ignored, leading to confusing behaviour).
checkDuplicates :: NodeMap [Either ErrMsg ModSummary] -> IO ()
checkDuplicates root_map
| allow_dup_roots = return ()
| null dup_roots = return ()
| otherwise = liftIO $ multiRootsErr dflags (head dup_roots)
where
dup_roots :: [[ModSummary]] -- Each at least of length 2
dup_roots = filterOut isSingleton $ map rights $ nodeMapElts root_map
loop :: [(Located ModuleName,IsBoot)]
-- Work list: process these modules
-> NodeMap [Either ErrMsg ModSummary]
-- Visited set; the range is a list because
-- the roots can have the same module names
-- if allow_dup_roots is True
-> IO [Either ErrMsg ModSummary]
-- The result includes the worklist, except
-- for those mentioned in the visited set
loop [] done = return (concat (nodeMapElts done))
loop ((wanted_mod, is_boot) : ss) done
| Just summs <- Map.lookup key done
= if isSingleton summs then
loop ss done
else
do { multiRootsErr dflags (rights summs); return [] }
| otherwise
= do mb_s <- summariseModule hsc_env old_summary_map
is_boot wanted_mod True
Nothing excl_mods
case mb_s of
Nothing -> loop ss done
Just (Left e) -> loop ss (Map.insert key [Left e] done)
Just (Right s)-> loop (calcDeps s ++ ss)
(Map.insert key [Right s] done)
where
key = (unLoc wanted_mod, is_boot)
mkRootMap :: [ModSummary] -> NodeMap [Either ErrMsg ModSummary]
mkRootMap summaries = Map.insertListWith (flip (++))
[ (msKey s, [Right s]) | s <- summaries ]
Map.empty
-- | Returns the dependencies of the ModSummary s.
-- A wrinkle is that for a {-# SOURCE #-} import we return
-- *both* the hs-boot file
-- *and* the source file
-- as "dependencies". That ensures that the list of all relevant
-- modules always contains B.hs if it contains B.hs-boot.
-- Remember, this pass isn't doing the topological sort. It's
-- just gathering the list of all relevant ModSummaries
msDeps :: ModSummary -> [(Located ModuleName, IsBoot)]
msDeps s =
concat [ [(m,IsBoot), (m,NotBoot)] | m <- ms_home_srcimps s ]
++ [ (m,NotBoot) | m <- ms_home_imps s ]
home_imps :: [(Maybe FastString, Located ModuleName)] -> [Located ModuleName]
home_imps imps = [ lmodname | (mb_pkg, lmodname) <- imps,
isLocal mb_pkg ]
where isLocal Nothing = True
isLocal (Just pkg) | pkg == fsLit "this" = True -- "this" is special
isLocal _ = False
ms_home_allimps :: ModSummary -> [ModuleName]
ms_home_allimps ms = map unLoc (ms_home_srcimps ms ++ ms_home_imps ms)
-- | Like 'ms_home_imps', but for SOURCE imports.
ms_home_srcimps :: ModSummary -> [Located ModuleName]
ms_home_srcimps = home_imps . ms_srcimps
-- | All of the (possibly) home module imports from a
-- 'ModSummary'; that is to say, each of these module names
-- could be a home import if an appropriately named file
-- existed. (This is in contrast to package qualified
-- imports, which are guaranteed not to be home imports.)
ms_home_imps :: ModSummary -> [Located ModuleName]
ms_home_imps = home_imps . ms_imps
-----------------------------------------------------------------------------
-- Summarising modules
-- We have two types of summarisation:
--
-- * Summarise a file. This is used for the root module(s) passed to
-- cmLoadModules. The file is read, and used to determine the root
-- module name. The module name may differ from the filename.
--
-- * Summarise a module. We are given a module name, and must provide
-- a summary. The finder is used to locate the file in which the module
-- resides.
summariseFile
:: HscEnv
-> [ModSummary] -- old summaries
-> FilePath -- source file name
-> Maybe Phase -- start phase
-> Bool -- object code allowed?
-> Maybe (StringBuffer,UTCTime)
-> IO ModSummary
summariseFile hsc_env old_summaries file mb_phase obj_allowed maybe_buf
-- we can use a cached summary if one is available and the
-- source file hasn't changed, But we have to look up the summary
-- by source file, rather than module name as we do in summarise.
| Just old_summary <- findSummaryBySourceFile old_summaries file
= do
let location = ms_location old_summary
dflags = hsc_dflags hsc_env
src_timestamp <- get_src_timestamp
-- The file exists; we checked in getRootSummary above.
-- If it gets removed subsequently, then this
-- getModificationUTCTime may fail, but that's the right
-- behaviour.
-- return the cached summary if the source didn't change
if ms_hs_date old_summary == src_timestamp &&
not (gopt Opt_ForceRecomp (hsc_dflags hsc_env))
then do -- update the object-file timestamp
obj_timestamp <-
if isObjectTarget (hscTarget (hsc_dflags hsc_env))
|| obj_allowed -- bug #1205
then liftIO $ getObjTimestamp location NotBoot
else return Nothing
hi_timestamp <- maybeGetIfaceDate dflags location
return old_summary{ ms_obj_date = obj_timestamp
, ms_iface_date = hi_timestamp }
else
new_summary src_timestamp
| otherwise
= do src_timestamp <- get_src_timestamp
new_summary src_timestamp
where
get_src_timestamp = case maybe_buf of
Just (_,t) -> return t
Nothing -> liftIO $ getModificationUTCTime file
-- getMofificationUTCTime may fail
new_summary src_timestamp = do
let dflags = hsc_dflags hsc_env
let hsc_src = if isHaskellSigFilename file then HsigFile else HsSrcFile
(dflags', hspp_fn, buf)
<- preprocessFile hsc_env file mb_phase maybe_buf
(srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn file
-- Make a ModLocation for this file
location <- liftIO $ mkHomeModLocation dflags mod_name file
-- Tell the Finder cache where it is, so that subsequent calls
-- to findModule will find it, even if it's not on any search path
mod <- liftIO $ addHomeModuleToFinder hsc_env mod_name location
-- when the user asks to load a source file by name, we only
-- use an object file if -fobject-code is on. See #1205.
obj_timestamp <-
if isObjectTarget (hscTarget (hsc_dflags hsc_env))
|| obj_allowed -- bug #1205
then liftIO $ modificationTimeIfExists (ml_obj_file location)
else return Nothing
hi_timestamp <- maybeGetIfaceDate dflags location
return (ModSummary { ms_mod = mod, ms_hsc_src = hsc_src,
ms_location = location,
ms_hspp_file = hspp_fn,
ms_hspp_opts = dflags',
ms_hspp_buf = Just buf,
ms_srcimps = srcimps, ms_textual_imps = the_imps,
ms_hs_date = src_timestamp,
ms_iface_date = hi_timestamp,
ms_obj_date = obj_timestamp })
findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
findSummaryBySourceFile summaries file
= case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
[] -> Nothing
(x:_) -> Just x
-- Summarise a module, and pick up source and timestamp.
summariseModule
:: HscEnv
-> NodeMap ModSummary -- Map of old summaries
-> IsBoot -- IsBoot <=> a {-# SOURCE #-} import
-> Located ModuleName -- Imported module to be summarised
-> Bool -- object code allowed?
-> Maybe (StringBuffer, UTCTime)
-> [ModuleName] -- Modules to exclude
-> IO (Maybe (Either ErrMsg ModSummary)) -- Its new summary
summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod)
obj_allowed maybe_buf excl_mods
| wanted_mod `elem` excl_mods
= return Nothing
| Just old_summary <- Map.lookup (wanted_mod, is_boot) old_summary_map
= do -- Find its new timestamp; all the
-- ModSummaries in the old map have valid ml_hs_files
let location = ms_location old_summary
src_fn = expectJust "summariseModule" (ml_hs_file location)
-- check the modification time on the source file, and
-- return the cached summary if it hasn't changed. If the
-- file has disappeared, we need to call the Finder again.
case maybe_buf of
Just (_,t) -> check_timestamp old_summary location src_fn t
Nothing -> do
m <- tryIO (getModificationUTCTime src_fn)
case m of
Right t -> check_timestamp old_summary location src_fn t
Left e | isDoesNotExistError e -> find_it
| otherwise -> ioError e
| otherwise = find_it
where
dflags = hsc_dflags hsc_env
check_timestamp old_summary location src_fn src_timestamp
| ms_hs_date old_summary == src_timestamp &&
not (gopt Opt_ForceRecomp dflags) = do
-- update the object-file timestamp
obj_timestamp <-
if isObjectTarget (hscTarget (hsc_dflags hsc_env))
|| obj_allowed -- bug #1205
then getObjTimestamp location is_boot
else return Nothing
hi_timestamp <- maybeGetIfaceDate dflags location
return (Just (Right old_summary{ ms_obj_date = obj_timestamp
, ms_iface_date = hi_timestamp}))
| otherwise =
-- source changed: re-summarise.
new_summary location (ms_mod old_summary) src_fn src_timestamp
find_it = do
-- Don't use the Finder's cache this time. If the module was
-- previously a package module, it may have now appeared on the
-- search path, so we want to consider it to be a home module. If
-- the module was previously a home module, it may have moved.
uncacheModule hsc_env wanted_mod
found <- findImportedModule hsc_env wanted_mod Nothing
case found of
Found location mod
| isJust (ml_hs_file location) ->
-- Home package
just_found location mod
_ -> return Nothing
-- Not found
-- (If it is TRULY not found at all, we'll
-- error when we actually try to compile)
just_found location mod = do
-- Adjust location to point to the hs-boot source file,
-- hi file, object file, when is_boot says so
let location' | IsBoot <- is_boot = addBootSuffixLocn location
| otherwise = location
src_fn = expectJust "summarise2" (ml_hs_file location')
-- Check that it exists
-- It might have been deleted since the Finder last found it
maybe_t <- modificationTimeIfExists src_fn
case maybe_t of
Nothing -> return $ Just $ Left $ noHsFileErr dflags loc src_fn
Just t -> new_summary location' mod src_fn t
new_summary location mod src_fn src_timestamp
= do
-- Preprocess the source file and get its imports
-- The dflags' contains the OPTIONS pragmas
(dflags', hspp_fn, buf) <- preprocessFile hsc_env src_fn Nothing maybe_buf
(srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn src_fn
-- NB: Despite the fact that is_boot is a top-level parameter, we
-- don't actually know coming into this function what the HscSource
-- of the module in question is. This is because we may be processing
-- this module because another module in the graph imported it: in this
-- case, we know if it's a boot or not because of the {-# SOURCE #-}
-- annotation, but we don't know if it's a signature or a regular
-- module until we actually look it up on the filesystem.
let hsc_src = case is_boot of
IsBoot -> HsBootFile
_ | isHaskellSigFilename src_fn -> HsigFile
| otherwise -> HsSrcFile
when (mod_name /= wanted_mod) $
throwOneError $ mkPlainErrMsg dflags' mod_loc $
text "File name does not match module name:"
$$ text "Saw:" <+> quotes (ppr mod_name)
$$ text "Expected:" <+> quotes (ppr wanted_mod)
-- Find the object timestamp, and return the summary
obj_timestamp <-
if isObjectTarget (hscTarget (hsc_dflags hsc_env))
|| obj_allowed -- bug #1205
then getObjTimestamp location is_boot
else return Nothing
hi_timestamp <- maybeGetIfaceDate dflags location
return (Just (Right (ModSummary { ms_mod = mod,
ms_hsc_src = hsc_src,
ms_location = location,
ms_hspp_file = hspp_fn,
ms_hspp_opts = dflags',
ms_hspp_buf = Just buf,
ms_srcimps = srcimps,
ms_textual_imps = the_imps,
ms_hs_date = src_timestamp,
ms_iface_date = hi_timestamp,
ms_obj_date = obj_timestamp })))
getObjTimestamp :: ModLocation -> IsBoot -> IO (Maybe UTCTime)
getObjTimestamp location is_boot
= if is_boot == IsBoot then return Nothing
else modificationTimeIfExists (ml_obj_file location)
preprocessFile :: HscEnv
-> FilePath
-> Maybe Phase -- ^ Starting phase
-> Maybe (StringBuffer,UTCTime)
-> IO (DynFlags, FilePath, StringBuffer)
preprocessFile hsc_env src_fn mb_phase Nothing
= do
(dflags', hspp_fn) <- preprocess hsc_env (src_fn, mb_phase)
buf <- hGetStringBuffer hspp_fn
return (dflags', hspp_fn, buf)
preprocessFile hsc_env src_fn mb_phase (Just (buf, _time))
= do
let dflags = hsc_dflags hsc_env
let local_opts = getOptions dflags buf src_fn
(dflags', leftovers, warns)
<- parseDynamicFilePragma dflags local_opts
checkProcessArgsResult dflags leftovers
handleFlagWarnings dflags' warns
let needs_preprocessing
| Just (Unlit _) <- mb_phase = True
| Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
-- note: local_opts is only required if there's no Unlit phase
| xopt LangExt.Cpp dflags' = True
| gopt Opt_Pp dflags' = True
| otherwise = False
when needs_preprocessing $
throwGhcExceptionIO (ProgramError "buffer needs preprocesing; interactive check disabled")
return (dflags', src_fn, buf)
-----------------------------------------------------------------------------
-- Error messages
-----------------------------------------------------------------------------
noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> ErrMsg
-- ToDo: we don't have a proper line number for this error
noModError dflags loc wanted_mod err
= mkPlainErrMsg dflags loc $ cannotFindModule dflags wanted_mod err
noHsFileErr :: DynFlags -> SrcSpan -> String -> ErrMsg
noHsFileErr dflags loc path
= mkPlainErrMsg dflags loc $ text "Can't find" <+> text path
packageModErr :: DynFlags -> ModuleName -> ErrMsg
packageModErr dflags mod
= mkPlainErrMsg dflags noSrcSpan $
text "module" <+> quotes (ppr mod) <+> text "is a package module"
multiRootsErr :: DynFlags -> [ModSummary] -> IO ()
multiRootsErr _ [] = panic "multiRootsErr"
multiRootsErr dflags summs@(summ1:_)
= throwOneError $ mkPlainErrMsg dflags noSrcSpan $
text "module" <+> quotes (ppr mod) <+>
text "is defined in multiple files:" <+>
sep (map text files)
where
mod = ms_mod summ1
files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
cyclicModuleErr :: [ModSummary] -> SDoc
-- From a strongly connected component we find
-- a single cycle to report
cyclicModuleErr mss
= ASSERT( not (null mss) )
case findCycle graph of
Nothing -> text "Unexpected non-cycle" <+> ppr mss
Just path -> vcat [ text "Module imports form a cycle:"
, nest 2 (show_path path) ]
where
graph :: [Node NodeKey ModSummary]
graph = [(ms, msKey ms, get_deps ms) | ms <- mss]
get_deps :: ModSummary -> [NodeKey]
get_deps ms = ([ (unLoc m, IsBoot) | m <- ms_home_srcimps ms ] ++
[ (unLoc m, NotBoot) | m <- ms_home_imps ms ])
show_path [] = panic "show_path"
show_path [m] = text "module" <+> ppr_ms m
<+> text "imports itself"
show_path (m1:m2:ms) = vcat ( nest 7 (text "module" <+> ppr_ms m1)
: nest 6 (text "imports" <+> ppr_ms m2)
: go ms )
where
go [] = [text "which imports" <+> ppr_ms m1]
go (m:ms) = (text "which imports" <+> ppr_ms m) : go ms
ppr_ms :: ModSummary -> SDoc
ppr_ms ms = quotes (ppr (moduleName (ms_mod ms))) <+>
(parens (text (msHsFilePath ms)))
| vikraman/ghc | compiler/main/GhcMake.hs | bsd-3-clause | 88,794 | 9 | 35 | 28,133 | 14,533 | 7,430 | 7,103 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS -Wall -fno-warn-missing-signatures #-}
-- | Ghc compatibility layer.
module Haskell.Docs.Ghc where
import Haskell.Docs.Types
import Control.Exception (SomeException)
import GHC hiding (verbosity)
import GHC.Paths (libdir)
import GhcMonad (liftIO)
import Module
import Name
import Outputable
import Packages
import qualified SrcLoc
#if __GLASGOW_HASKELL__ < 706
import DynFlags (defaultLogAction)
#else
import DynFlags (defaultFatalMessager, defaultFlushOut)
#endif
-- * GHC actions
-- | Run an action with an initialized GHC package set.
withInitializedPackages :: [String] -> Ghc a -> IO a
withInitializedPackages ghcopts m =
run (do dflags <- getSessionDynFlags
(dflags', _, _) <- parseDynamicFlags dflags (map SrcLoc.noLoc ghcopts)
_ <- setSessionDynFlags (dflags' { hscTarget = HscInterpreted
, ghcLink = LinkInMemory })
(dflags'',_packageids) <- liftIO (initPackages dflags')
_ <- setSessionDynFlags dflags''
m)
-- | Get the type of the given identifier from the given module.
findIdentifier :: ModuleName -> Identifier -> Ghc (Maybe Id)
findIdentifier mname name =
gcatch (do _ <- depanal [] False
_ <- load LoadAllTargets
setImportContext mname
names <- getNamesInScope
mty <- lookupName (head (filter ((==unIdentifier name).getOccString) names))
case mty of
Just (AnId i) -> return (Just i)
_ -> return Nothing)
(\(_ :: SomeException) -> return Nothing)
-- | Make a module name.
makeModuleName :: String -> ModuleName
makeModuleName = mkModuleName
-- * Internal functions
-- | Run the given GHC action.
#if __GLASGOW_HASKELL__ < 706
run :: Ghc a -> IO a
run = defaultErrorHandler defaultLogAction . runGhc (Just libdir)
#else
run :: Ghc a -> IO a
run = defaultErrorHandler defaultFatalMessager defaultFlushOut . runGhc (Just libdir)
#endif
-- | Pretty print something to string.
showppr dflags = Haskell.Docs.Ghc.showSDocForUser dflags neverQualify . ppr
-- | Wraps 'Outputable.showSDocForUser'.
#if __GLASGOW_HASKELL__ == 702
showSDocForUser _ = Outputable.showSDocForUser
#endif
#if __GLASGOW_HASKELL__ == 704
showSDocForUser _ = Outputable.showSDocForUser
#endif
#if __GLASGOW_HASKELL__ == 706
showSDocForUser = Outputable.showSDocForUser
#endif
#if __GLASGOW_HASKELL__ == 708
showSDocForUser = Outputable.showSDocForUser
#endif
#if __GLASGOW_HASKELL__ == 710
showSDocForUser = Outputable.showSDocForUser
#endif
-- | Set the import context.
setImportContext :: ModuleName -> Ghc ()
#if __GLASGOW_HASKELL__ == 702
setImportContext mname = setContext [] [simpleImportDecl mname]
#else
setImportContext mname = setContext [IIDecl (simpleImportDecl mname)]
#endif
-- | Show the package name e.g. base.
#if __GLASGOW_HASKELL__ >= 710
showPackageName :: PackageKey -> String
showPackageName = packageKeyString
#else
showPackageName :: PackageIdentifier -> String
showPackageName = packageIdString . mkPackageId
#endif
| chrisbarrett/haskell-docs | src/Haskell/Docs/Ghc.hs | bsd-3-clause | 3,236 | 0 | 18 | 725 | 580 | 317 | 263 | 44 | 2 |
-- Simple example reads a C file, extracts comments, and prints them.
-- Build with something like this:
-- ghc -package-conf ../dist/package.conf.inplace --make Main.hs
import Language.C
import Language.C.Comments
import System (getArgs)
import Text.Printf
printComment :: Comment -> IO ()
printComment c = do
let posn = commentPosition c
file = posFile posn
row = posRow posn
col = posColumn posn
fmt = show $ commentFormat c
printf "(%d:%d) %s %s\n" row col file fmt
putStrLn $ commentText c
putStrLn $ commentTextWithoutMarks c
putStrLn "---"
main :: IO ()
main = do
putStrLn $ show SingleLine
[file] <- getArgs
cmnts <- comments file
mapM_ printComment cmnts
| ghulette/language-c-comments | examples/Main.hs | bsd-3-clause | 712 | 0 | 11 | 153 | 191 | 92 | 99 | 21 | 1 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE ViewPatterns #-}
module Comonad where
import Data.Function
import Data.Semigroup
import Control.Comonad
data Stream a = a :> Stream a deriving Functor
instance Comonad Stream where
extract (a :> _) = a
duplicate a@(_ :> as) = a :> duplicate as
newtype Embed f a = Embed { unembed :: f (f a) } deriving Functor
instance Comonad f => Comonad (Embed f) where
extract = extract . extract . unembed
duplicate (unembed -> w) = Embed $ fmap (Embed . duplicate) <$> duplicate w
instance (ComonadApply f, Applicative f) => Applicative (Embed f) where
pure = Embed . pure . pure
(<*>) = (<@>)
instance ComonadApply f => ComonadApply (Embed f) where
Embed f <@> Embed a = Embed $ (<@>) <$> f <@> a
data Zipper a = Zipper (Stream a) a (Stream a) deriving Functor
instance Applicative Zipper where
pure a = zipper id id a
(<*>) = (<@>)
type Sheet = Embed Zipper
moveL :: Zipper a -> Zipper a
moveL (Zipper (l :> ls) a rs) = Zipper ls l $ a :> rs
moveR :: Zipper a -> Zipper a
moveR (Zipper ls a (r :> rs)) = Zipper (a :> ls) r rs
instance Comonad Zipper where
extract (Zipper _ a _) = a
duplicate = zipper moveL moveR
coiter :: (a -> a) -> a -> Stream a
coiter f a = f a :> coiter f (f a)
instance ComonadApply Stream where
(f :> fs) <@> (a :> as) = f a :> (fs <@> as)
instance ComonadApply Zipper where
Zipper lf f rf <@> Zipper la a ra = Zipper (lf <@> la) (f a) (rf <@> ra)
zipper :: (a -> a) -> (a -> a) -> a -> Zipper a
zipper lf rf a = Zipper (coiter lf a) a (coiter rf a)
stolist :: Stream a -> [a]
stolist (a :> as) = a : stolist as
tolist :: Zipper a -> [a]
tolist (Zipper _ a as) = stolist $ a :> as
wat :: Zipper (Zipper Integer -> Integer)
wat = zipper id (\f w -> extract (moveL w) + extract (moveL $ moveL w)) (const 1)
inject :: a -> Zipper a -> Zipper a
inject a (Zipper ls _ rs) = Zipper ls a rs
sheet :: Sheet (Sheet Integer -> Integer)
sheet = Embed $ fmap (inject $ const 1) (inject (pure $ const 1) base)
where
base = unembed $ pure go
go :: Sheet Integer -> Integer
go (unembed -> w) = up + left
where
up = extract . extract $ moveL w
left = extract . moveL $ extract w
pascal :: Zipper (Zipper Integer)
pascal = unembed $ kfix sheet
moveRN :: Integer -> Zipper a -> Zipper a
moveRN (fromIntegral -> n) = head . drop n . iterate moveR
triangle :: Integer -> Integer
triangle n = extract $ moveRN n . extract . moveRN n $ pascal
main :: IO ()
main = print . take 10 . tolist $ kfix wat
| isovector/dependent-types | src/Comonad.hs | bsd-3-clause | 2,532 | 0 | 12 | 607 | 1,208 | 617 | 591 | 62 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module AminoAcid
( AminoAcid (..)
, Radical (..)
, Hydrated (..)
, HydratedAminoAcid
, AtomType (..)
, atomCoordinates
, atomHydrogens
, connections
, atoms
) where
import Data.Data (Data, Typeable, toConstr)
import Linear.V3 (V3)
data AminoAcid a = AminoAcid { nitro :: a
, carbonAlpha :: a
, carbon :: a
, oxi2 :: a
, oxi :: Maybe a
, radical :: Radical a
}
instance (Show a, Data a) => Show (AminoAcid a) where
show (AminoAcid nitro' carbonAlpha' carbon' oxi2' oxi' radical') =
show (toConstr radical') ++ baseAtoms
where baseAtoms = "\n N " ++ show nitro' ++
"\n CA " ++ show carbonAlpha' ++
"\n C " ++ show carbon' ++
"\n O " ++ show oxi2' ++
(case oxi' of
Nothing -> ""
Just v -> "\n OXT " ++ show v) ++
"\n R " ++ show radical'
data Radical a = Alanine a -- CB
| Glysine -- nothing
| Valine a a a -- CB CG1 CG2
| Isoleucine a a a a -- CB CG1 CG2 CD1
| Leucine a a a a -- CB CG CD1 CD2
| Methionine a a a a -- CB CG SD CE
| Phenylalanine a a a a a a a -- CB CG CD1 CD2 CE1 CE2 CZ
| Tyrosine a a a a a a a a -- CB CG CD1 CD2 CE1 CE2 CZ OH
| Tryptophan a a a a a a a a a a -- CB CG CD1 CD2 NE1 CE2 CE3 CZ2 CZ3 CH2
| Serine a a -- CB OG
| Threonine a a a -- CB OG1 CG2
| Asparagine a a a a -- CB CG OD1 ND2
| Glutamine a a a a a -- CB CG CD OE1 NE2
| Cysteine a a -- CB SG
| Proline a a a -- CB CG CD
| Arginine a a a a a a a -- CB CG CD NE CZ NH1 NH2
| Histidine a a a a a a -- CB CG ND1 CD2 CE1 NE2
| Lysine a a a a a -- CB CG CD CE NZ
| AsparticAcid a a a a -- CB CG OD1 OD2
| GlutamicAcid a a a a a -- CB CG CD OE1 OE2
deriving (Typeable, Data)
instance (Show a) => Show (Radical a) where
show Glysine = ""
show (Alanine cb) = "CB " ++ show cb
show (Valine cb cg1 cg2) = "CB " ++ show cb ++
"\n CG1 " ++ show cg1 ++
"\n CG2 " ++ show cg2
show (Isoleucine cb cg1 cg2 cd1) = "CB " ++ show cb ++
"\n CG1 " ++ show cg1 ++
"\n CG2 " ++ show cg2 ++
"\n CD1 " ++ show cd1
show (Leucine cb cg cd1 cd2) = "CB " ++ show cb ++
"\n CG " ++ show cg ++
"\n CD1 " ++ show cd1 ++
"\n CD2 " ++ show cd2
show (Methionine cb cg sd ce) = "CB " ++ show cb ++
"\n CG " ++ show cg ++
"\n SD " ++ show sd ++
"\n CE " ++ show ce
show (Phenylalanine cb cg cd1 cd2 ce1 ce2 cz) = "CB " ++ show cb ++
"\n CG " ++ show cg ++
"\n CD1 " ++ show cd1 ++
"\n CD2 " ++ show cd2 ++
"\n CE1 " ++ show ce1 ++
"\n CE2 " ++ show ce2 ++
"\n CZ " ++ show cz
show (Tyrosine cb cg cd1 cd2 ce1 ce2 cz oh) = "CB " ++ show cb ++
"\n CG " ++ show cg ++
"\n CD1 " ++ show cd1 ++
"\n CD2 " ++ show cd2 ++
"\n CE1 " ++ show ce1 ++
"\n CE2 " ++ show ce2 ++
"\n CZ " ++ show cz ++
"\n OH " ++ show oh
show (Tryptophan cb cg cd1 cd2 ne1 ce2 ce3 cz2 cz3 ch2) = "CB " ++ show cb ++
"\n CG " ++ show cg ++
"\n CD1 " ++ show cd1 ++
"\n CD2 " ++ show cd2 ++
"\n NE1 " ++ show ne1 ++
"\n CE2 " ++ show ce2 ++
"\n CE3 " ++ show ce3 ++
"\n CZ2 " ++ show cz2 ++
"\n CZ3 " ++ show cz3 ++
"\n CH2 " ++ show ch2
show (Serine cb og) = "CB " ++ show cb ++
"\n OG " ++ show og
show (Threonine cb og1 cg2) = "CB " ++ show cb ++
"\n OG1 " ++ show og1 ++
"\n CG2 " ++ show cg2
show (Asparagine cb cg od1 nd2) = "CB " ++ show cb ++
"\n CG " ++ show cg ++
"\n OD1 " ++ show od1 ++
"\n ND2 " ++ show nd2
show (Glutamine cb cg cd oe1 ne2) = "CB " ++ show cb ++
"\n CG " ++ show cg ++
"\n CD " ++ show cd ++
"\n OE1 " ++ show oe1 ++
"\n NE2 " ++ show ne2
show (Cysteine cb sg) = "CB " ++ show cb ++
"\n SG " ++ show sg
show (Proline cb cg cd) = "CB " ++ show cb ++
"\n CG " ++ show cg ++
"\n CD " ++ show cd
show (Arginine cb cg cd ne cz nh1 nh2) = "CB " ++ show cb ++
"\n CG " ++ show cg ++
"\n CD " ++ show cd ++
"\n NE " ++ show ne ++
"\n CZ " ++ show cz ++
"\n NH1 " ++ show nh1 ++
"\n NH2 " ++ show nh2
show (Histidine cb cg nd1 cd2 ce1 ne2) = "CB " ++ show cb ++
"\n CG " ++ show cg ++
"\n ND1 " ++ show nd1 ++
"\n CD2 " ++ show cd2 ++
"\n CE1 " ++ show ce1 ++
"\n NE2 " ++ show ne2
show (Lysine cb cg cd ce nz) = "CB " ++ show cb ++
"\n CG " ++ show cg ++
"\n CD " ++ show cd ++
"\n CE " ++ show ce ++
"\n NZ " ++ show nz
show (AsparticAcid cb cg od1 od2) = "CB " ++ show cb ++
"\n CG " ++ show cg ++
"\n OD1 " ++ show od1 ++
"\n OD2 " ++ show od2
show (GlutamicAcid cb cg cd oe1 oe2) = "CB " ++ show cb ++
"\n CG " ++ show cg ++
"\n CD " ++ show cd ++
"\n OE1 " ++ show oe1 ++
"\n OE2 " ++ show oe2
instance Functor Radical where
fmap f (Alanine cb) = Alanine $ f cb
fmap _ Glysine = Glysine
fmap f (Valine cb cg1 cg2) = Valine (f cb) (f cg1) (f cg2)
fmap f (Isoleucine cb cg1 cg2 cd1) = Isoleucine (f cb) (f cg1) (f cg2) (f cd1)
fmap f (Leucine cb cg cd1 cd2) = Leucine (f cb) (f cg) (f cd1) (f cd2)
fmap f (Methionine cb cg sd ce) = Methionine (f cb) (f cg) (f sd) (f ce)
fmap f (Phenylalanine cb cg cd1 cd2 ce1 ce2 cz) = Phenylalanine (f cb) (f cg) (f cd1) (f cd2) (f ce1) (f ce2) (f cz)
fmap f (Tyrosine cb cg cd1 cd2 ce1 ce2 cz oh) = Tyrosine (f cb) (f cg) (f cd1) (f cd2) (f ce1) (f ce2) (f cz) (f oh)
fmap f (Tryptophan cb cg cd1 cd2 ne1 ce2 ce3 cz2 cz3 ch2) = Tryptophan (f cb) (f cg) (f cd1) (f cd2) (f ne1) (f ce2) (f ce3) (f cz2) (f cz3) (f ch2)
fmap f (Serine cb og) = Serine (f cb) (f og)
fmap f (Threonine cb og1 cg2) = Threonine (f cb) (f og1) (f cg2)
fmap f (Asparagine cb cg od1 nd2) = Asparagine (f cb) (f cg) (f od1) (f nd2)
fmap f (Glutamine cb cg cd oe1 ne2) = Glutamine (f cb) (f cg) (f cd) (f oe1) (f ne2)
fmap f (Cysteine cb sg) = Cysteine (f cb) (f sg)
fmap f (Proline cb cg cd) = Proline (f cb) (f cg) (f cd)
fmap f (Arginine cb cg cd ne cz nh1 nh2) = Arginine (f cb) (f cg) (f cd) (f ne) (f cz) (f nh1) (f nh2)
fmap f (Histidine cb cg nd1 cd2 ce1 ne2) = Histidine (f cb) (f cg) (f nd1) (f cd2) (f ce1) (f ne2)
fmap f (Lysine cb cg cd ce nz) = Lysine (f cb) (f cg) (f cd) (f ce) (f nz)
fmap f (AsparticAcid cb cg od1 od2) = AsparticAcid (f cb) (f cg) (f od1) (f od2)
fmap f (GlutamicAcid cb cg cd oe1 oe2) = GlutamicAcid (f cb) (f cg) (f cd) (f oe1) (f oe2)
data Hydrated a = Hydrated a [a]
deriving (Show, Typeable, Data)
data AtomType = N | CA | C | O | OXT
| CB
| CG | CG1 | CG2
| CD | CD1 | CD2
| CE | CE1 | CE2 | CE3
| CZ | CZ2 | CZ3
| CH2
| SG
| SD
| OG | OG1
| OD1 | OD2
| OE1 | OE2
| OH
| ND1 | ND2
| NE | NE1 | NE2
| NZ
| NH1 | NH2
deriving (Show, Read, Eq, Ord)
type HydratedAminoAcid = AminoAcid (Hydrated (V3 Float))
atoms :: HydratedAminoAcid -> [AtomType]
atoms aminoacid = [N, CA, C, O] ++ case radical aminoacid of
Alanine {} -> [CB]
Glysine {} -> []
Valine {} -> [CB, CG1, CG2]
Isoleucine {} -> [CB, CG1, CG2, CD1]
Leucine {} -> [CB, CG, CD1, CD2]
Methionine {} -> [CB, CG, SD, CE]
Phenylalanine {} -> [CB, CG, CD1, CD2, CE1, CE2, CZ]
Tyrosine {} -> [CB, CG, CD1, CD2, CE1, CE2, CZ, OH]
Tryptophan {} -> [CB, CG, CD1, CD2, NE1, CE2, CE3, CZ2, CZ3, CH2]
Serine {} -> [CB, OG]
Threonine {} -> [CB, OG1, CG2]
Asparagine {} -> [CB, CG, OD1, ND2]
Glutamine {} -> [CB, CG, CD, OE1, NE2]
Cysteine {} -> [CB, SG]
Proline {} -> [CB, CG, CD]
Arginine {} -> [CB, CG, CD, NE, CZ, NH1, NH2]
Histidine {} -> [CB, CG, ND1, CD2, CE1, NE2]
Lysine {} -> [CB, CG, CD, CE, NZ]
AsparticAcid {} -> [CB, CG, OD1, OD2]
GlutamicAcid {} -> [CB, CG, CD, OE1, OE2]
atomCoordinates :: HydratedAminoAcid -> AtomType -> V3 Float
atomCoordinates aminoAcid atomType =
case atomType of
N -> nitroCoords
CA -> carbonAlphaCoords
C -> carbonCoords
O -> oxi2Coords
OXT -> case oxi aminoAcid of
Just (Hydrated oxiCoords _) -> oxiCoords
Nothing -> error "No atom OXT"
_ -> radicalAtomCoordinates (radical aminoAcid) atomType
where Hydrated nitroCoords _ = nitro aminoAcid
Hydrated carbonAlphaCoords _ = carbonAlpha aminoAcid
Hydrated carbonCoords _ = carbon aminoAcid
Hydrated oxi2Coords _ = oxi2 aminoAcid
radicalAtomCoordinates :: Radical (Hydrated (V3 Float)) -> AtomType -> V3 Float
radicalAtomCoordinates (Alanine (Hydrated atomCoords _)) atomType =
case atomType of
CB -> atomCoords
_ -> error $ "No atom type " ++ show atomType ++ "in Alanine"
radicalAtomCoordinates Glysine atomType = error $ "No atom type " ++ show atomType ++ "in Glysine, because it hasn't radical"
radicalAtomCoordinates (Valine cb cg1 cg2) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated cg1Coords _) = cg1
(Hydrated cg2Coords _) = cg2
in case atomType of
CB -> cbCoords
CG1 -> cg1Coords
CG2 -> cg2Coords
_ -> error $ "No atom type " ++ show atomType ++ "in Valine"
radicalAtomCoordinates (Isoleucine cb cg1 cg2 cd1) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated cg1Coords _) = cg1
(Hydrated cg2Coords _) = cg2
(Hydrated cd1Coords _) = cd1
in case atomType of
CB -> cbCoords
CG1 -> cg1Coords
CG2 -> cg2Coords
CD1 -> cd1Coords
_ -> error $ "No atom type " ++ show atomType ++ "in Isoleucine"
radicalAtomCoordinates (Leucine cb cg cd1 cd2) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated cgCoords _) = cg
(Hydrated cd1Coords _) = cd1
(Hydrated cd2Coords _) = cd2
in case atomType of
CB -> cbCoords
CG -> cgCoords
CD1 -> cd1Coords
CD2 -> cd2Coords
_ -> error $ "No atom type " ++ show atomType ++ "in Leucine"
radicalAtomCoordinates (Methionine cb cg sd ce) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated cgCoords _) = cg
(Hydrated sdCoords _) = sd
(Hydrated ceCoords _) = ce
in case atomType of
CB -> cbCoords
CG -> cgCoords
SD -> sdCoords
CE -> ceCoords
_ -> error $ "No atom type " ++ show atomType ++ "in Methionine"
radicalAtomCoordinates (Phenylalanine cb cg cd1 cd2 ce1 ce2 cz) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated cgCoords _) = cg
(Hydrated cd1Coords _) = cd1
(Hydrated cd2Coords _) = cd2
(Hydrated ce1Coords _) = ce1
(Hydrated ce2Coords _) = ce2
(Hydrated czCoords _) = cz
in case atomType of
CB -> cbCoords
CG -> cgCoords
CD1 -> cd1Coords
CE1 -> ce1Coords
CZ -> czCoords
CE2 -> ce2Coords
CD2 -> cd2Coords
_ -> error $ "No atom type " ++ show atomType ++ "in Phenylalanine"
radicalAtomCoordinates (Tyrosine cb cg cd1 cd2 ce1 ce2 cz oh) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated cgCoords _) = cg
(Hydrated cd1Coords _) = cd1
(Hydrated cd2Coords _) = cd2
(Hydrated ce1Coords _) = ce1
(Hydrated ce2Coords _) = ce2
(Hydrated czCoords _) = cz
(Hydrated ohCoords _) = oh
in case atomType of
CB -> cbCoords
CG -> cgCoords
CD1 -> cd1Coords
CE1 -> ce1Coords
CZ -> czCoords
CE2 -> ce2Coords
CD2 -> cd2Coords
OH -> ohCoords
_ -> error $ "No atom type " ++ show atomType ++ "in Tyrosine"
radicalAtomCoordinates (Tryptophan cb cg cd1 cd2 ne1 ce2 ce3 cz2 cz3 ch2) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated cgCoords _) = cg
(Hydrated cd1Coords _) = cd1
(Hydrated cd2Coords _) = cd2
(Hydrated ne1Coords _) = ne1
(Hydrated ce2Coords _) = ce2
(Hydrated ce3Coords _) = ce3
(Hydrated cz2Coords _) = cz2
(Hydrated cz3Coords _) = cz3
(Hydrated ch2Coords _) = ch2
in case atomType of
CB -> cbCoords
CG -> cgCoords
CD1 -> cd1Coords
NE1 -> ne1Coords
CE2 -> ce2Coords
CD2 -> cd2Coords
CE3 -> ce3Coords
CZ3 -> cz3Coords
CH2 -> ch2Coords
CZ2 -> cz2Coords
_ -> error $ "No atom type " ++ show atomType ++ "in Tryptophan"
radicalAtomCoordinates (Serine cb og) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated ogCoords _) = og
in case atomType of
CB -> cbCoords
OG -> ogCoords
_ -> error $ "No atom type " ++ show atomType ++ "in Serine"
radicalAtomCoordinates (Threonine cb og1 cg2) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated og1Coords _) = og1
(Hydrated cg2Coords _) = cg2
in case atomType of
CB -> cbCoords
OG1 -> og1Coords
CG2 -> cg2Coords
_ -> error $ "No atom type " ++ show atomType ++ "in Threonine"
radicalAtomCoordinates (Asparagine cb cg od1 nd2) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated cgCoords _) = cg
(Hydrated od1Coords _) = od1
(Hydrated nd2Coords _) = nd2
in case atomType of
CB -> cbCoords
CG -> cgCoords
OD1 -> od1Coords
ND2 -> nd2Coords
_ -> error $ "No atom type " ++ show atomType ++ "in Asparagine"
radicalAtomCoordinates (Glutamine cb cg cd oe1 ne2) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated cgCoords _) = cg
(Hydrated cdCoords _) = cd
(Hydrated oe1Coords _) = oe1
(Hydrated ne2Coords _) = ne2
in case atomType of
CB -> cbCoords
CG -> cgCoords
CD -> cdCoords
OE1 -> oe1Coords
NE2 -> ne2Coords
_ -> error $ "No atom type " ++ show atomType ++ "in Glutamine"
radicalAtomCoordinates (Cysteine cb sg) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated sgCoords _) = sg
in case atomType of
CB -> cbCoords
SG -> sgCoords
_ -> error $ "No atom type " ++ show atomType ++ "in Cysteine"
radicalAtomCoordinates (Proline cb cg cd) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated cgCoords _) = cg
(Hydrated cdCoords _) = cd
in case atomType of
CB -> cbCoords
CG -> cgCoords
CD -> cdCoords
_ -> error $ "No atom type " ++ show atomType ++ "in Proline"
radicalAtomCoordinates (Arginine cb cg cd ne cz nh1 nh2) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated cgCoords _) = cg
(Hydrated cdCoords _) = cd
(Hydrated neCoords _) = ne
(Hydrated czCoords _) = cz
(Hydrated nh1Coords _) = nh1
(Hydrated nh2Coords _) = nh2
in case atomType of
CB -> cbCoords
CG -> cgCoords
CD -> cdCoords
NE -> neCoords
CZ -> czCoords
NH1 -> nh1Coords
NH2 -> nh2Coords
_ -> error $ "No atom type " ++ show atomType ++ "in Arginine"
radicalAtomCoordinates (Histidine cb cg nd1 cd2 ce1 ne2) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated cgCoords _) = cg
(Hydrated nd1Coords _) = nd1
(Hydrated cd2Coords _) = cd2
(Hydrated ce1Coords _) = ce1
(Hydrated ne2Coords _) = ne2
in case atomType of
CB -> cbCoords
CG -> cgCoords
ND1 -> nd1Coords
CE1 -> ce1Coords
NE2 -> ne2Coords
CD2 -> cd2Coords
_ -> error $ "No atom type " ++ show atomType ++ "in Histidine"
radicalAtomCoordinates (Lysine cb cg cd ce nz) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated cgCoords _) = cg
(Hydrated cdCoords _) = cd
(Hydrated ceCoords _) = ce
(Hydrated nzCoords _) = nz
in case atomType of
CB -> cbCoords
CG -> cgCoords
CD -> cdCoords
CE -> ceCoords
NZ -> nzCoords
_ -> error $ "No atom type " ++ show atomType ++ "in Lysine"
radicalAtomCoordinates (AsparticAcid cb cg od1 od2) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated cgCoords _) = cg
(Hydrated od1Coords _) = od1
(Hydrated od2Coords _) = od2
in case atomType of
CB -> cbCoords
CG -> cgCoords
OD1 -> od1Coords
OD2 -> od2Coords
_ -> error $ "No atom type " ++ show atomType ++ "in AsparticAcid"
radicalAtomCoordinates (GlutamicAcid cb cg cd oe1 oe2) atomType =
let (Hydrated cbCoords _) = cb
(Hydrated cgCoords _) = cg
(Hydrated cdCoords _) = cd
(Hydrated oe1Coords _) = oe1
(Hydrated oe2Coords _) = oe2
in case atomType of
CB -> cbCoords
CG -> cgCoords
CD -> cdCoords
OE1 -> oe1Coords
OE2 -> oe2Coords
_ -> error $ "No atom type " ++ show atomType ++ "in GlutamicAcid"
atomHydrogens :: HydratedAminoAcid -> AtomType -> [V3 Float]
atomHydrogens aminoacid atomType =
case atomType of
N -> nitroHydrogensCoords
CA -> carbonAlphaHydrogensCoords
C -> carbonHydrogensCoords
O -> oxi2HydrogensCoords
OXT -> case oxi aminoacid of
Just (Hydrated _ oxiHydrogensCoords) -> oxiHydrogensCoords
Nothing -> error "No atom OXT"
_ -> radicalAtomHydrogens (radical aminoacid) atomType
where Hydrated _ nitroHydrogensCoords = nitro aminoacid
Hydrated _ carbonAlphaHydrogensCoords = carbonAlpha aminoacid
Hydrated _ carbonHydrogensCoords = carbon aminoacid
Hydrated _ oxi2HydrogensCoords = oxi2 aminoacid
radicalAtomHydrogens :: Radical (Hydrated (V3 Float)) -> AtomType -> [V3 Float]
radicalAtomHydrogens (Alanine (Hydrated _ hydrogens)) atomType =
case atomType of
CB -> hydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Alanine"
radicalAtomHydrogens Glysine atomType = error $ "No atom type " ++ show atomType ++ "in Glysine, because it hasn't radical"
radicalAtomHydrogens (Valine cb cg1 cg2) atomType =
let (Hydrated _ cbHydrogens ) = cb
(Hydrated _ cg1Hydrogens) = cg1
(Hydrated _ cg2Hydrogens) = cg2
in case atomType of
CB -> cbHydrogens
CG1 -> cg1Hydrogens
CG2 -> cg2Hydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Valine"
radicalAtomHydrogens (Isoleucine cb cg1 cg2 cd1) atomType =
let (Hydrated _ cbHydrogens ) = cb
(Hydrated _ cg1Hydrogens) = cg1
(Hydrated _ cg2Hydrogens) = cg2
(Hydrated _ cd1Hydrogens) = cd1
in case atomType of
CB -> cbHydrogens
CG1 -> cg1Hydrogens
CG2 -> cg2Hydrogens
CD1 -> cd1Hydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Isoleucine"
radicalAtomHydrogens (Leucine cb cg cd1 cd2) atomType =
let (Hydrated _ cbHydrogens ) = cb
(Hydrated _ cgHydrogens ) = cg
(Hydrated _ cd1Hydrogens) = cd1
(Hydrated _ cd2Hydrogens) = cd2
in case atomType of
CB -> cbHydrogens
CG -> cgHydrogens
CD1 -> cd1Hydrogens
CD2 -> cd2Hydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Leucine"
radicalAtomHydrogens (Methionine cb cg sd ce) atomType =
let (Hydrated _ cbHydrogens) = cb
(Hydrated _ cgHydrogens) = cg
(Hydrated _ sdHydrogens) = sd
(Hydrated _ ceHydrogens) = ce
in case atomType of
CB -> cbHydrogens
CG -> cgHydrogens
SD -> sdHydrogens
CE -> ceHydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Methionine"
radicalAtomHydrogens (Phenylalanine cb cg cd1 cd2 ce1 ce2 cz) atomType =
let (Hydrated _ cbHydrogens ) = cb
(Hydrated _ cgHydrogens ) = cg
(Hydrated _ cd1Hydrogens) = cd1
(Hydrated _ cd2Hydrogens) = cd2
(Hydrated _ ce1Hydrogens) = ce1
(Hydrated _ ce2Hydrogens) = ce2
(Hydrated _ czHydrogens ) = cz
in case atomType of
CB -> cbHydrogens
CG -> cgHydrogens
CD1 -> cd1Hydrogens
CE1 -> ce1Hydrogens
CZ -> czHydrogens
CE2 -> ce2Hydrogens
CD2 -> cd2Hydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Phenylalanine"
radicalAtomHydrogens (Tyrosine cb cg cd1 cd2 ce1 ce2 cz oh) atomType =
let (Hydrated _ cbHydrogens ) = cb
(Hydrated _ cgHydrogens ) = cg
(Hydrated _ cd1Hydrogens) = cd1
(Hydrated _ cd2Hydrogens) = cd2
(Hydrated _ ce1Hydrogens) = ce1
(Hydrated _ ce2Hydrogens) = ce2
(Hydrated _ czHydrogens ) = cz
(Hydrated _ ohHydrogens ) = oh
in case atomType of
CB -> cbHydrogens
CG -> cgHydrogens
CD1 -> cd1Hydrogens
CE1 -> ce1Hydrogens
CZ -> czHydrogens
CE2 -> ce2Hydrogens
CD2 -> cd2Hydrogens
OH -> ohHydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Tyrosine"
radicalAtomHydrogens (Tryptophan cb cg cd1 cd2 ne1 ce2 ce3 cz2 cz3 ch2) atomType =
let (Hydrated _ cbHydrogens ) = cb
(Hydrated _ cgHydrogens ) = cg
(Hydrated _ cd1Hydrogens) = cd1
(Hydrated _ cd2Hydrogens) = cd2
(Hydrated _ ne1Hydrogens) = ne1
(Hydrated _ ce2Hydrogens) = ce2
(Hydrated _ ce3Hydrogens) = ce3
(Hydrated _ cz2Hydrogens) = cz2
(Hydrated _ cz3Hydrogens) = cz3
(Hydrated _ ch2Hydrogens) = ch2
in case atomType of
CB -> cbHydrogens
CG -> cgHydrogens
CD1 -> cd1Hydrogens
NE1 -> ne1Hydrogens
CE2 -> ce2Hydrogens
CD2 -> cd2Hydrogens
CE3 -> ce3Hydrogens
CZ3 -> cz3Hydrogens
CH2 -> ch2Hydrogens
CZ2 -> cz2Hydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Tryptophan"
radicalAtomHydrogens (Serine cb og) atomType =
let (Hydrated _ cbHydrogens) = cb
(Hydrated _ ogHydrogens) = og
in case atomType of
CB -> cbHydrogens
OG -> ogHydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Serine"
radicalAtomHydrogens (Threonine cb og1 cg2) atomType =
let (Hydrated _ cbHydrogens ) = cb
(Hydrated _ og1Hydrogens) = og1
(Hydrated _ cg2Hydrogens) = cg2
in case atomType of
CB -> cbHydrogens
OG1 -> og1Hydrogens
CG2 -> cg2Hydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Threonine"
radicalAtomHydrogens (Asparagine cb cg od1 nd2) atomType =
let (Hydrated _ cbHydrogens ) = cb
(Hydrated _ cgHydrogens ) = cg
(Hydrated _ od1Hydrogens) = od1
(Hydrated _ nd2Hydrogens) = nd2
in case atomType of
CB -> cbHydrogens
CG -> cgHydrogens
OD1 -> od1Hydrogens
ND2 -> nd2Hydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Asparagine"
radicalAtomHydrogens (Glutamine cb cg cd oe1 ne2) atomType =
let (Hydrated _ cbHydrogens ) = cb
(Hydrated _ cgHydrogens ) = cg
(Hydrated _ cdHydrogens ) = cd
(Hydrated _ oe1Hydrogens) = oe1
(Hydrated _ ne2Hydrogens) = ne2
in case atomType of
CB -> cbHydrogens
CG -> cgHydrogens
CD -> cdHydrogens
OE1 -> oe1Hydrogens
NE2 -> ne2Hydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Glutamine"
radicalAtomHydrogens (Cysteine cb sg) atomType =
let (Hydrated _ cbHydrogens) = cb
(Hydrated _ sgHydrogens) = sg
in case atomType of
CB -> cbHydrogens
SG -> sgHydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Cysteine"
radicalAtomHydrogens (Proline cb cg cd) atomType =
let (Hydrated _ cbHydrogens) = cb
(Hydrated _ cgHydrogens) = cg
(Hydrated _ cdHydrogens) = cd
in case atomType of
CB -> cbHydrogens
CG -> cgHydrogens
CD -> cdHydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Proline"
radicalAtomHydrogens (Arginine cb cg cd ne cz nh1 nh2) atomType =
let (Hydrated _ cbHydrogens ) = cb
(Hydrated _ cgHydrogens ) = cg
(Hydrated _ cdHydrogens ) = cd
(Hydrated _ neHydrogens ) = ne
(Hydrated _ czHydrogens ) = cz
(Hydrated _ nh1Hydrogens) = nh1
(Hydrated _ nh2Hydrogens) = nh2
in case atomType of
CB -> cbHydrogens
CG -> cgHydrogens
CD -> cdHydrogens
NE -> neHydrogens
CZ -> czHydrogens
NH1 -> nh1Hydrogens
NH2 -> nh2Hydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Arginine"
radicalAtomHydrogens (Histidine cb cg nd1 cd2 ce1 ne2) atomType =
let (Hydrated _ cbHydrogens ) = cb
(Hydrated _ cgHydrogens ) = cg
(Hydrated _ nd1Hydrogens) = nd1
(Hydrated _ cd2Hydrogens) = cd2
(Hydrated _ ce1Hydrogens) = ce1
(Hydrated _ ne2Hydrogens) = ne2
in case atomType of
CB -> cbHydrogens
CG -> cgHydrogens
ND1 -> nd1Hydrogens
CE1 -> ce1Hydrogens
NE2 -> ne2Hydrogens
CD2 -> cd2Hydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Histidine"
radicalAtomHydrogens (Lysine cb cg cd ce nz) atomType =
let (Hydrated _ cbHydrogens) = cb
(Hydrated _ cgHydrogens) = cg
(Hydrated _ cdHydrogens) = cd
(Hydrated _ ceHydrogens) = ce
(Hydrated _ nzHydrogens) = nz
in case atomType of
CB -> cbHydrogens
CG -> cgHydrogens
CD -> cdHydrogens
CE -> ceHydrogens
NZ -> nzHydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in Lysine"
radicalAtomHydrogens (AsparticAcid cb cg od1 od2) atomType =
let (Hydrated _ cbHydrogens ) = cb
(Hydrated _ cgHydrogens ) = cg
(Hydrated _ od1Hydrogens) = od1
(Hydrated _ od2Hydrogens) = od2
in case atomType of
CB -> cbHydrogens
CG -> cgHydrogens
OD1 -> od1Hydrogens
OD2 -> od2Hydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in AsparticAcid"
radicalAtomHydrogens (GlutamicAcid cb cg cd oe1 oe2) atomType =
let (Hydrated _ cbHydrogens ) = cb
(Hydrated _ cgHydrogens ) = cg
(Hydrated _ cdHydrogens ) = cd
(Hydrated _ oe1Hydrogens) = oe1
(Hydrated _ oe2Hydrogens) = oe2
in case atomType of
CB -> cbHydrogens
CG -> cgHydrogens
CD -> cdHydrogens
OE1 -> oe1Hydrogens
OE2 -> oe2Hydrogens
_ -> error $ "No atom type " ++ show atomType ++ "in GlutamicAcid"
connections :: HydratedAminoAcid -> [(AtomType, AtomType)]
connections aminoacid = [(N, CA), (CA, C), (C, O)] ++ caConnections aminoacid ++ radicalConnections (radical aminoacid)
caConnections :: HydratedAminoAcid -> [(AtomType, AtomType)]
caConnections aminoacid = case radical aminoacid of
Glysine {} -> []
_ -> [(CA, CB)]
radicalConnections :: Radical (Hydrated (V3 Float)) -> [(AtomType, AtomType)]
radicalConnections Alanine {} = []
radicalConnections Glysine {} = []
radicalConnections Valine {} = [(CB, CG1), (CB, CG2)]
radicalConnections Isoleucine {} = [(CB, CG1), (CB, CG2), (CG1, CD1)]
radicalConnections Leucine {} = [(CB, CG), (CG, CD1), (CG, CD2)]
radicalConnections Methionine {} = [(CB, CG), (CG, SD), (SD, CE)]
radicalConnections Phenylalanine {} = [(CB, CG), (CG, CD1), (CD1, CE1), (CE1, CZ), (CZ, CE2), (CE2, CD2), (CD2, CG)]
radicalConnections Tyrosine {} = [(CB, CG), (CG, CD1), (CD1, CE1), (CE1, CZ), (CZ, CE2), (CE2, CD2), (CD2, CG)]
radicalConnections Tryptophan {} = [(CB, CG), (CG, CD1), (CD1, NE1), (NE1, CE2), (CE2, CD2), (CD2, CG), (CD2, CE3), (CE3, CZ3), (CZ3, CH2), (CH2, CZ2), (CZ2, CE2)]
radicalConnections Serine {} = [(CB, OG)]
radicalConnections Threonine {} = [(CB, OG1), (CB, CG2)]
radicalConnections Asparagine {} = [(CB, CG), (CG, OD1), (CG, ND2)]
radicalConnections Glutamine {} = [(CB, CG), (CG, CD), (CD, OE1), (CD, NE2)]
radicalConnections Cysteine {} = [(CB, SG)]
radicalConnections Proline {} = [(CB, CG), (CG, CD), (CD, N)]
radicalConnections Arginine {} = [(CB, CG), (CG, CD), (CD, NE), (NE, CZ), (CZ, NH2)]
radicalConnections Histidine {} = [(CB, CG), (CG, ND1), (ND1, CE1), (CE1, NE2), (NE2, CD2), (CD2, CG)]
radicalConnections Lysine {} = [(CB, CG), (CG, CD), (CD, CE), (CE, NZ)]
radicalConnections AsparticAcid {} = [(CB, CG), (CG, OD1), (CG, OD2)]
radicalConnections GlutamicAcid {} = [(CB, CG), (CG, CD), (CD, OE1), (CD, OE2)]
| mosigo/haskell-sandbox | src/AminoAcid.hs | bsd-3-clause | 33,381 | 0 | 25 | 13,808 | 10,757 | 5,481 | 5,276 | 725 | 88 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.VertexShader
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/ARB/vertex_shader.txt ARB_vertex_shader> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.VertexShader (
-- * Enums
gl_CURRENT_VERTEX_ATTRIB_ARB,
gl_FLOAT,
gl_FLOAT_MAT2_ARB,
gl_FLOAT_MAT3_ARB,
gl_FLOAT_MAT4_ARB,
gl_FLOAT_VEC2_ARB,
gl_FLOAT_VEC3_ARB,
gl_FLOAT_VEC4_ARB,
gl_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB,
gl_MAX_TEXTURE_COORDS_ARB,
gl_MAX_TEXTURE_IMAGE_UNITS_ARB,
gl_MAX_VARYING_FLOATS_ARB,
gl_MAX_VERTEX_ATTRIBS_ARB,
gl_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB,
gl_MAX_VERTEX_UNIFORM_COMPONENTS_ARB,
gl_OBJECT_ACTIVE_ATTRIBUTES_ARB,
gl_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB,
gl_VERTEX_ATTRIB_ARRAY_ENABLED_ARB,
gl_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB,
gl_VERTEX_ATTRIB_ARRAY_POINTER_ARB,
gl_VERTEX_ATTRIB_ARRAY_SIZE_ARB,
gl_VERTEX_ATTRIB_ARRAY_STRIDE_ARB,
gl_VERTEX_ATTRIB_ARRAY_TYPE_ARB,
gl_VERTEX_PROGRAM_POINT_SIZE_ARB,
gl_VERTEX_PROGRAM_TWO_SIDE_ARB,
gl_VERTEX_SHADER_ARB,
-- * Functions
glBindAttribLocationARB,
glDisableVertexAttribArrayARB,
glEnableVertexAttribArrayARB,
glGetActiveAttribARB,
glGetAttribLocationARB,
glGetVertexAttribPointervARB,
glGetVertexAttribdvARB,
glGetVertexAttribfvARB,
glGetVertexAttribivARB,
glVertexAttrib1dARB,
glVertexAttrib1dvARB,
glVertexAttrib1fARB,
glVertexAttrib1fvARB,
glVertexAttrib1sARB,
glVertexAttrib1svARB,
glVertexAttrib2dARB,
glVertexAttrib2dvARB,
glVertexAttrib2fARB,
glVertexAttrib2fvARB,
glVertexAttrib2sARB,
glVertexAttrib2svARB,
glVertexAttrib3dARB,
glVertexAttrib3dvARB,
glVertexAttrib3fARB,
glVertexAttrib3fvARB,
glVertexAttrib3sARB,
glVertexAttrib3svARB,
glVertexAttrib4NbvARB,
glVertexAttrib4NivARB,
glVertexAttrib4NsvARB,
glVertexAttrib4NubARB,
glVertexAttrib4NubvARB,
glVertexAttrib4NuivARB,
glVertexAttrib4NusvARB,
glVertexAttrib4bvARB,
glVertexAttrib4dARB,
glVertexAttrib4dvARB,
glVertexAttrib4fARB,
glVertexAttrib4fvARB,
glVertexAttrib4ivARB,
glVertexAttrib4sARB,
glVertexAttrib4svARB,
glVertexAttrib4ubvARB,
glVertexAttrib4uivARB,
glVertexAttrib4usvARB,
glVertexAttribPointerARB
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/ARB/VertexShader.hs | bsd-3-clause | 2,647 | 0 | 4 | 298 | 259 | 180 | 79 | 75 | 0 |
{-# LANGUAGE MultiParamTypeClasses #-}
module Lambda.Convertor.Type where
import DeepControl.Applicative
import DeepControl.Monad hiding (forM, mapM)
import Lambda.DataType (Name, Lambda)
import Lambda.DataType.Type
import Util.Pseudo
import Prelude hiding (forM, mapM)
import Data.Monoid
import Data.Foldable
import Data.Traversable
instance PseudoFunctor Type where
pdfmap f (x :-> y) = f x :-> f y
pdfmap f (TUPLE xs) = TUPLE (f |$> xs)
pdfmap f (CONS x) = CONS (f x)
pdfmap _ pm = pm
instance PseudoFoldable Type where
pdfoldMap f (x :-> y) = f x <> f y
pdfoldMap f (TUPLE xs) = fold $ f |$> xs
pdfoldMap f (CONS x) = f x
pdfoldMap f x = f x
instance PseudoTraversable Lambda Type where
pdmapM f (x :-> y) = f x <$|(:->)|*> f y
pdmapM f (TUPLE xs) = TUPLE |$> mapM f xs
pdmapM f (CONS x) = CONS |$> f x
pdmapM _ pm = (*:) pm
| ocean0yohsuke/Simply-Typed-Lambda | src/Lambda/Convertor/Type.hs | bsd-3-clause | 920 | 0 | 8 | 240 | 371 | 194 | 177 | 26 | 0 |
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module TestImport where
import Data.Aeson
import GHC.Generics
import Data.Serialize
import Data.Aeson.Serialize
import Control.Applicative ((<$>))
import Data.Traversable (traverse)
import Data.Maybe (catMaybes)
import Control.Monad (void)
import Data.Hashable
-- Needed for store creation
import SimpleStore
import SimpleStore.Cell
import DirectedKeys
import DirectedKeys.Types
-- import DirectedKeys.Router
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
type SampleCell = SimpleCell SampleKey SampleSrc SampleDst SampleTime Sample (SimpleStore CellKeyStore)
type SampleCellKey = CellKey SampleKey SampleSrc SampleDst SampleTime Sample
type SampleDirectedKey = DirectedKeyRaw SampleKey SampleSrc SampleDst SampleTime
data Sample = Sample {
sampleInt :: Int
} deriving (Show,Eq,Generic)
newtype SampleDst = SampleDst { unSampleDst :: Int }
deriving (Eq,Ord,Generic,Hashable)
instance Serialize SampleDst where
newtype SampleSrc = SampleSrc { unSampleSrc :: Int }
deriving (Eq,Ord,Generic ,Hashable)
instance Serialize SampleSrc where
newtype SampleKey = SampleKey { unSampleKey :: Int }
deriving (Eq,Ord,Generic ,Hashable)
instance Serialize SampleKey where
newtype SampleTime = SampleTime { unSampleTime :: Int }
deriving (Eq,Ord,Generic ,Hashable)
instance Serialize SampleTime where
----------------------------
sampleSrc :: SampleSrc
sampleSrc = SampleSrc 1
sampleDst :: SampleDst
sampleDst = SampleDst 1
sampleTime :: SampleTime
sampleTime = (SampleTime 0)
instance ToJSON Sample where
instance FromJSON Sample where
instance Serialize Sample where
get = getFromJSON
put = putToJSON
initSample :: Sample
initSample = Sample 0
sampleStoreCellKey :: SampleCellKey
sampleStoreCellKey = CellKey { getKey = getKeyFcn
, codeCellKeyFilename = fullEncodeFcn
, decodeCellKeyFilename = fullDecodeFcn
}
{-
type DirectedSampleKey = DirectedKeyRaw SampleKey SampleSrc SampleDst SampleTime
type SampleCell = SimpleCell
SampleKey
SampleSrc
SampleDst
SampleTime
Sample
(SimpleStore CellKeyStore)
type SampleCK = CellKey SampleKey SampleSrc SampleDst SampleTime Sample
-}
fullEncodeFcn :: SampleDirectedKey -> T.Text
fullEncodeFcn = TE.decodeUtf8 . encodeKey
fullDecodeFcn :: ( Serialize datetime
, Serialize destination
, Serialize source
, Serialize key)
=> T.Text
-> Either T.Text (DirectedKeyRaw key source destination datetime)
fullDecodeFcn akey = case (decodeKey $ TE.encodeUtf8 $ akey) of
Left e -> Left . T.pack $ e
Right r -> Right r
getKeyFcn :: Sample -> SampleDirectedKey
getKeyFcn st = DKeyRaw (SampleKey . sampleInt $ st) sampleSrc sampleDst sampleTime
--- Simple Cell generation
$(makeStoreCell 'sampleStoreCellKey 'initSample ''Sample)
-- | TH Defnitions
getSampleSC :: SampleCell -> SampleDirectedKey -> IO (Maybe (SimpleStore Sample))
repsertSampleSC :: SampleCell -> SimpleStore Sample -> Sample -> IO ()
createCheckpointAndCloseSampleSC :: SampleCell -> IO ()
insertSampleSC :: SampleCell -> Sample -> IO (SimpleStore Sample)
deleteSampleSC :: SampleCell -> SampleDirectedKey -> IO ()
traverseWithKeySampleSC_
:: SampleCell
-> (SampleCellKey -> SampleDirectedKey -> Sample -> IO ())
-> IO ()
foldlWithKeySampleSC
:: SampleCell
-> (SampleCellKey -> SampleDirectedKey -> Sample -> IO b -> IO b)
-> IO b
-> IO b
initializeSampleSC :: T.Text -> IO SampleCell
initializeSampleWithErrorsSC :: T.Text -> IO (InitializedCell SampleKey SampleSrc SampleDst SampleTime Sample (SimpleStore CellKeyStore))
checkpointsSampleSC :: SimpleCell
SampleKey SampleSrc SampleDst SampleTime Sample stdormant
-> IO ()
getOrInsertSampleSC
:: SampleCell
-> Sample
-> IO (SimpleStore Sample)
getOrInsertSampleSC sc si = do
maybeVal <- getSampleSC sc $ getKeyFcn si
case maybeVal of
(Just st) -> createCheckpoint st >> return st
Nothing -> insertSampleSC sc si >>= (\st -> createCheckpoint st >> return st)
runRestartTest :: [Int] -> IO [Int]
runRestartTest i = do
let sis = Sample <$> i
putStrLn "init first time"
sc <- initializeSampleSC "testSampleCell"
putStrLn "traverse given list"
void $ traverse (getOrInsertSampleSC sc) sis
putStrLn "first checkpiont and close"
createCheckpointAndCloseSampleSC sc
putStrLn "init second time"
sc' <- initializeSampleSC "testSampleCell"
putStrLn "list em"
storeSamples <- traverse (getSampleSC sc' . getKeyFcn) sis
putStrLn "store em"
samples <- traverse (traverse getSimpleStore) storeSamples
putStrLn "Checkpoint Only "
checkpointsSampleSC sc
putStrLn "checkpoint"
createCheckpointAndCloseSampleSC sc'
return $ sampleInt <$> (catMaybes samples)
| plow-technologies/simple-cell | test/TestImport.hs | bsd-3-clause | 5,412 | 0 | 14 | 1,378 | 1,251 | 648 | 603 | 116 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
-- In addition, you can configure a number of different aspects of Yesod
-- by overriding methods in the Yesod typeclass. That instance is
-- declared in the Foundation.hs file.
module Settings where
import ClassyPrelude.Yesod
import qualified Control.Exception as Exception
import Data.Aeson (Result (..), fromJSON, withObject, (.!=),
(.:?))
import Data.FileEmbed (embedFile)
import Data.Yaml (decodeEither')
import Database.Persist.Sqlite (SqliteConf)
import Language.Haskell.TH.Syntax (Exp, Name, Q)
import Network.Wai.Handler.Warp (HostPreference)
import Yesod.Default.Config2 (applyEnvValue, configSettingsYml)
import Yesod.Default.Util (WidgetFileSettings, widgetFileNoReload,
widgetFileReload)
-- | Runtime settings to configure this application. These settings can be
-- loaded from various sources: defaults, environment variables, config files,
-- theoretically even a database.
data AppSettings = AppSettings
{ appStaticDir :: String
-- ^ Directory from which to serve static files.
, appDatabaseConf :: SqliteConf
-- ^ Configuration settings for accessing the database.
, appRoot :: Maybe Text
-- ^ Base for all generated URLs. If @Nothing@, determined
-- from the request headers.
, appHost :: HostPreference
-- ^ Host/interface the server should bind to.
, appPort :: Int
-- ^ Port to listen on
, appIpFromHeader :: Bool
-- ^ Get the IP address from the header when logging. Useful when sitting
-- behind a reverse proxy.
, appDetailedRequestLogging :: Bool
-- ^ Use detailed request logging system
, appShouldLogAll :: Bool
-- ^ Should all log messages be displayed?
, appReloadTemplates :: Bool
-- ^ Use the reload version of templates
, appMutableStatic :: Bool
-- ^ Assume that files in the static dir may change after compilation
, appSkipCombining :: Bool
-- ^ Perform no stylesheet/script combining
-- Example app-specific configuration values.
, appCopyright :: Text
-- ^ Copyright text to appear in the footer of the page
, appAnalytics :: Maybe Text
-- ^ Google Analytics code
, appAuthDummyLogin :: Bool
-- ^ Indicate if auth dummy login should be enabled.
}
instance FromJSON AppSettings where
parseJSON = withObject "AppSettings" $ \o -> do
let defaultDev =
#ifdef DEVELOPMENT
True
#else
False
#endif
appStaticDir <- o .: "static-dir"
appDatabaseConf <- o .: "database"
appRoot <- o .:? "approot"
appHost <- fromString <$> o .: "host"
appPort <- o .: "port"
appIpFromHeader <- o .: "ip-from-header"
appDetailedRequestLogging <- o .:? "detailed-logging" .!= defaultDev
appShouldLogAll <- o .:? "should-log-all" .!= defaultDev
appReloadTemplates <- o .:? "reload-templates" .!= defaultDev
appMutableStatic <- o .:? "mutable-static" .!= defaultDev
appSkipCombining <- o .:? "skip-combining" .!= defaultDev
appCopyright <- o .: "copyright"
appAnalytics <- o .:? "analytics"
appAuthDummyLogin <- o .:? "auth-dummy-login" .!= defaultDev
return AppSettings {..}
-- | Settings for 'widgetFile', such as which template languages to support and
-- default Hamlet settings.
--
-- For more information on modifying behavior, see:
--
-- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile
widgetFileSettings :: WidgetFileSettings
widgetFileSettings = def
-- | How static files should be combined.
combineSettings :: CombineSettings
combineSettings = def
-- The rest of this file contains settings which rarely need changing by a
-- user.
widgetFile :: String -> Q Exp
widgetFile = (if appReloadTemplates compileTimeAppSettings
then widgetFileReload
else widgetFileNoReload)
widgetFileSettings
-- | Raw bytes at compile time of @config/settings.yml@
configSettingsYmlBS :: ByteString
configSettingsYmlBS = $(embedFile configSettingsYml)
-- | @config/settings.yml@, parsed to a @Value@.
configSettingsYmlValue :: Value
configSettingsYmlValue = either Exception.throw id
$ decodeEither' configSettingsYmlBS
-- | A version of @AppSettings@ parsed at compile time from @config/settings.yml@.
compileTimeAppSettings :: AppSettings
compileTimeAppSettings =
case fromJSON $ applyEnvValue False mempty configSettingsYmlValue of
Error e -> error e
Success settings -> settings
-- The following two functions can be used to combine multiple CSS or JS files
-- at compile time to decrease the number of http requests.
-- Sample usage (inside a Widget):
--
-- > $(combineStylesheets 'StaticR [style1_css, style2_css])
combineStylesheets :: Name -> [Route Static] -> Q Exp
combineStylesheets = combineStylesheets'
(appSkipCombining compileTimeAppSettings)
combineSettings
combineScripts :: Name -> [Route Static] -> Q Exp
combineScripts = combineScripts'
(appSkipCombining compileTimeAppSettings)
combineSettings
| flaviusb/moss-submitter-webapp | src/Settings.hs | mit | 5,824 | 0 | 12 | 1,573 | 732 | 422 | 310 | 79 | 2 |
module Examples.MostReliablePath
( mrExamples
) where
import Utils
import Algebra.Matrix
import Algebra.Semiring
import Policy.MostReliablePath
mrExamples :: Int -> Matrix MostReliablePath
mrExamples 0 = M (toArray 5 [ zero , MR 0.1, MR 0.4, zero , MR 0.5
, MR 0.1, zero , MR 0.4, zero , MR 0.3
, MR 0.4, MR 0.4, zero , MR 0.9, zero
, zero , zero , MR 0.9, zero , MR 0.2
, MR 0.5, MR 0.3, zero , MR 0.2, zero])
mrExamples _ = error "Undefined example of MostReliablePath"
| sdynerow/Semirings-Library | haskell/Examples/MostReliablePath.hs | apache-2.0 | 600 | 0 | 9 | 215 | 188 | 102 | 86 | 13 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="pt-BR">
<title>Substituto |Extensão ZAP</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Conteúdo</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Índice</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Busca</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favoritos</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/replacer/src/main/javahelp/org/zaproxy/zap/extension/replacer/resources/help_pt_BR/helpset_pt_BR.hs | apache-2.0 | 973 | 80 | 66 | 158 | 418 | 211 | 207 | -1 | -1 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE PatternSynonyms #-}
module Hans.IP4.Input (
processArp,
processIP4,
handleIP4,
) where
import Hans.Checksum (computeChecksum)
import Hans.Device (Device(..),ChecksumOffload(..),rxOffload)
import Hans.Ethernet (Mac,pattern ETYPE_ARP,sendEthernet)
import Hans.IP4.ArpTable (addEntry,lookupEntry)
import Hans.IP4.Fragments (processFragment)
import Hans.IP4.Icmp4 (Icmp4Packet(..),getIcmp4Packet)
import Hans.IP4.Output (queueIcmp4,portUnreachable)
import Hans.IP4.Packet
import Hans.IP4.RoutingTable (Route(..))
import Hans.Lens (view)
import Hans.Monad (Hans,io,dropPacket,escape,decode,decode')
import Hans.Network.Types
import Hans.Serialize (runPutPacket)
import Hans.Types
import Hans.Udp.Input (processUdp)
import Hans.Tcp.Input (processTcp)
import Control.Monad (when,unless)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
-- Arp Processing --------------------------------------------------------------
-- | Handle incoming Arp packets.
processArp :: NetworkStack -> Device -> S.ByteString -> Hans ()
processArp ns dev payload =
do ArpPacket { .. } <- decode (devStats dev) getArpPacket payload
-- if the entry already exists in the arp table, update it
merge <- io (updateEntry ns arpSHA arpSPA)
-- are we the target of the request?
mb <- io (isLocalAddr ns arpTPA)
dev' <- case mb of
Just route -> return (routeDevice route)
Nothing -> escape
let lha = devMac dev'
-- add the entry if it didn't already exist
unless merge (io (addEntry (ip4ArpTable (view ip4State ns)) arpSPA arpSHA))
-- respond if the packet was a who-has request for our mac
when (arpOper == ArpRequest)
$ io
$ sendEthernet dev' arpSHA ETYPE_ARP
$ runPutPacket 28 100 L.empty
$ putArpPacket ArpPacket { arpSHA = lha, arpSPA = arpTPA
, arpTHA = arpSHA, arpTPA = arpSPA
, arpOper = ArpReply }
-- | Update an entry in the arp table, if it exists already.
updateEntry :: NetworkStack -> Mac -> IP4 -> IO Bool
updateEntry ns sha spa =
do mb <- lookupEntry (ip4ArpTable (view ip4State ns)) spa
case mb of
Just _ -> do addEntry (ip4ArpTable (view ip4State ns)) spa sha
return True
Nothing -> return False
-- IP4 Processing --------------------------------------------------------------
-- | Process a packet that has arrived from a device.
processIP4 :: NetworkStack -> Device -> S.ByteString -> Hans ()
processIP4 ns dev payload =
do ((hdr,hdrLen,bodyLen),body) <- decode' (devStats dev) getIP4Packet payload
-- only validate the checkum if the device hasn't done that already
let packetValid = coIP4 (view rxOffload dev)
|| 0 == computeChecksum (S.take hdrLen payload)
unless packetValid (dropPacket (devStats dev))
-- Drop packets that weren't destined for an address that this device
-- holds.
-- XXX: if we ever want to use HaNS as a router, this would be where IP
-- routing would happen
checkDestination ns dev (ip4DestAddr hdr)
handleIP4 ns dev (Just (hdrLen,payload)) hdr (S.take bodyLen body)
-- | The processing stage after the packet has been decoded and validated. It's
-- exposed here so that routing to an address that's managed by the network
-- stack can skip the device layer.
handleIP4 :: NetworkStack -> Device -> Maybe (Int,S.ByteString)
-> IP4Header -> S.ByteString -> Hans ()
handleIP4 ns dev mbOrig hdr body =
do (IP4Header { .. },body') <-
processFragment (ip4Fragments (view ip4State ns)) hdr body
case ip4Protocol of
PROT_ICMP4 -> processICMP ns dev ip4SourceAddr ip4DestAddr body'
PROT_UDP ->
do routed <- processUdp ns dev ip4SourceAddr ip4DestAddr body'
case (routed,mbOrig) of
-- when we failed to route the datagram, and have the original
-- message handy, send a portUnreachable message.
(False,Just(ihl,orig)) -> io
$ portUnreachable ns dev (SourceIP4 ip4DestAddr) ip4SourceAddr
$ S.take (ihl + 8) orig
-- otherwise, the packet was routed from an internal device, or a
-- destination actually existed.
_ -> return ()
PROT_TCP -> processTcp ns dev ip4SourceAddr ip4DestAddr body'
_ -> dropPacket (devStats dev)
-- | Validate the destination of this packet.
checkDestination :: NetworkStack -> Device -> IP4 -> Hans ()
-- always accept broadcast messages
checkDestination _ _ BroadcastIP4 = return ()
-- require that the input device has the destination address
checkDestination ns dev dest =
do mb <- io (isLocalAddr ns dest)
case mb of
Just Route { .. }
| routeDevice == dev -> return ()
-- A route was found, and it didn't involve the device the packet
-- arrived on
| otherwise -> escape
-- No route was found. Check to see if there are any routes for this
-- device, and forward the packet on if there are none (in order to
-- support things like unicast DHCP).
Nothing ->
do routes <- io (routesForDev ns dev)
unless (null routes) escape
-- ICMP Processing -------------------------------------------------------------
-- | Process incoming ICMP packets.
processICMP :: NetworkStack -> Device -> IP4 -> IP4 -> S.ByteString -> Hans ()
processICMP ns dev src dst body =
do let packetValid = coIcmp4 (view rxOffload dev) || 0 == computeChecksum body
unless packetValid (dropPacket (devStats dev))
msg <- decode (devStats dev) getIcmp4Packet body
case msg of
-- XXX: use the stats and config for the device that the message arrived
-- on. As it's probably going out the same device, this seems OK, but it
-- would be nice to confirm that.
Echo ident seqNum bytes ->
do io (queueIcmp4 ns dev (SourceIP4 dst) src (EchoReply ident seqNum bytes))
escape
-- Drop all other messages for now
_ -> escape
| GaloisInc/HaNS | src/Hans/IP4/Input.hs | bsd-3-clause | 6,239 | 0 | 19 | 1,587 | 1,454 | 760 | 694 | 94 | 5 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
--------------------------------------------------------------------------------
-- |
-- Module : Data.Rakhana.Nursery
-- Copyright : (C) 2014 Yorick Laupa
-- License : (see the file LICENSE)
--
-- Maintainer : Yorick Laupa <yo.eight@gmail.com>
-- Stability : provisional
-- Portability : non-portable
--
--------------------------------------------------------------------------------
module Data.Rakhana.Nursery
( Playground
, Pages
, Root
, NReq
, NResp
, NurseryException(..)
, XRefException(..)
, nurseryGetInfo
, nurseryGetHeader
, nurseryGetPages
, nurseryLoadStreamData
, nurseryGetReferences
, nurseryResolve
, withNursery
) where
--------------------------------------------------------------------------------
import Prelude hiding (take, takeWhile)
import Control.Applicative
import qualified Data.ByteString.Lazy as BL
import qualified Data.Map.Strict as M
import qualified Data.Set as S
--------------------------------------------------------------------------------
import Codec.Compression.Zlib (decompress)
import Control.Lens
import Control.Lens.Action
import Control.Monad.Error.Class
import Control.Monad.Reader
import Control.Monad.State.Strict
import Control.Monad.Trans.Except
import Data.Attoparsec.ByteString.Char8
import qualified Data.Attoparsec.ByteString.Lazy as PL
import Pipes
import Pipes.Core
--------------------------------------------------------------------------------
import Data.Rakhana.Internal.Parsers
import Data.Rakhana.Internal.Types
import Data.Rakhana.Tape
import Data.Rakhana.Util.Drive
import Data.Rakhana.XRef
--------------------------------------------------------------------------------
data NurseryException
= NurseryParsingException (Maybe Reference) String
| NurseryParsingExceptionInObjStm String
| NurseryUnresolvedObject Int Int
| NurseryRootNotFound
| NurseryPagesNotFound
| NurseryInvalidStreamObject
| NurseryInvalidLinearizedObject
| NurseryXRefException XRefException
| NurseryExpectedStreamObject
| NurseryInvalidObjStm
| NurseryUnresolvedObjectInObjStm Int
| NurseryWrongObject Reference Reference
| NurseryCyclicDependency Reference
deriving Show
--------------------------------------------------------------------------------
type Nursery m a = Proxy TReq TResp NReq NResp m a
type Playground m a = Client' NReq NResp m a
type Root = Dictionary
type Pages = Dictionary
--------------------------------------------------------------------------------
data NReq
= RqInfo
| RqHeader
| RqPages
| RqResolve Reference
| RqLoadStreamData Stream
| RqReferences
--------------------------------------------------------------------------------
data NResp
= Unit
| RBinaryLazy BL.ByteString
| RInfo Dictionary
| RHeader Header
| RPages Dictionary
| RResolve Object
| RReferences [Reference]
--------------------------------------------------------------------------------
data ObjStm
= ObjStm
{ objStmCount :: !Integer
, objStmFirst :: !Integer
, objStmExtends :: !(Maybe Reference)
, objStmOffset :: !Integer
, objStmStream :: !BL.ByteString
, objStmReg :: !(M.Map Integer Integer)
}
deriving Show
--------------------------------------------------------------------------------
data NurseryState
= NurseryState
{ nurseryHeader :: !Header
, nurseryXRef :: !XRef
, nurseryRoot :: !Dictionary
, nurseryInfo :: !Dictionary
, nurseryPages :: !Dictionary
}
--------------------------------------------------------------------------------
bufferSize :: Int
bufferSize = 64
--------------------------------------------------------------------------------
nursery :: MonadError NurseryException m => Nursery m a
nursery
= do h <- getHeader
initState <- regularPDFAccess h
rq <- respond Unit
nurseryLoop dispatch initState rq
where
dispatch s RqInfo = serveInfo s
dispatch s RqPages = servePages s
dispatch s (RqResolve ref) = serveResolve s ref
dispatch s RqHeader = serveHeader s
dispatch s (RqLoadStreamData t) = serveLoadStream s t
dispatch s RqReferences = serveReferences s
--------------------------------------------------------------------------------
regularPDFAccess :: MonadError NurseryException m
=> Header
-> Nursery m NurseryState
regularPDFAccess h
= do pos <- hoist liftError getXRefPos
nurseryState h =<< hoist liftError (getXRef h pos)
--------------------------------------------------------------------------------
nurseryState :: MonadError NurseryException m
=> Header
-> XRef
-> Nursery m NurseryState
nurseryState h xref
= do info <- getInfo xref
root <- getRoot xref
pages <- getPages xref root
let initState = NurseryState
{ nurseryHeader = h
, nurseryXRef = xref
, nurseryRoot = root
, nurseryInfo = info
, nurseryPages = pages
}
return initState
--------------------------------------------------------------------------------
serveInfo :: Monad m => NurseryState -> Nursery m (NResp, NurseryState)
serveInfo s = return (RInfo info, s)
where
info = nurseryInfo s
--------------------------------------------------------------------------------
serveHeader :: Monad m => NurseryState -> Nursery m (NResp, NurseryState)
serveHeader s = return (RHeader header, s)
where
header = nurseryHeader s
--------------------------------------------------------------------------------
servePages :: Monad m => NurseryState -> Nursery m (NResp, NurseryState)
servePages s = return (RPages pages, s)
where
pages = nurseryPages s
--------------------------------------------------------------------------------
serveResolve :: MonadError NurseryException m
=> NurseryState
-> Reference
-> Nursery m (NResp, NurseryState)
serveResolve s ref
= do obj <- resolveObject xref ref
return (RResolve obj, s)
where
xref = nurseryXRef s
--------------------------------------------------------------------------------
serveLoadStream :: MonadError NurseryException m
=> NurseryState
-> Stream
-> Nursery m (NResp, NurseryState)
serveLoadStream s stream
= do bs <- loadStream xref stream
return (RBinaryLazy bs, s)
where
xref = nurseryXRef s
--------------------------------------------------------------------------------
loadStream :: MonadError NurseryException m
=> XRef
-> Stream
-> Nursery m BL.ByteString
loadStream xref stream
= do mLen <- dict ^!? dictKey "Length"
. act (resolveIfRef xref)
. _Number
. _Natural
case mLen of
Nothing
-> throwError NurseryInvalidStreamObject
Just len
-> do driveSeek pos
bs <- driveGetLazy $ fromIntegral len
let filt = dict ^? dictKey "Filter" . _Name
case filt of
Nothing -> return bs
Just x | "FlateDecode" <- x -> return $ decompress bs
| otherwise -> return $ bs
where
dict = stream ^. streamDict
pos = stream ^. streamPos
--------------------------------------------------------------------------------
serveReferences :: Monad m => NurseryState -> Nursery m (NResp, NurseryState)
serveReferences s
= return (RReferences rs, s)
where
rs = M.keys $ xrefUTable $ nurseryXRef s
--------------------------------------------------------------------------------
getHeader :: MonadError NurseryException m => Nursery m Header
getHeader
= do hE <- driveParse 8 parseHeader
case hE of
Left e -> throwError $ NurseryParsingException Nothing e
Right h -> return h
--------------------------------------------------------------------------------
getInfo :: MonadError NurseryException m => XRef -> Nursery m Dictionary
getInfo xref = perform action trailer
where
trailer = xrefTrailer xref
action = dictKey "Info"
. _Ref
. act (resolveObject xref)
. _Dict
--------------------------------------------------------------------------------
getRoot :: MonadError NurseryException m => XRef -> Nursery m Root
getRoot xref
= maybe (trailerRoot xref) (streamRoot xref) xstreamM
where
xstreamM = xrefStream xref
--------------------------------------------------------------------------------
trailerRoot :: MonadError NurseryException m => XRef -> Nursery m Root
trailerRoot xref
= do mR <- trailer ^!? action
case mR of
Nothing -> throwError NurseryRootNotFound
Just r -> return r
where
trailer = xrefTrailer xref
action
= dictKey "Root"
. _Ref
. act (resolveObject xref)
. _Dict
--------------------------------------------------------------------------------
streamRoot :: MonadError NurseryException m
=> XRef
-> XRefStream
-> Nursery m Root
streamRoot xref xstream
= do mR <- dict ^!? action
case mR of
Nothing -> throwError NurseryRootNotFound
Just r -> return r
where
dict = xrefStreamDict xstream
action
= dictKey "Root"
. _Ref
. act (resolveObject xref)
. _Dict
--------------------------------------------------------------------------------
getPages :: MonadError NurseryException m => XRef -> Root -> Nursery m Pages
getPages xref root
= do mP <- root ^!? action
case mP of
Nothing -> throwError NurseryPagesNotFound
Just p -> return p
where
action
= dictKey "Pages"
. _Ref
. act (resolveObject xref)
. _Dict
--------------------------------------------------------------------------------
resolveIfRef :: MonadError NurseryException m
=> XRef
-> Object
-> Nursery m Object
resolveIfRef xref (Ref i g) = resolveObject xref (i,g)
resolveIfRef _ obj = return obj
--------------------------------------------------------------------------------
resolveObject :: MonadError NurseryException m
=> XRef
-> Reference
-> Nursery m Object
resolveObject xref ref
= do driveTop
driveForward
loop (S.singleton ref) ref
where
entries = xrefUTable xref
loop visited cRef
= case M.lookup cRef entries of
Nothing
-> resolveCompressedObject xref ref
Just e
-> do let offset = uObjOff e
driveSeek offset
r <- parsing cRef
let pRef = (r ^. _1, r ^. _2)
when (cRef /= pRef) $
throwError $ NurseryWrongObject cRef pRef
case r ^. _3 of
Ref nidx ngen
| S.member (nidx,ngen) visited
-> throwError $
NurseryCyclicDependency (nidx,ngen)
| otherwise
-> let nRef = (nidx,ngen)
nVisited = S.insert nRef visited in
loop nVisited nRef
obj -> return obj
parsing cRef
= driveParseObject bufferSize >>=
either (throwError . NurseryParsingException (Just cRef)) return
--------------------------------------------------------------------------------
resolveCompressedObject :: MonadError NurseryException m
=> XRef
-> Reference
-> Nursery m Object
resolveCompressedObject xref ref@(idx,gen)
= case M.lookup ref centries of
Nothing
-> throwError $ NurseryUnresolvedObject idx gen
Just cObj
-> let objsNum = cObjNum cObj
sRef = (objsNum, 0) in
do sObj <- resolveObject xref sRef
let mPos = sObj ^? _Stream
case mPos of
Nothing
-> throwError NurseryExpectedStreamObject
Just stream
-> do bs <- loadStream xref stream
o <- validateObjStm stream bs
lookupObjStm ref o
where
centries = xrefCTable xref
--------------------------------------------------------------------------------
validateObjStm :: MonadError NurseryException m
=> Stream
-> BL.ByteString
-> m ObjStm
validateObjStm stream bs
= maybe (throwError NurseryInvalidObjStm) return action
where
action
= do typ <- dict ^? dictKey "Type" . _Name
when (typ /= "ObjStm") Nothing
n <- dict ^? dictKey "N" . _Number . _Natural
first <- dict ^? dictKey "First" . _Number . _Natural
reg <- registery $ fromIntegral n
let extends = dict ^? dictKey "Extends" . _Ref
info = ObjStm
{ objStmCount = n
, objStmFirst = first
, objStmExtends = extends
, objStmOffset = pos
, objStmStream = bs
, objStmReg = reg
}
return info
registery n
= case PL.parse (parseRegistery n) bs of
PL.Done _ r -> Just r
_ -> Nothing
parseRegistery n
= execStateT (replicateM_ n step) M.empty
step = do lift skipSpace
num <- lift decimal
_ <- lift space
off <- lift decimal
modify' (M.insert num off)
dict = stream ^. streamDict
pos = stream ^. streamPos
--------------------------------------------------------------------------------
lookupObjStm :: MonadError NurseryException m
=> Reference
-> ObjStm
-> Nursery m Object
lookupObjStm (idx,_) stm
= case M.lookup (fromIntegral idx) reg of
Nothing
-> throwError $ NurseryUnresolvedObjectInObjStm idx
Just off
-> do let skipN = fromIntegral (first+off)
stream' = BL.drop skipN stream
case PL.parse parser stream' of
PL.Fail _ _ e
-> throwError $ NurseryParsingExceptionInObjStm e
PL.Done _ obj
-> return obj
where
parser = parseDict <|> parseArray
reg = objStmReg stm
stream = objStmStream stm
first = objStmFirst stm
--------------------------------------------------------------------------------
withNursery :: MonadError NurseryException m
=> Client' NReq NResp m a
-> Drive m a
withNursery user = nursery >>~ const user
--------------------------------------------------------------------------------
nurseryLoop :: Monad m
=> (NurseryState -> NReq -> Nursery m (NResp, NurseryState))
-> NurseryState
-> NReq
-> Nursery m r
nurseryLoop k s rq
= do (r, s') <- k s rq
rq' <- respond r
nurseryLoop k s' rq'
--------------------------------------------------------------------------------
-- Utilities
--------------------------------------------------------------------------------
liftError :: MonadError NurseryException m => ExceptT XRefException m a -> m a
liftError action
= runExceptT action >>=
either (throwError . NurseryXRefException) return
--------------------------------------------------------------------------------
-- API
--------------------------------------------------------------------------------
nurseryGetInfo :: Monad m => Playground m Dictionary
nurseryGetInfo
= do RInfo info <- request RqInfo
return info
--------------------------------------------------------------------------------
nurseryGetHeader :: Monad m => Playground m Header
nurseryGetHeader
= do RHeader header <- request RqHeader
return header
--------------------------------------------------------------------------------
nurseryGetPages :: Monad m => Playground m Dictionary
nurseryGetPages
= do RPages pages <- request RqPages
return pages
--------------------------------------------------------------------------------
nurseryResolve :: Monad m => Reference -> Playground m Object
nurseryResolve ref
= do RResolve obj <- request $ RqResolve ref
return obj
--------------------------------------------------------------------------------
nurseryLoadStreamData :: Monad m => Stream -> Playground m BL.ByteString
nurseryLoadStreamData s
= do RBinaryLazy bs <- request $ RqLoadStreamData s
return bs
--------------------------------------------------------------------------------
nurseryGetReferences :: Monad m => Playground m [Reference]
nurseryGetReferences
= do RReferences rs <- request $ RqReferences
return rs
| erantapaa/rakhana | Data/Rakhana/Nursery.hs | bsd-3-clause | 18,119 | 0 | 21 | 5,470 | 3,708 | 1,869 | 1,839 | -1 | -1 |
{-# LANGUAGE NamedFieldPuns #-}
module CmdLine where
import Data.List (intersperse)
import System.Console.GetOpt
import Text.PrettyPrint
--------------------------------------------------------------------------------
-- Command line interaction
class PShow a where
pshow :: a -> String
class PRead a where
pread :: String -> a
data Format = Markdown | ASCII
deriving (Show, Read, Eq)
instance PShow Format where
pshow s = case s of
Markdown -> "markdown"
ASCII -> "ascii"
instance PRead Format where
pread s = case s of
"markdown" -> Markdown
"ascii" -> ASCII
_ -> error $ "Cannot parse " ++ s
data Entries = Min | All
deriving (Show, Read, Eq)
instance PShow Entries where
pshow s = case s of
Min -> "min-entries"
All -> "all-entries"
instance PRead Entries where
pread s = case s of
"min-entries" -> Min
"all-entries" -> All
_ -> error $ "Cannot parse " ++ s
-- Sort order
data Sort = File | Func | Line | Result | Entry
deriving (Eq, Read, Show)
instance PShow Sort where
pshow s = case s of
File -> "file"
Func -> "function"
Line -> "line"
Result -> "result"
Entry -> "entry"
instance PRead Sort where
pread s = case s of
"file" -> File
"function" -> Func
"line" -> Line
"result" -> Result
"entry" -> Entry
_ -> error $
"No parse for " ++ s ++ " into a sort order."
data Opts = Opts
{ cbmc :: FilePath -- ^ CBMC executable. If not, assume it's in the
-- path.
, srcs :: [String] -- ^ C sources.
, incls :: [String] -- ^ Includes.
, function :: [String] -- ^ functions to analyze.
, cbmcOpts :: [String] -- ^ Remaining options
, format :: Format -- ^ Output format
, timeout :: Int -- ^ Timeout bound in seconds
, asserts :: Bool -- ^ Show the assertions in the generated report?
, coverage :: Entries -- ^ Minimal set coverage or run from all entries?
, outfile :: Maybe FilePath -- ^ A file to write the generated table
, sort :: Sort -- ^ Column to sort the generated table.
, threads :: Integer
, help :: Bool
-- Internally used options
, toExec :: FilePath -- ^ Timeout executable
} deriving (Eq, Read, Show)
defaultOpts :: Opts
defaultOpts = Opts
{ cbmc = "cbmc"
, srcs = []
, incls = []
, function = []
, cbmcOpts = []
, format = ASCII
, timeout = 0 -- No timeout
, asserts = True
, coverage = Min
, outfile = Nothing -- default: standard out
, sort = File
, threads = 2
, help = False
, toExec = ""
}
options :: [OptDescr (Opts -> Opts)]
options =
[ Option "c" ["cbmc"] cbmcOpt cbmcHlp
, Option "f" ["function"] funcOpt funcHlp
, Option "s" ["src"] srcOpt srcHlp
, Option "I" ["incl"] inclOpt inclHlp
, Option "m" ["format"] fmtOpt fmtHlp
, Option "t" ["timeout"] timeOpt timeHlp
, Option "n" ["no-asserts"] astOpt astHlp
, Option "e" ["entries"] entOpt entHlp
, Option "o" ["outfile"] outOpt outHlp
, Option "r" ["sort"] sortOpt sortHlp
, Option "d" ["threads"] thrdOpt thrdHlp
, Option "h" ["help"] helpOpt helpHlp
]
where
cbmcOpt = ReqArg (\cbmc opts -> opts {cbmc}) "PATH"
cbmcHlp = unwords
[ "Optional path to the CBMC executable."
, "If no path is provided, it is assumed"
, "to exist in your $PATH." ]
funcOpt = ReqArg (\f opts -> opts {function = f:function opts}) "SYMBOL"
funcHlp = unwords
[ "Entry functions for analysis."
, "Multiple entry points may be given"
, "as --function=f0 --function=f1 ..."
, "If no functions are given, function"
, "symbols are parsed from the C sources."
, "Model-checking from each function is"
, "run in parallel (modulo the number of"
, "cores available."
]
entOpt = ReqArg (\ent opts -> opts {coverage = pread ent})
(pshow Min ++ "|" ++ pshow All)
entHlp = unwords
[ "Which entry functions to test with"
, "for claims that are reachable from"
, "more than one entry point."
, "min-entries finds approximates a minimum"
, "number of required entry points using a"
, "depth-first greedy set-cover approximation."
, "all-entries uses all functions as entries. If a claim"
, "fails from any entry point, False is reported"
, "for the claim (and the entry function used)."
, "Default: min-entries."
]
srcOpt = ReqArg (\src opts -> opts {srcs = src:srcs opts}) "PATH"
srcHlp = unwords
[ "PATH to C source file."
, "Multiple sources may be provided."
]
inclOpt = ReqArg (\incl opts -> opts {incls = incl:incls opts}) "PATH"
inclHlp = unwords
[ "PATH to includes. "
, "Multiple includes may be provided."
, "PATH should NOT include the preceding -I."
]
fmtOpt = ReqArg (\fmt opts -> opts {format = pread fmt})
(pshow ASCII ++ "|" ++ pshow Markdown)
fmtHlp = unwords
[ "Output format of table."
, "Default: ASCII format."]
timeOpt = ReqArg (\t opts -> opts {timeout = read t}) "INT"
timeHlp = unwords
[ "Timeout bound for CBMC"
, "(in seconds)." ]
astOpt = NoArg (\opts -> opts {asserts = False})
astHlp = unwords
[ "Do not show the proposed assertion"
, "expressions in the generated report."
, "Default: False."
]
outOpt = ReqArg (\fp opts -> opts {outfile = Just fp}) "PATH"
outHlp = unwords
[ "Path to write generated table."
, "Default: stdout."
]
sortOpt = ReqArg (\srt opts -> opts {sort = pread srt})
( concat
$ intersperse "|"
$ map pshow [File, Func, Line, Result, Entry]
)
sortHlp = unwords
[ "Column to sort table (low-to-high)."
, "For each claim: file name, function,"
, "line number, entry point, or result"
, "(true or false). Default: file."
]
thrdOpt = ReqArg (\n opts -> opts {threads = read n}) "INT"
thrdHlp = unwords
[ "Specify the maximum number of threads to issue."
, "There is no problem with specifying more threads"
, "than available cores, but note that each thread"
, "spawns a model-checker, which may consume enough"
, "memory to cause your system to thrash."
]
helpOpt = NoArg (const defaultOpts {help = True})
helpHlp = ""
parseArgs :: [String] -> Either [String] Opts
parseArgs args =
case getOpt RequireOrder options args of
(opts,toCbmc,[]) -> Right $ foldl (flip id) (startOpts toCbmc) opts
(_,_,errs) -> Left errs
where
startOpts cbmcOpts = defaultOpts {cbmcOpts}
header :: String
header = unlines
[ ""
, "-------------------------------------------------------------"
, "| cbmc-reporter is a driver for the CBMC model-checker |"
, "| <http://www.cprover.org/cbmc/> for use with library code. |"
, "| |"
, "| Licence : BSD3 |"
, "| Maintainer: Lee Pike (leepike@galois.com) |"
, "| |"
, "| Usage : cbmc-report [OPTION...] -- [CBMC OPTIONS ...] |"
, "| (All CBMC options must come after cbmc-report options). |"
, "-------------------------------------------------------------"
]
--------------------------------------------------------------------------------
-- A better usageInfo formatter.
myUsageInfo :: String
myUsageInfo = renderStyle style' $
text header
$$ empty
$$ text "USAGE:"
$$ vcat (map docOpt options)
$$ text "EXAMPLES:"
$+$ space $$ examples
$+$ space
where
style' = style {lineLength = 70}
docOpt (Option shrt [long] req hlp) =
nest 2 $ text "-" <> text shrt <> args req space <> comma
<+> text "--" <> text long <> args req equals
$$ nest 4 (takeup 0 empty (words hlp)) $+$ space
docOpt _ = empty
ll = lineLength style'
-- Take words up to lineLength words, keeping the remainder.
takeup :: Int -> Doc -> [String] -> Doc
takeup _ acc [] = acc
takeup n acc (wrd:wrds) =
let len = n + length wrd + 1 in
-- Can't fit anymore words on this line.
if len >= ll then acc $$ takeup 0 empty (wrd:wrds)
else takeup len (acc <+> text wrd) wrds
args req sp = case req of
(ReqArg _ arg) -> sp <> text arg
(NoArg _) -> empty
-- OptArg ... if we add that
_ -> empty
examples =
nest 2 (text "> cbmc-reporter -f foo -f bar -s s0.c -s s1.c -I hdr.h -- --win64")
$$ nest 4 (takeup 0 empty $ words explain)
where
explain = unwords
[ "Using foo and bar as entry points, analyze s0 and s1 with"
, "header hdr.h. Pass an an argument to CBMC --win64."
]
| VCTLabs/cbmc-reporter | src/CmdLine.hs | bsd-3-clause | 9,177 | 0 | 16 | 2,907 | 2,121 | 1,169 | 952 | 219 | 6 |
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import qualified GitHub as GH
main :: IO ()
main = do
possibleUser <- GH.executeRequest' $ GH.userInfoForR "phadej"
print possibleUser
| jwiegley/github | samples/Users/ShowUser2.hs | bsd-3-clause | 205 | 0 | 10 | 38 | 55 | 30 | 25 | 7 | 1 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
{- |
Module : $Header$
Copyright : (c) Klaus Hartke, Uni Bremen 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : experimental
Portability : non-portable (MPTC-FD)
-}
module Kripke where
import Data.Set as Set
{- ----------------------------------------------------------------------------
Kripke Structure
---------------------------------------------------------------------------- -}
class Kripke k a s | k -> a s where
states :: k -> Set s
initial :: k -> Set s
next :: k -> s -> Set s
labels :: k -> s -> Set a
-- ----------------------------------------------------------------------------
| keithodulaigh/Hets | Temporal/Kripke.hs | gpl-2.0 | 752 | 0 | 9 | 135 | 91 | 51 | 40 | 8 | 0 |
{-|
Module : Idris.Core.WHNF
Description : Reduction to Weak Head Normal Form
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE PatternGuards #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.Core.WHNF(whnf, whnfArgs, WEnv) where
import Idris.Core.CaseTree
import Idris.Core.Evaluate hiding (quote)
import qualified Idris.Core.Evaluate as Evaluate
import Idris.Core.TT
import Debug.Trace
-- | A stack entry consists of a term and the environment it is to be
-- evaluated in (i.e. it's a thunk)
type StackEntry = (Term, WEnv)
data WEnv = WEnv Int -- number of free variables
[(Term, WEnv)]
deriving Show
type Stack = [StackEntry]
-- | A WHNF is a top level term evaluated in the empty environment. It is
-- always headed by either an irreducible expression, i.e. a constructor,
-- a lambda, a constant, or a postulate
--
-- Every 'Term' or 'Type' in this structure is associated with the
-- environment it was encountered in, so that when we quote back to a term
-- we get the substitutions right.
data WHNF = WDCon Int Int Bool Name (Term, WEnv) -- ^ data constructor
| WTCon Int Int Name (Type, WEnv) -- ^ type constructor
| WPRef Name (Term, WEnv) -- ^irreducible global (e.g. a postulate)
| WV Int
| WBind Name (Binder (Term, WEnv)) (Term, WEnv)
| WApp WHNF (Term, WEnv)
| WConstant Const
| WProj WHNF Int
| WType UExp
| WUType Universe
| WErased
| WImpossible
-- NOTE: These aren't yet ready to be used in practice - there's still a
-- bug or two in the handling of de Bruijn indices.
-- | Reduce a term to weak head normal form.
whnf :: Context -> Env -> Term -> Term
-- whnf ctxt env tm = let res = whnf' ctxt env tm in
-- trace (show tm ++ "\n==>\n" ++ show res ++ "\n") res
whnf ctxt env tm =
inlineSmall ctxt env $ -- reduce small things in body. This is primarily
-- to get rid of any noisy "assert_smaller/assert_total"
-- and evaluate any simple operators, which makes things
-- easier to read.
whnf' ctxt env tm
whnf' ctxt env tm =
quote (do_whnf ctxt (map finalEntry env) (finalise tm))
-- | Reduce a type so that all arguments are expanded
whnfArgs :: Context -> Env -> Term -> Term
whnfArgs ctxt env tm = inlineSmall ctxt env $ finalise (whnfArgs' ctxt env tm)
whnfArgs' ctxt env tm
= case whnf' ctxt env tm of
-- The assumption is that de Bruijn indices refer to local things
-- (so not in the external environment) so we need to instantiate
-- the name
Bind n b@(Pi rig _ ty _) sc ->
Bind n b (whnfArgs' ctxt ((n, rig, b):env)
(subst n (P Bound n ty) sc))
res -> tm
finalEntry :: (Name, RigCount, Binder (TT Name)) -> (Name, RigCount, Binder (TT Name))
finalEntry (n, r, b) = (n, r, fmap finalise b)
do_whnf :: Context -> Env -> Term -> WHNF
do_whnf ctxt genv tm = eval (WEnv 0 []) [] tm
where
eval :: WEnv -> Stack -> Term -> WHNF
eval wenv@(WEnv d env) stk (V i)
| i < length env = let (tm, env') = env !! i in
eval env' stk tm
| otherwise = WV i
eval wenv@(WEnv d env) stk (Bind n (Let t v) sc)
= eval (WEnv d ((v, wenv) : env)) stk sc
eval (WEnv d env) ((tm, tenv) : stk) (Bind n b@(Lam _ _) sc)
= eval (WEnv d ((tm, tenv) : env)) stk sc
eval wenv@(WEnv d env) stk (Bind n b sc) -- stk must be empty if well typed
=let n' = uniqueName n (map fstEnv genv) in
WBind n' (fmap (\t -> (t, wenv)) b) (sc, WEnv (d + 1) env)
eval env stk (P nt n ty)
| Just (Let t v) <- lookupBinder n genv = eval env stk v
eval env stk (P nt n ty) = apply env nt n ty stk
eval env stk (App _ f a) = eval env ((a, env) : stk) f
eval env stk (Constant c) = unload (WConstant c) stk
-- Should never happen in compile time code (for now...)
eval env stk (Proj tm i) = unload (WProj (eval env [] tm) i) stk
eval env stk Erased = unload WErased stk
eval env stk Impossible = unload WImpossible stk
eval env stk (Inferred tm) = eval env stk tm
eval env stk (TType u) = unload (WType u) stk
eval env stk (UType u) = unload (WUType u) stk
apply :: WEnv -> NameType -> Name -> Type -> Stack -> WHNF
apply env nt n ty stk
= let wp = case nt of
DCon t a u -> WDCon t a u n (ty, env)
TCon t a -> WTCon t a n (ty, env)
Ref -> WPRef n (ty, env)
_ -> WPRef n (ty, env)
in
if not (tcReducible n ctxt)
then unload wp stk
else case lookupDefAccExact n False ctxt of
Just (CaseOp ci _ _ _ _ cd, acc)
| acc == Public || acc == Hidden ->
let (ns, tree) = cases_compiletime cd in
case evalCase env ns tree stk of
Just w -> w
Nothing -> unload wp stk
Just (Operator _ i op, acc) ->
if i <= length stk
then case runOp env op (take i stk) (drop i stk) of
Just v -> v
Nothing -> unload wp stk
else unload wp stk
_ -> unload wp stk
unload :: WHNF -> Stack -> WHNF
unload f [] = f
unload f (a : as) = unload (WApp f a) as
runOp :: WEnv -> ([Value] -> Maybe Value) -> Stack -> Stack -> Maybe WHNF
runOp env op stk rest
= do vals <- mapM tmtoValue stk
case op vals of
Just (VConstant c) -> Just $ unload (WConstant c) rest
-- Operators run on values, so we have to convert back
-- and forth. This is pretty ugly, but operators that
-- aren't run on constants are themselves pretty ugly
-- (it's prim__believe_me and prim__syntacticEq, for
-- example) so let's not worry too much...
-- We will need to deal with believe_me before dropping this
-- into the type checker, though.
Just val -> Just $ eval env rest (quoteTerm val)
_ -> Nothing
tmtoValue :: (Term, WEnv) -> Maybe Value
tmtoValue (tm, tenv)
= case eval tenv [] tm of
WConstant c -> Just (VConstant c)
_ -> let tm' = quoteEnv tenv tm in
Just (toValue ctxt [] tm')
evalCase :: WEnv -> [Name] -> SC -> Stack -> Maybe WHNF
evalCase wenv@(WEnv d env) ns tree args
| length ns > length args = Nothing
| otherwise = let args' = take (length ns) args
rest = drop (length ns) args in
do (tm, amap) <- evalTree wenv (zip ns args') tree
let wtm = pToVs (map fst amap) tm
Just $ eval (WEnv d (map snd amap)) rest wtm
evalTree :: WEnv -> [(Name, (Term, WEnv))] -> SC ->
Maybe (Term, [(Name, (Term, WEnv))])
evalTree env amap (STerm tm) = Just (tm, amap)
evalTree env amap (Case _ n alts)
= case lookup n amap of
Just (tm, tenv) -> findAlt env amap
(deconstruct (eval tenv [] tm) []) alts
_ -> Nothing
evalTree _ _ _ = Nothing
deconstruct :: WHNF -> Stack -> (WHNF, Stack)
deconstruct (WApp f arg) stk = deconstruct f (arg : stk)
deconstruct t stk = (t, stk)
findAlt :: WEnv -> [(Name, (Term, WEnv))] -> (WHNF, Stack) ->
[CaseAlt] ->
Maybe (Term, [(Name, (Term, WEnv))])
findAlt env amap (WDCon tag _ _ _ _, args) alts
| Just (ns, sc) <- findTag tag alts
= let amap' = updateAmap (zip ns args) amap in
evalTree env amap' sc
| Just sc <- findDefault alts
= evalTree env amap sc
findAlt env amap (WConstant c, []) alts
| Just sc <- findConst c alts
= evalTree env amap sc
| Just sc <- findDefault alts
= evalTree env amap sc
findAlt _ _ _ _ = Nothing
findTag :: Int -> [CaseAlt] -> Maybe ([Name], SC)
findTag i [] = Nothing
findTag i (ConCase n j ns sc : xs) | i == j = Just (ns, sc)
findTag i (_ : xs) = findTag i xs
findDefault :: [CaseAlt] -> Maybe SC
findDefault [] = Nothing
findDefault (DefaultCase sc : xs) = Just sc
findDefault (_ : xs) = findDefault xs
findConst c [] = Nothing
findConst c (ConstCase c' v : xs) | c == c' = Just v
findConst (AType (ATInt ITNative)) (ConCase n 1 [] v : xs) = Just v
findConst (AType ATFloat) (ConCase n 2 [] v : xs) = Just v
findConst (AType (ATInt ITChar)) (ConCase n 3 [] v : xs) = Just v
findConst StrType (ConCase n 4 [] v : xs) = Just v
findConst (AType (ATInt ITBig)) (ConCase n 6 [] v : xs) = Just v
findConst (AType (ATInt (ITFixed ity))) (ConCase n tag [] v : xs)
| tag == 7 + fromEnum ity = Just v
findConst c (_ : xs) = findConst c xs
updateAmap newm amap
= newm ++ filter (\ (x, _) -> not (elem x (map fst newm))) amap
quote :: WHNF -> Term
quote (WDCon t a u n (ty, env)) = P (DCon t a u) n (quoteEnv env ty)
quote (WTCon t a n (ty, env)) = P (TCon t a) n (quoteEnv env ty)
quote (WPRef n (ty, env)) = P Ref n (quoteEnv env ty)
quote (WV i) = V i
quote (WBind n b (sc, env)) = Bind n (fmap (\ (t, env) -> quoteEnv env t) b)
(quoteEnv env sc)
quote (WApp f (a, env)) = App Complete (quote f) (quoteEnv env a)
quote (WConstant c) = Constant c
quote (WProj t i) = Proj (quote t) i
quote (WType u) = TType u
quote (WUType u) = UType u
quote WErased = Erased
quote WImpossible = Impossible
quoteEnv :: WEnv -> Term -> Term
quoteEnv (WEnv d ws) tm = qe' d ws tm
where
-- d is number of free variables in the external environment
-- (all bound in the scope of 'ws')
qe' d ts (V i)
| (i - d) < length ts && (i - d) >= 0
= let (tm, env) = ts !! (i - d) in
quoteEnv env tm
| otherwise = V i
qe' d ts (Bind n b sc)
= Bind n (fmap (qe' d ts) b) (qe' (d + 1) ts sc)
qe' d ts (App c f a)
= App c (qe' d ts f) (qe' d ts a)
qe' d ts (P nt n ty) = P nt n (qe' d ts ty)
qe' d ts (Proj tm i) = Proj (qe' d ts tm) i
qe' d ts tm = tm
| jmitchell/Idris-dev | src/Idris/Core/WHNF.hs | bsd-3-clause | 10,764 | 0 | 19 | 3,868 | 3,954 | 2,019 | 1,935 | 188 | 45 |
{-# LANGUAGE ScopedTypeVariables #-}
-- Test #246
module Main where
import Control.Exception
data T = T { x :: Bool, y :: Bool }
f (T { y=True, x=True }) = "Odd"
f _ = "OK"
g (T { x=True, y=True }) = "Odd2"
g _ = "Odd3"
funny = T { x = undefined, y = False }
main = do { print (f funny) -- Should work, because we test
-- y first, which fails, and falls
-- through to "OK"
; Control.Exception.catch
(print (g funny)) -- Should fail, because we test
(\(_::SomeException) -> print "caught") -- x first, and hit "undefined"
}
| sdiehl/ghc | testsuite/tests/deSugar/should_run/T246.hs | bsd-3-clause | 697 | 0 | 11 | 279 | 185 | 108 | 77 | 13 | 1 |
-- | Pretty printing of graphs.
module GraphPpr (
dumpGraph,
dotGraph
)
where
import GraphBase
import Outputable
import Unique
import UniqSet
import UniqFM
import Data.List
import Data.Maybe
-- | Pretty print a graph in a somewhat human readable format.
dumpGraph
:: (Outputable k, Outputable cls, Outputable color)
=> Graph k cls color -> SDoc
dumpGraph graph
= text "Graph"
$$ (vcat $ map dumpNode $ eltsUFM $ graphMap graph)
dumpNode
:: (Outputable k, Outputable cls, Outputable color)
=> Node k cls color -> SDoc
dumpNode node
= text "Node " <> ppr (nodeId node)
$$ text "conflicts "
<> parens (int (sizeUniqSet $ nodeConflicts node))
<> text " = "
<> ppr (nodeConflicts node)
$$ text "exclusions "
<> parens (int (sizeUniqSet $ nodeExclusions node))
<> text " = "
<> ppr (nodeExclusions node)
$$ text "coalesce "
<> parens (int (sizeUniqSet $ nodeCoalesce node))
<> text " = "
<> ppr (nodeCoalesce node)
$$ space
-- | Pretty print a graph in graphviz .dot format.
-- Conflicts get solid edges.
-- Coalescences get dashed edges.
dotGraph
:: ( Uniquable k
, Outputable k, Outputable cls, Outputable color)
=> (color -> SDoc) -- ^ What graphviz color to use for each node color
-- It's usually safe to return X11 style colors here,
-- ie "red", "green" etc or a hex triplet #aaff55 etc
-> Triv k cls color
-> Graph k cls color -> SDoc
dotGraph colorMap triv graph
= let nodes = eltsUFM $ graphMap graph
in vcat
( [ text "graph G {" ]
++ map (dotNode colorMap triv) nodes
++ (catMaybes $ snd $ mapAccumL dotNodeEdges emptyUniqSet nodes)
++ [ text "}"
, space ])
dotNode :: ( Uniquable k
, Outputable k, Outputable cls, Outputable color)
=> (color -> SDoc)
-> Triv k cls color
-> Node k cls color -> SDoc
dotNode colorMap triv node
= let name = ppr $ nodeId node
cls = ppr $ nodeClass node
excludes
= hcat $ punctuate space
$ map (\n -> text "-" <> ppr n)
$ uniqSetToList $ nodeExclusions node
preferences
= hcat $ punctuate space
$ map (\n -> text "+" <> ppr n)
$ nodePreference node
expref = if and [isEmptyUniqSet (nodeExclusions node), null (nodePreference node)]
then empty
else text "\\n" <> (excludes <+> preferences)
-- if the node has been colored then show that,
-- otherwise indicate whether it looks trivially colorable.
color
| Just c <- nodeColor node
= text "\\n(" <> ppr c <> text ")"
| triv (nodeClass node) (nodeConflicts node) (nodeExclusions node)
= text "\\n(" <> text "triv" <> text ")"
| otherwise
= text "\\n(" <> text "spill?" <> text ")"
label = name <> text " :: " <> cls
<> expref
<> color
pcolorC = case nodeColor node of
Nothing -> text "style=filled fillcolor=white"
Just c -> text "style=filled fillcolor=" <> doubleQuotes (colorMap c)
pout = text "node [label=" <> doubleQuotes label <> space <> pcolorC <> text "]"
<> space <> doubleQuotes name
<> text ";"
in pout
-- | Nodes in the graph are doubly linked, but we only want one edge for each
-- conflict if the graphviz graph. Traverse over the graph, but make sure
-- to only print the edges for each node once.
dotNodeEdges
:: ( Uniquable k
, Outputable k, Outputable cls, Outputable color)
=> UniqSet k
-> Node k cls color
-> (UniqSet k, Maybe SDoc)
dotNodeEdges visited node
| elementOfUniqSet (nodeId node) visited
= ( visited
, Nothing)
| otherwise
= let dconflicts
= map (dotEdgeConflict (nodeId node))
$ uniqSetToList
$ minusUniqSet (nodeConflicts node) visited
dcoalesces
= map (dotEdgeCoalesce (nodeId node))
$ uniqSetToList
$ minusUniqSet (nodeCoalesce node) visited
out = vcat dconflicts
$$ vcat dcoalesces
in ( addOneToUniqSet visited (nodeId node)
, Just out)
where dotEdgeConflict u1 u2
= doubleQuotes (ppr u1) <> text " -- " <> doubleQuotes (ppr u2)
<> text ";"
dotEdgeCoalesce u1 u2
= doubleQuotes (ppr u1) <> text " -- " <> doubleQuotes (ppr u2)
<> space <> text "[ style = dashed ];"
| spacekitteh/smcghc | compiler/utils/GraphPpr.hs | bsd-3-clause | 5,238 | 0 | 22 | 2,122 | 1,304 | 636 | 668 | 113 | 3 |
{-# OPTIONS_JHC -fno-prelude -fffi #-}
module System.Mem where
import Jhc.Prim.IO
foreign import ccall safe "hs_perform_gc" performGC :: IO ()
| m-alvarez/jhc | lib/jhc/System/Mem.hs | mit | 146 | 0 | 7 | 22 | 32 | 19 | 13 | 4 | 0 |
{-# LANGUAGE OverlappingInstances #-}
module C where
import A
import B
class Class1 a => Class2 a
instance Class2 B
| ryantm/ghc | testsuite/tests/ghci/prog007/C.hs | bsd-3-clause | 120 | 0 | 6 | 24 | 32 | 17 | 15 | -1 | -1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE UnboxedTuples #-}
module UniqSupply (
-- * Main data type
UniqSupply, -- Abstractly
-- ** Operations on supplies
uniqFromSupply, uniqsFromSupply, -- basic ops
takeUniqFromSupply,
mkSplitUniqSupply,
splitUniqSupply, listSplitUniqSupply,
-- * Unique supply monad and its abstraction
UniqSM, MonadUnique(..),
-- ** Operations on the monad
initUs, initUs_,
lazyThenUs, lazyMapUs,
) where
import Unique
import FastTypes
import GHC.IO
import MonadUtils
import Control.Monad
{-
************************************************************************
* *
\subsection{Splittable Unique supply: @UniqSupply@}
* *
************************************************************************
-}
-- | A value of type 'UniqSupply' is unique, and it can
-- supply /one/ distinct 'Unique'. Also, from the supply, one can
-- also manufacture an arbitrary number of further 'UniqueSupply' values,
-- which will be distinct from the first and from all others.
data UniqSupply
= MkSplitUniqSupply FastInt -- make the Unique with this
UniqSupply UniqSupply
-- when split => these two supplies
mkSplitUniqSupply :: Char -> IO UniqSupply
-- ^ Create a unique supply out of thin air. The character given must
-- be distinct from those of all calls to this function in the compiler
-- for the values generated to be truly unique.
splitUniqSupply :: UniqSupply -> (UniqSupply, UniqSupply)
-- ^ Build two 'UniqSupply' from a single one, each of which
-- can supply its own 'Unique'.
listSplitUniqSupply :: UniqSupply -> [UniqSupply]
-- ^ Create an infinite list of 'UniqSupply' from a single one
uniqFromSupply :: UniqSupply -> Unique
-- ^ Obtain the 'Unique' from this particular 'UniqSupply'
uniqsFromSupply :: UniqSupply -> [Unique] -- Infinite
-- ^ Obtain an infinite list of 'Unique' that can be generated by constant splitting of the supply
takeUniqFromSupply :: UniqSupply -> (Unique, UniqSupply)
-- ^ Obtain the 'Unique' from this particular 'UniqSupply', and a new supply
mkSplitUniqSupply c
= case fastOrd (cUnbox c) `shiftLFastInt` _ILIT(24) of
mask -> let
-- here comes THE MAGIC:
-- This is one of the most hammered bits in the whole compiler
mk_supply
-- NB: Use unsafeInterleaveIO for thread-safety.
= unsafeInterleaveIO (
genSym >>= \ u_ -> case iUnbox u_ of { u -> (
mk_supply >>= \ s1 ->
mk_supply >>= \ s2 ->
return (MkSplitUniqSupply (mask `bitOrFastInt` u) s1 s2)
)})
in
mk_supply
foreign import ccall unsafe "genSym" genSym :: IO Int
splitUniqSupply (MkSplitUniqSupply _ s1 s2) = (s1, s2)
listSplitUniqSupply (MkSplitUniqSupply _ s1 s2) = s1 : listSplitUniqSupply s2
uniqFromSupply (MkSplitUniqSupply n _ _) = mkUniqueGrimily (iBox n)
uniqsFromSupply (MkSplitUniqSupply n _ s2) = mkUniqueGrimily (iBox n) : uniqsFromSupply s2
takeUniqFromSupply (MkSplitUniqSupply n s1 _) = (mkUniqueGrimily (iBox n), s1)
{-
************************************************************************
* *
\subsubsection[UniqSupply-monad]{@UniqSupply@ monad: @UniqSM@}
* *
************************************************************************
-}
-- | A monad which just gives the ability to obtain 'Unique's
newtype UniqSM result = USM { unUSM :: UniqSupply -> (# result, UniqSupply #) }
instance Monad UniqSM where
return = returnUs
(>>=) = thenUs
(>>) = thenUs_
instance Functor UniqSM where
fmap f (USM x) = USM (\us -> case x us of
(# r, us' #) -> (# f r, us' #))
instance Applicative UniqSM where
pure = returnUs
(USM f) <*> (USM x) = USM $ \us -> case f us of
(# ff, us' #) -> case x us' of
(# xx, us'' #) -> (# ff xx, us'' #)
(*>) = thenUs_
-- | Run the 'UniqSM' action, returning the final 'UniqSupply'
initUs :: UniqSupply -> UniqSM a -> (a, UniqSupply)
initUs init_us m = case unUSM m init_us of { (# r, us #) -> (r,us) }
-- | Run the 'UniqSM' action, discarding the final 'UniqSupply'
initUs_ :: UniqSupply -> UniqSM a -> a
initUs_ init_us m = case unUSM m init_us of { (# r, _ #) -> r }
{-# INLINE thenUs #-}
{-# INLINE lazyThenUs #-}
{-# INLINE returnUs #-}
{-# INLINE splitUniqSupply #-}
-- @thenUs@ is where we split the @UniqSupply@.
liftUSM :: UniqSM a -> UniqSupply -> (a, UniqSupply)
liftUSM (USM m) us = case m us of (# a, us' #) -> (a, us')
instance MonadFix UniqSM where
mfix m = USM (\us -> let (r,us') = liftUSM (m r) us in (# r,us' #))
thenUs :: UniqSM a -> (a -> UniqSM b) -> UniqSM b
thenUs (USM expr) cont
= USM (\us -> case (expr us) of
(# result, us' #) -> unUSM (cont result) us')
lazyThenUs :: UniqSM a -> (a -> UniqSM b) -> UniqSM b
lazyThenUs expr cont
= USM (\us -> let (result, us') = liftUSM expr us in unUSM (cont result) us')
thenUs_ :: UniqSM a -> UniqSM b -> UniqSM b
thenUs_ (USM expr) (USM cont)
= USM (\us -> case (expr us) of { (# _, us' #) -> cont us' })
returnUs :: a -> UniqSM a
returnUs result = USM (\us -> (# result, us #))
getUs :: UniqSM UniqSupply
getUs = USM (\us -> case splitUniqSupply us of (us1,us2) -> (# us1, us2 #))
-- | A monad for generating unique identifiers
class Monad m => MonadUnique m where
-- | Get a new UniqueSupply
getUniqueSupplyM :: m UniqSupply
-- | Get a new unique identifier
getUniqueM :: m Unique
-- | Get an infinite list of new unique identifiers
getUniquesM :: m [Unique]
-- This default definition of getUniqueM, while correct, is not as
-- efficient as it could be since it needlessly generates and throws away
-- an extra Unique. For your instances consider providing an explicit
-- definition for 'getUniqueM' which uses 'takeUniqFromSupply' directly.
getUniqueM = liftM uniqFromSupply getUniqueSupplyM
getUniquesM = liftM uniqsFromSupply getUniqueSupplyM
instance MonadUnique UniqSM where
getUniqueSupplyM = getUs
getUniqueM = getUniqueUs
getUniquesM = getUniquesUs
getUniqueUs :: UniqSM Unique
getUniqueUs = USM (\us -> case takeUniqFromSupply us of
(u,us') -> (# u, us' #))
getUniquesUs :: UniqSM [Unique]
getUniquesUs = USM (\us -> case splitUniqSupply us of
(us1,us2) -> (# uniqsFromSupply us1, us2 #))
-- {-# SPECIALIZE mapM :: (a -> UniqSM b) -> [a] -> UniqSM [b] #-}
-- {-# SPECIALIZE mapAndUnzipM :: (a -> UniqSM (b,c)) -> [a] -> UniqSM ([b],[c]) #-}
-- {-# SPECIALIZE mapAndUnzip3M :: (a -> UniqSM (b,c,d)) -> [a] -> UniqSM ([b],[c],[d]) #-}
lazyMapUs :: (a -> UniqSM b) -> [a] -> UniqSM [b]
lazyMapUs _ [] = returnUs []
lazyMapUs f (x:xs)
= f x `lazyThenUs` \ r ->
lazyMapUs f xs `lazyThenUs` \ rs ->
returnUs (r:rs)
| TomMD/ghc | compiler/basicTypes/UniqSupply.hs | bsd-3-clause | 7,329 | 0 | 28 | 1,981 | 1,557 | 850 | 707 | 102 | 1 |
module Records where
import Prelude ()
import BasicPrelude
import Data.Fixed (Centi)
import Control.Error (readMay)
import Data.Text.Encoding (encodeUtf8)
import Text.Blaze.Html (Html)
import Text.Blaze.Internal (MarkupM)
import Network.URI (URI)
import Text.Email.Validate (EmailAddress, validate)
import Data.Base58Address (RippleAddress)
import Data.Text.Buildable
import Database.SQLite.Simple (SQLData(SQLText,SQLInteger,SQLFloat))
import Database.SQLite.Simple.FromRow (FromRow(..), field, fieldWith)
import Database.SQLite.Simple.ToRow (ToRow(..))
import Database.SQLite.Simple.ToField (ToField(..), toField)
import Database.SQLite.Simple.FromField (fieldData, ResultError(ConversionFailed))
import Database.SQLite.Simple.Ok (Ok(Ok, Errors))
import Text.Blaze.Html.Renderer.Text (renderHtmlBuilder)
s :: (IsString s) => String -> s
s = fromString
serviceFee :: Int
serviceFee = 2
toDbl :: (Real a) => a -> Double
toDbl = realToFrac
baseDepositLimit :: Centi
baseDepositLimit = 150
depositMaxLimit :: Centi
depositMaxLimit = 900
quoteLimit :: Centi
quoteLimit = 100
instance Buildable (MarkupM a) where
build = renderHtmlBuilder . fmap (const ())
instance Buildable URI where
build = build . show
instance ToRow Deposit where
toRow (Deposit rid fn email tel ripple amnt complete) =
[toField rid, toField fn, toField (show email), toField tel, toField (show ripple), toField (toDbl amnt), toField complete]
instance FromRow Deposit where
fromRow = Deposit <$> field <*> field <*> fieldWith emailF <*> field <*> fieldWith rippleF <*> fieldWith dbl <*> field
where
emailF f = case fieldData f of
(SQLText t) -> case validate (encodeUtf8 t) of
Left e -> Errors [toException $ ConversionFailed "TEXT" "EmailAddress" e]
Right email -> Ok email
_ -> Errors [toException $ ConversionFailed "TEXT" "EmailAddress" "need a text"]
rippleF f = case fieldData f of
(SQLText t) -> case readMay (textToString t) of
Nothing -> Errors [toException $ ConversionFailed "TEXT" "RippleAddress" "invalid"]
Just ripple -> Ok ripple
_ -> Errors [toException $ ConversionFailed "TEXT" "RippleAddress" "need a text"]
dbl f = case fieldData f of
SQLInteger i -> Ok $ fromIntegral i
SQLFloat d -> Ok $ realToFrac d
_ -> Errors []
instance ToRow Quote where
toRow (Quote qid typ amnt dest email q a msg complete) =
[toField qid, toField typ, toField (toDbl amnt), toField (show dest), toField (show email), toField q, toField a, toField msg, toField complete]
instance (CanVerify a) => ToRow (Verification a) where
toRow (Verification item typ notes token) = [
toField itemId,
toField itemTable,
toField typ,
toField notes,
toField token
]
where
(itemId, itemTable) = verifyItemData item
instance ToField VerificationType where
toField = toField . show
instance ToField QuoteType where
toField = toField . show
class CanVerify a where
verifyItemData :: a -> (Int64, String)
instance CanVerify Deposit where
verifyItemData d = (depositId d, "deposits")
instance Eq Form where
(Form _ a1) == (Form _ a2) = a1 == a2
data Home = Home {
renderedDepositForm :: [Form],
renderedQuoteForm :: [Form],
depositLimit :: Centi,
foundDepositLimit :: Bool
}
data Form = Form {
formHtml :: Html,
formAction :: URI
}
data DepositSuccess = DepositSuccess {
successfulDeposit :: [Deposit],
higherVerificationNeeded :: Bool,
renderedStripeVerifyForm :: [Form],
homeLink :: URI
}
data Deposit = Deposit {
depositId :: Int64,
depositorFN :: Text,
depositorEmail :: EmailAddress,
depositorTel :: Text,
depositorRipple :: RippleAddress,
depositAmount :: Centi,
depositComplete :: Bool
}
data VerificationType = AutomatedPhoneVerification | ManualPhoneVerification | StripeVerification
deriving (Show, Read, Enum)
data Verification a = Verification {
verificationItem :: a,
verificationType :: VerificationType,
verificationNotes :: Maybe Text,
verificationAddrToken :: Maybe Text
}
data PlivoDeposit = PlivoDeposit {
plivoCode :: String
}
data QuoteType = InteracETransferQuote
deriving (Show, Read, Enum)
data Quote = Quote {
quoteId :: Word32, -- Because destination tag
quoteType :: QuoteType,
quoteAmount :: Centi,
quoteDestination :: EmailAddress,
quotorEmail :: EmailAddress,
quoteQuestion :: Text,
quoteAnswer :: Text,
quoteMessage :: Text,
quoteComplete :: Bool
}
data QuoteSuccess = QuoteSuccess {
successfulQuote :: [Quote],
quoteHomeLink :: URI
}
data PlivoConfig = PlivoConfig {
plivoAuthId :: String,
plivoAuthToken :: String,
plivoTel :: String
}
data Header = Header {
}
instance Monoid Header where
mempty = Header
mappend _ _ = Header
instance Eq Header where
_ == _ = False
header :: Header
header = Header
| singpolyma/rippleunion-interac | Records.hs | isc | 4,861 | 156 | 17 | 919 | 1,652 | 914 | 738 | 132 | 1 |
module Data where
import System.IO (Handle)
import Control.Monad.Reader (ReaderT, runReaderT)
import Control.Monad.IO.Class (liftIO)
import Database.Redis as R (Connection)
import Config (Config(..))
-- Convenience function to lift a computation from the IO Monad into the Bot monad.
-- Basically, it provides a type annotation (`lift` is too abstract).
io :: IO a -> Bot a
io = liftIO
data BotState = BotState {
handle :: Handle
, redisConn :: R.Connection
, config :: Config
, source :: String
}
type Bot = ReaderT BotState IO
runBot :: Bot a -> BotState -> IO a
runBot = runReaderT
| jdiez17/HaskellHawk | Data.hs | mit | 619 | 0 | 9 | 130 | 156 | 94 | 62 | 16 | 1 |
module Rebase.GHC.IO.FD
(
module GHC.IO.FD
)
where
import GHC.IO.FD
| nikita-volkov/rebase | library/Rebase/GHC/IO/FD.hs | mit | 71 | 0 | 5 | 12 | 23 | 16 | 7 | 4 | 0 |
-- | This is a convenience module that reexports it's sub-modules
--
-- License: MIT
-- Maintainer: Montez Fitzpatrick
-- Stability: experimental
module Nexpose.API where
| m15k/hs-nexpose-client | nexpose/src/Nexpose/API.hs | mit | 179 | 0 | 3 | 33 | 11 | 9 | 2 | 1 | 0 |
-- Copyright (c) 2013 Radek Micek
--
-- This file is distributed under the terms of the MIT License.
-- Usage: OptApplyEval unoptimized.js optimized.js
--
-- Optimizes functions __IDR__.APPLY0 and __IDR__.EVAL0 by converting
-- the large if-else statement to switch.
import Data.List
import Control.Applicative
import System.Environment
main :: IO ()
main = do
[input, output] <- take 2 <$> getArgs
ls <- lines <$> readFile input
let (before, apply0, eval0, after) = splitLines ls
writeFile output $ unlines $ concat
[ before
, procApply apply0
, procEval eval0
, after
]
splitLines :: [String] -> ([String], [String], [String], [String])
splitLines ls = (before, apply0, eval0, after)
where
(before, ls2) = break (== "__IDR__.APPLY0 = function(fn0,arg0){") ls
(apply0, ls3) = break (== "__IDR__.EVAL0 = function(arg0){") ls2
(eval0', ls4') = break (== "};") ls3 -- Line "};" belongs to eval0.
(eval0, after) = (eval0' ++ ["};"], tail ls4')
procApply :: [String] -> [String]
procApply = concatMap f
where
f l
| "if (e instanceof __IDRRT__.Con && " `isPrefixOf` l
= [ "if (e instanceof __IDRRT__.Con)"
, "switch (e.i) {"
, "case " ++ numStr ++ ":"
]
| "} else if (e instanceof __IDRRT__.Con && " `isPrefixOf` l
= ["case " ++ numStr ++ ":"]
| otherwise
= [l]
where
numStr = filter (`elem` ['0'..'9']) l
procEval :: [String] -> [String]
procEval = concatMap f
where
f l
| "if (e instanceof __IDRRT__.Con && " `isPrefixOf` l
= [ "if (!(e instanceof __IDRRT__.Con)) {"
, "return __var_0;"
, "} else"
, "switch (e.i) {"
, "case " ++ numStr ++ ":"
]
| "} else if (e instanceof __IDRRT__.Con && " `isPrefixOf` l
= ["case " ++ numStr ++ ":"]
| "} else if (true) {" `isPrefixOf` l
= ["default:"]
| otherwise
= [l]
where
numStr = filter (`elem` ['0'..'9']) l
| radekm/satviz | OptApplyEval.hs | mit | 1,992 | 0 | 11 | 543 | 552 | 309 | 243 | 47 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Text.Dot
main :: IO ()
main = renderToStdOut $ graph directed "example" $ do
a <- newNode
b <- newNode
c <- newNode
ranksame $ do
node_ a "a"
node_ c "c"
b <- node "b"
a --> b
c --> b
| NorfairKing/haphviz | examples/ranksame.hs | mit | 321 | 0 | 11 | 142 | 103 | 46 | 57 | 13 | 1 |
module MathTests where
import Test.QuickCheck
import Test.HUnit
import System.IO
import TestAbstract
import Math
powModTests = TestList
[
TestCase $ assertEqual "powMod 4 13 497 should return 445." 445 (powMod 4 13 497),
TestCase $ assertEqual "powMod 46565 0 961748941 should return 1." 1 (powMod 46565 0 961748941),
TestCase $ assertEqual "powMod 46565 240437235 961748941 should return 533506838." 533506838 (powMod 46565 240437235 961748941),
TestCase $ assertEqual "powMod 45621 419039293 301230039 should return 6285651." 6285651 (powMod 45621 419039293 301230039)
]
factorialTestCases = TestList
[
TestCase $ easyAssertEqual "factorial" factorial 0 1,
TestCase $ easyAssertEqual "factorial" factorial 2 2,
TestCase $ easyAssertEqual "factorial" factorial 3 6,
TestCase $ easyAssertEqual "factorial" factorial 1 1,
TestCase $ easyAssertEqual "factorial" factorial 20 2432902008176640000,
TestCase $ easyAssertEqual "factorial" factorial 25 15511210043330985984000000
]
roundFloatTestCases = TestList
[
TestCase $ easyAssertEqualTwoInputs "roundFloat" roundFloat 2.156486 4 2.1565,
TestCase $ easyAssertEqualTwoInputs "roundFloat" roundFloat 2.156486 0 2,
TestCase $ easyAssertEqualTwoInputs "roundFloat" roundFloat 2.156486 5 2.15649
]
testCases = TestList
[
powModTests,
factorialTestCases,
roundFloatTestCases
]
qc_powMod_exponentOne :: Integer -> Integer -> Property
qc_powMod_exponentOne base modulus =
modulus > 0 ==>
powMod base 1 modulus == base `mod` modulus
qc_powMod :: Integer -> Integer -> Integer -> Property
qc_powMod base theExponent modulus =
modulus > 0 && theExponent > 1 ==>
powMod base theExponent modulus == base ^ theExponent `mod` modulus
tests = runTestTT testCases
>> quickCheck qc_powMod_exponentOne
>> quickCheck qc_powMod
| Sobieck00/practice | utilities/nonvisualstudio/haskell/math/Tests.hs | mit | 1,949 | 0 | 11 | 420 | 448 | 230 | 218 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module StackIdePackage where
import Atom.CommandRegistry
import Atom.Decoration
import Atom.Marker
import Atom.Package
import Atom.TextEditor
import Control.Exception
import Control.Monad
import Data.IORef
import qualified Data.Text as T
import Data.Traversable
import GHCJS.Foreign
import GHCJS.Types
import GHCJS.Utils
import IdeSession.Types.Public
import StackIde
import StackIdeM
foreign import javascript unsafe
"atom.notifications.addError($1)" addError :: JSString -> IO ()
wrap :: IO () -> IO ()
wrap expr = catch expr handle
where
handle ex = addError (toJSString (show (ex :: SomeException)))
stackIdePackage :: Package
stackIdePackage = Package {
activate = onActivate
}
foreign import javascript unsafe
"$1.destroy()" js_destroy :: Marker -> IO ()
onActivate :: IO ()
onActivate = do
markersRef <- newIORef []
addCommand "atom-text-editor" "stack-ide-atom:source-errors" $ \editor -> wrap $ do
path <- getPath editor
let dir = T.dropWhileEnd (/= '/') path
print dir
sourceErrors <- runStackIde $ do
createSession dir
getSourceErrors
print sourceErrors
oldMarkers <- readIORef markersRef
void $ traverse js_destroy oldMarkers
newMarkers <- flip traverse sourceErrors $ \sourceError -> do
let (SourceError _ (ProperSpan (SourceSpan _ sx sy ex ey)) _) = sourceError
let range = rangeBetween (sx - 1) (sy - 1) (ex - 1) (ey - 1)
marker <- markBufferRange editor range
consoleLog marker
decoration <- decorateMarker editor marker "sia-error"
consoleLog $ jsDecoration decoration
return marker
writeIORef markersRef newMarkers
putStrLn "hi" | CRogers/stack-ide-atom | haskell/src/StackIdePackage.hs | mit | 1,698 | 9 | 26 | 328 | 514 | 255 | 259 | 51 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.HTMLDivElement
(js_setAlign, setAlign, js_getAlign, getAlign, HTMLDivElement,
castToHTMLDivElement, gTypeHTMLDivElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"align\"] = $2;" js_setAlign
:: HTMLDivElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLDivElement.align Mozilla HTMLDivElement.align documentation>
setAlign ::
(MonadIO m, ToJSString val) => HTMLDivElement -> val -> m ()
setAlign self val = liftIO (js_setAlign (self) (toJSString val))
foreign import javascript unsafe "$1[\"align\"]" js_getAlign ::
HTMLDivElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLDivElement.align Mozilla HTMLDivElement.align documentation>
getAlign ::
(MonadIO m, FromJSString result) => HTMLDivElement -> m result
getAlign self = liftIO (fromJSString <$> (js_getAlign (self))) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/HTMLDivElement.hs | mit | 1,761 | 14 | 10 | 226 | 463 | 284 | 179 | 28 | 1 |
module Test.Week5 (week5) where
import Data.List (permutations)
import Test.Tasty
import Test.Tasty.HUnit
import Week5
import ExprT
import Parser
import qualified StackVM as S
week5 :: TestTree
week5 = testGroup "Week 5 - More polymorphism and type classes"
[
exercise1
, exercise2
, exercise3
, exercise4
, exercise5
, exercise6
]
exercise1 =
testGroup "Exercise 1" [
testCase "Example 1" $ 20 @?=
eval (Mul (Add (Lit 2) (Lit 3)) (Lit 4))
]
exercise2 =
testGroup "Exercise 2" [
testCase "Example 1" $ Just 20 @?=
evalStr "(2+3)*4"
, testCase "Example 2" $ Just 14 @?=
evalStr "2+3*4"
, testCase "Example 3" $ Nothing @?=
evalStr "2+3*"
]
testExp :: Expr a => Maybe a
testExp = parseExp lit add mul "(3 * -4) + 5"
exercise3 =
testGroup "Exercise 3" [
testGroup "Example 1" $ [
testCase "ExprT" $ (mul (add (lit 2) (lit 3)) (lit 4) :: ExprT) @?=
Mul (Add (Lit 2) (Lit 3)) (Lit 4)
]
]
exercise4 =
testGroup "Exercise 4" [
testGroup "Example 2" [
testCase "Integer" $ (testExp :: Maybe Integer) @?= Just (-7)
, testCase "Bool" $ (testExp :: Maybe Bool) @?= Just True
, testCase "MinMax" $ (testExp :: Maybe MinMax) @?= Just (MinMax 3)
, testCase "Mod7" $ (testExp :: Maybe Mod7) @?= Just (Mod7 0)
]
]
exercise5 =
testGroup "Exercise 5" [
testCase "Example 1" $ compile "2+3*4" @?=
Just [S.PushI 2, S.PushI 3, S.PushI 4, S.Mul, S.Add]
]
exercise6 =
testGroup "Exercise 6" [
testCase "Example 1" $ (add (lit 3) (var "x") :: VarExprT) @?=
VAdd (VLit 3) (VVar "x")
, testCase "Example 2" $ (withVars [("x", 6)] $ add (lit 3) (var "x")) @?=
Just 9
, testCase "Example 3" $ (withVars [("x", 6)] $ add (lit 3) (var "y")) @?=
Nothing
, testCase "Example 4" $ (withVars [("x", 6), ("y", 3)] $
mul (var "x") (add (var "y") (var "x"))) @?=
Just 54
]
| taylor1791/cis-194-spring | test/Test/Week5.hs | mit | 1,919 | 0 | 16 | 501 | 785 | 404 | 381 | 58 | 1 |
-- Finding an appointment
-- http://www.codewars.com/kata/525f277c7103571f47000147/
-- Note: Tests fail due to ambiguous occurrence of `shuffle'
module FindingAnAppointment where
import Data.Maybe (listToMaybe)
import Control.Arrow ((***), (&&&))
import Data.List.Split (splitOn)
import Text.Printf (printf)
getStartTime :: [[(String, String)]] -> Int -> Maybe String
getStartTime schedules d = listToMaybe . map (writeT . fst)
. filter (\(s1, e1) -> (s0 <= s1) && (e1 < e0) && ((>=d) . f e1 $ s1))
. uncurry (flip zip) . ((++[e0]) *** (s0:))
. unzip . foldr (g . map (readT *** readT)) [] $ schedules
where (s0, e0) = ((9, 0), (19, 0))
f (h1, m1) (h2, m2) = 60*(h1-h2)+(m1-m2)
readT = (read . head &&& read . last) . splitOn ":"
writeT = uncurry (printf "%02d:%02d")
g [] s2 = s2
g s1 [] = s1
g ((s1, e1):xs) ((s2, e2):ys) | e1 < s2 = (s1, e1) : (s2, e2) : g xs ys
| e2 < s1 = (s2, e2) : (s1, e1) : g xs ys
| otherwise = (min s1 s2, max e1 e2) : g xs ys
| gafiatulin/codewars | src/3 kyu/FindingAnAppointment.hs | mit | 1,388 | 0 | 18 | 612 | 523 | 290 | 233 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Document.Tests.Lambdas where
-- Modules
import Document.Tests.Suite
import Logic.Expr.Const
import Logic.Proof
import Logic.Theories.FunctionTheory
import UnitB.Expr
-- Libraries
import Data.Map hiding ( map )
import qualified Data.Map as M
import Test.UnitTest
import Utilities.Syntactic
test_case :: TestCase
test_case = test
test :: TestCase
test = test_cases
"lambda expressions in the cube example"
[ part0
, part1
, part2
, part3
]
part0 :: TestCase
part0 = test_cases
"part 0"
[ (poCase "test 0, verification, lambda vs empty-fun"
(verify path0 0) result0)
, (poCase "test 1, verification, lambda vs ovl, mk-fun"
(verify path1 0) result1)
, (poCase "test 2, verification, lambda vs apply"
(verify path2 0) result2)
]
part1 :: TestCase
part1 = test_cases
"part 1"
[ (poCase "test 3, verification, set comprehension, failed proof"
(verify path3 0) result3)
, (aCase "test 4, adding a progress property" case4 result4)
, (aCase "test 5, unless properties" case5 result5)
]
part2 :: TestCase
part2 = test_cases
"part 2"
[ (poCase "test 6, verify progress refinement" case6 result6)
, (poCase "test 7, verify refinement rules" case7 result7)
, (poCase "test 8, verify refinement rules" case8 result8)
]
part3 :: TestCase
part3 = test_cases
"part 3"
[ (poCase "test 9, verify disjunction rule" (verify path9 0) result9)
, (stringCase "test 10, error: cyclic proof" (find_errors path10) result10)
, (stringCase "test 11, intermediate goals of monotonic \
\simplification" case11 result11)
, (aCase "test 12, bound variable with ambiguous type"
case12 result12)
, stringCase "test 13, inv6, PO" case13 result13
]
result0 :: String
result0 = unlines
[ " o m0/INIT/INV/inv0"
, " o m0/INIT/INV/inv1"
, " o m0/INIT/INV/inv2"
, " o m0/INIT/INV/inv3/goal"
, " o m0/INIT/INV/inv3/hypotheses"
, " o m0/INIT/INV/inv3/relation"
, " o m0/INIT/INV/inv3/step 1"
, " o m0/INIT/INV/inv3/step 2"
, " o m0/INIT/INV/inv3/step 3"
, " o m0/evt/FIS/a@prime"
, " o m0/evt/FIS/b@prime"
, " o m0/evt/FIS/c@prime"
, " o m0/evt/FIS/n@prime"
, " o m0/evt/INV/inv0/goal"
, " o m0/evt/INV/inv0/hypotheses"
, " o m0/evt/INV/inv0/relation"
, " o m0/evt/INV/inv0/step 1"
, " o m0/evt/INV/inv0/step 2"
, " o m0/evt/INV/inv0/step 3"
, " o m0/evt/INV/inv0/step 4"
, " o m0/evt/INV/inv0/step 5"
, " o m0/evt/INV/inv1/goal"
, " o m0/evt/INV/inv1/hypotheses"
, " o m0/evt/INV/inv1/relation"
, " o m0/evt/INV/inv1/step 1"
, " o m0/evt/INV/inv1/step 2"
, " o m0/evt/INV/inv1/step 3"
, " o m0/evt/INV/inv1/step 4"
, " o m0/evt/INV/inv1/step 5"
, " o m0/evt/INV/inv1/step 6"
, " o m0/evt/INV/inv1/step 7"
, " o m0/evt/INV/inv2/easy"
, " xxx m0/evt/INV/inv3"
, "passed 32 / 33"
]
path0 :: FilePath
path0 = [path|Tests/cubes-t0.tex|]
result1 :: String
result1 = unlines
[ " o m0/INIT/INV/inv0"
, " o m0/INIT/INV/inv1"
, " o m0/INIT/INV/inv2"
, " o m0/INIT/INV/inv3/goal"
, " o m0/INIT/INV/inv3/hypotheses"
, " o m0/INIT/INV/inv3/relation"
, " o m0/INIT/INV/inv3/step 1"
, " o m0/INIT/INV/inv3/step 2"
, " o m0/INIT/INV/inv3/step 3"
, " o m0/INIT/INV/inv4"
, " o m0/evt/FIS/a@prime"
, " o m0/evt/FIS/b@prime"
, " o m0/evt/FIS/c@prime"
, " o m0/evt/FIS/f@prime"
, " o m0/evt/FIS/n@prime"
, " o m0/evt/INV/inv0/goal"
, " o m0/evt/INV/inv0/hypotheses"
, " o m0/evt/INV/inv0/relation"
, " o m0/evt/INV/inv0/step 1"
, " o m0/evt/INV/inv0/step 2"
, " o m0/evt/INV/inv0/step 3"
, " o m0/evt/INV/inv0/step 4"
, " o m0/evt/INV/inv0/step 5"
, " o m0/evt/INV/inv1/goal"
, " o m0/evt/INV/inv1/hypotheses"
, " o m0/evt/INV/inv1/relation"
, " o m0/evt/INV/inv1/step 1"
, " o m0/evt/INV/inv1/step 2"
, " o m0/evt/INV/inv1/step 3"
, " o m0/evt/INV/inv1/step 4"
, " o m0/evt/INV/inv1/step 5"
, " o m0/evt/INV/inv1/step 6"
, " o m0/evt/INV/inv1/step 7"
, " o m0/evt/INV/inv2/easy"
, " o m0/evt/INV/inv3/goal"
, " o m0/evt/INV/inv3/hypotheses"
, " o m0/evt/INV/inv3/relation"
, " o m0/evt/INV/inv3/step 1"
, " o m0/evt/INV/inv3/step 2"
, " o m0/evt/INV/inv3/step 3"
, " o m0/evt/INV/inv3/step 4"
, " o m0/evt/INV/inv3/step 5"
, " o m0/evt/INV/inv3/step 6"
, " o m0/evt/INV/inv4"
, "passed 44 / 44"
]
path1 :: FilePath
path1 = [path|Tests/cubes-t1.tex|]
result2 :: String
result2 = unlines
[ " o m0/INIT/INV/inv0"
, " o m0/INIT/INV/inv1"
, " o m0/INIT/INV/inv2"
, " o m0/INIT/INV/inv3/goal"
, " o m0/INIT/INV/inv3/hypotheses"
, " o m0/INIT/INV/inv3/relation"
, " o m0/INIT/INV/inv3/step 1"
, " o m0/INIT/INV/inv3/step 2"
, " o m0/INIT/INV/inv3/step 3"
, " o m0/INIT/INV/inv4"
, " o m0/INIT/INV/inv5"
, " o m0/INV/WD"
, " o m0/evt/FIS/a@prime"
, " o m0/evt/FIS/b@prime"
, " o m0/evt/FIS/c@prime"
, " o m0/evt/FIS/f@prime"
, " o m0/evt/FIS/n@prime"
, " o m0/evt/INV/inv0/goal"
, " o m0/evt/INV/inv0/hypotheses"
, " o m0/evt/INV/inv0/relation"
, " o m0/evt/INV/inv0/step 1"
, " o m0/evt/INV/inv0/step 2"
, " o m0/evt/INV/inv0/step 3"
, " o m0/evt/INV/inv0/step 4"
, " o m0/evt/INV/inv0/step 5"
, " o m0/evt/INV/inv1/goal"
, " o m0/evt/INV/inv1/hypotheses"
, " o m0/evt/INV/inv1/relation"
, " o m0/evt/INV/inv1/step 1"
, " o m0/evt/INV/inv1/step 2"
, " o m0/evt/INV/inv1/step 3"
, " o m0/evt/INV/inv1/step 4"
, " o m0/evt/INV/inv1/step 5"
, " o m0/evt/INV/inv1/step 6"
, " o m0/evt/INV/inv1/step 7"
, " o m0/evt/INV/inv2/easy"
, " o m0/evt/INV/inv3/goal"
, " o m0/evt/INV/inv3/hypotheses"
, " o m0/evt/INV/inv3/relation"
, " o m0/evt/INV/inv3/step 1"
, " o m0/evt/INV/inv3/step 2"
, " o m0/evt/INV/inv3/step 3"
, " o m0/evt/INV/inv3/step 4"
, " o m0/evt/INV/inv3/step 5"
, " o m0/evt/INV/inv4"
, " o m0/evt/INV/inv5/assertion/asm0/easy"
, " o m0/evt/INV/inv5/main goal/goal"
, " o m0/evt/INV/inv5/main goal/hypotheses"
, " o m0/evt/INV/inv5/main goal/relation"
, " o m0/evt/INV/inv5/main goal/step 1"
, " o m0/evt/INV/inv5/main goal/step 2"
, " o m0/evt/INV/inv5/main goal/step 3"
, " o m0/evt/INV/inv5/main goal/step 4"
, " o m0/evt/INV/inv5/main goal/step 5"
, "passed 54 / 54"
]
path2 :: FilePath
path2 = [path|Tests/cubes-t2.tex|]
result3 :: String
result3 = unlines
[ " o m0/INIT/INV/inv0"
, " o m0/INIT/INV/inv1"
, " o m0/INIT/INV/inv2"
, " o m0/INIT/INV/inv3/goal"
, " o m0/INIT/INV/inv3/hypotheses"
, " o m0/INIT/INV/inv3/relation"
, " o m0/INIT/INV/inv3/step 1"
, " o m0/INIT/INV/inv3/step 2"
, " o m0/INIT/INV/inv3/step 3"
, " o m0/INIT/INV/inv4"
, " o m0/INIT/INV/inv5"
, " o m0/INIT/INV/inv6"
, " o m0/INV/WD"
, " o m0/evt/FIS/a@prime"
, " o m0/evt/FIS/b@prime"
, " o m0/evt/FIS/c@prime"
, " o m0/evt/FIS/f@prime"
, " o m0/evt/FIS/n@prime"
, " o m0/evt/INV/inv0/goal"
, " o m0/evt/INV/inv0/hypotheses"
, " o m0/evt/INV/inv0/relation"
, " o m0/evt/INV/inv0/step 1"
, " o m0/evt/INV/inv0/step 2"
, " o m0/evt/INV/inv0/step 3"
, " o m0/evt/INV/inv0/step 4"
, " o m0/evt/INV/inv0/step 5"
, " o m0/evt/INV/inv1/goal"
, " o m0/evt/INV/inv1/hypotheses"
, " o m0/evt/INV/inv1/relation"
, " o m0/evt/INV/inv1/step 1"
, " o m0/evt/INV/inv1/step 2"
, " o m0/evt/INV/inv1/step 3"
, " o m0/evt/INV/inv1/step 4"
, " o m0/evt/INV/inv1/step 5"
, " o m0/evt/INV/inv1/step 6"
, " o m0/evt/INV/inv1/step 7"
, " o m0/evt/INV/inv2/easy"
, " o m0/evt/INV/inv3/goal"
, " o m0/evt/INV/inv3/hypotheses"
, " o m0/evt/INV/inv3/relation"
, " o m0/evt/INV/inv3/step 1"
, " o m0/evt/INV/inv3/step 2"
, " o m0/evt/INV/inv3/step 3"
, " o m0/evt/INV/inv3/step 4"
, " o m0/evt/INV/inv3/step 5"
, " o m0/evt/INV/inv4"
, " o m0/evt/INV/inv5/assertion/asm0/easy"
, " o m0/evt/INV/inv5/main goal/goal"
, " o m0/evt/INV/inv5/main goal/hypotheses"
, " o m0/evt/INV/inv5/main goal/relation"
, " o m0/evt/INV/inv5/main goal/step 1"
, " o m0/evt/INV/inv5/main goal/step 2"
, " o m0/evt/INV/inv5/main goal/step 3"
, " o m0/evt/INV/inv5/main goal/step 4"
, " o m0/evt/INV/inv5/main goal/step 5"
, " o m0/evt/INV/inv6"
, "passed 56 / 56"
]
path3 :: FilePath
path3 = [path|Tests/cubes-t3.tex|]
result4 :: Either [Error] (Map ProgId ProgressProp)
result4 = M.map (fmap (DispExpr "")) <$> either g Right (do
q0 <- f `mzeq` zlambda [i_decl]
(mzle (mzint 0) i `mzand` mzless i bigN)
(mzpow i $ mzint 3)
q1 <- bigN `mzeq` n
q2 <- (k `mzless` n) `mzor` (n `mzeq` bigN)
p1 <- (n `mzeq` k)
p2 <- mzall [k `mzle` n, n `mzeq` k, mznot (n `mzeq` bigN)]
p3 <- mzall [n `mzeq` k, mznot (n `mzeq` bigN)]
q3 <- mzor
(mzle k n `mzand` mznot (k `mzeq` n))
(n `mzeq` bigN)
q4 <- mznot (n `mzeq` k)
return $ fromList
[ ("prog0", LeadsTo [] ztrue q0)
, ("prog1", LeadsTo [] ztrue q1)
, ("prog2", LeadsTo [kdec] p1 q2)
, ("prog3", LeadsTo [kdec] p2 q3)
, ("prog4", LeadsTo [kdec] p3 q4)
])
where
(k,kdec) = var "k" int
(i,i_decl) = var "i" int
(f,_) = var "f" (fun_type int int)
(n,_) = var "n" int
(bigN,_) = var "N" int
li = LI path4 0 0
g xs = Left $ map (`Error` li) xs
path4 :: FilePath
path4 = [path|Tests/cubes-t6.tex|]
case4 :: IO (Either [Error] (Map ProgId ProgressProp))
case4 = runEitherT (do
ms <- EitherT $ parse path4 :: EitherT [Error] IO [Machine]
case ms of
[m] -> right $ m!.props.progress
_ -> left [Error "a single machine is expected" (LI "" 0 0)])
result5 :: Either [Error] (Map Label SafetyProp)
result5 = M.map (fmap $ DispExpr "") <$> either g Right (do
q0 <- bigN `mzeq` n
p0 <- (k `mzle` n)
q1 <- mznot (n `mzeq` k)
p1 <- mzall
[ n `mzeq` k
, mznot (n `mzeq` bigN)
]
return $ fromList
[ (label "saf0", Unless [k_decl] p0 q0)
, (label "saf1", Unless [k_decl] p1 q1)
])
where
(k,k_decl) = var "k" int
(n,_) = var "n" int
(bigN,_) = var "N" int
li = LI path4 0 0
g xs = Left $ map (`Error` li) xs
case5 :: IO (Either [Error] (Map Label SafetyProp))
case5 = runEitherT (do
ms <- EitherT $ parse path4 :: EitherT [Error] IO [Machine]
case ms of
[m] -> right $ m!.props.safety
_ -> left [Error "a single machine is expected" (LI "" 0 0)])
case6 :: IO (String, Map Label Sequent)
case6 = verify path6 0
result6 :: String
result6 = unlines
[ " o m0/INIT/INV/inv0"
, " o m0/INIT/INV/inv1"
, " o m0/INIT/INV/inv2"
, " o m0/INIT/INV/inv3/goal"
, " o m0/INIT/INV/inv3/hypotheses"
, " o m0/INIT/INV/inv3/relation"
, " o m0/INIT/INV/inv3/step 1"
, " o m0/INIT/INV/inv3/step 2"
, " o m0/INIT/INV/inv3/step 3"
, " o m0/INIT/INV/inv4"
, " o m0/INIT/INV/inv5"
, " o m0/INIT/INV/inv6"
, " xxx m0/INIT/INV/inv8"
, " o m0/INV/WD"
, " o m0/evt/FIS/a@prime"
, " o m0/evt/FIS/b@prime"
, " o m0/evt/FIS/c@prime"
, " o m0/evt/FIS/f@prime"
, " o m0/evt/FIS/n@prime"
, " o m0/evt/INV/inv0/goal"
, " o m0/evt/INV/inv0/hypotheses"
, " o m0/evt/INV/inv0/relation"
, " o m0/evt/INV/inv0/step 1"
, " o m0/evt/INV/inv0/step 2"
, " o m0/evt/INV/inv0/step 3"
, " o m0/evt/INV/inv0/step 4"
, " o m0/evt/INV/inv0/step 5"
, " o m0/evt/INV/inv1/goal"
, " o m0/evt/INV/inv1/hypotheses"
, " o m0/evt/INV/inv1/relation"
, " o m0/evt/INV/inv1/step 1"
, " o m0/evt/INV/inv1/step 2"
, " o m0/evt/INV/inv1/step 3"
, " o m0/evt/INV/inv1/step 4"
, " o m0/evt/INV/inv1/step 5"
, " o m0/evt/INV/inv1/step 6"
, " o m0/evt/INV/inv1/step 7"
, " o m0/evt/INV/inv2/easy"
, " o m0/evt/INV/inv3/goal"
, " o m0/evt/INV/inv3/hypotheses"
, " o m0/evt/INV/inv3/relation"
, " o m0/evt/INV/inv3/step 1"
, " o m0/evt/INV/inv3/step 2"
, " o m0/evt/INV/inv3/step 3"
, " o m0/evt/INV/inv3/step 4"
, " o m0/evt/INV/inv3/step 5"
, " o m0/evt/INV/inv4"
, " o m0/evt/INV/inv5/assertion/asm0/easy"
, " o m0/evt/INV/inv5/main goal/goal"
, " o m0/evt/INV/inv5/main goal/hypotheses"
, " o m0/evt/INV/inv5/main goal/relation"
, " o m0/evt/INV/inv5/main goal/step 1"
, " o m0/evt/INV/inv5/main goal/step 2"
, " o m0/evt/INV/inv5/main goal/step 3"
, " o m0/evt/INV/inv5/main goal/step 4"
, " o m0/evt/INV/inv5/main goal/step 5"
, " o m0/evt/INV/inv6/goal"
, " o m0/evt/INV/inv6/hypotheses"
, " o m0/evt/INV/inv6/relation"
, " o m0/evt/INV/inv6/step 1"
, " o m0/evt/INV/inv6/step 2"
, " o m0/evt/INV/inv6/step 3"
, " o m0/evt/INV/inv6/step 4"
, " xxx m0/evt/INV/inv6/step 5"
, " o m0/evt/INV/inv8"
, " o m0/evt/SAF/saf0"
, " o m0/evt/SCH/grd0"
, " o m0/prog0/LIVE/monotonicity/rhs"
, " xxx m0/prog1/LIVE/add"
, " o m0/prog2/LIVE/trading/lhs"
, " o m0/prog2/LIVE/trading/rhs"
, " o m0/prog3/LIVE/PSP/lhs"
, " o m0/prog3/LIVE/PSP/rhs"
, " o m0/prog4/LIVE/discharge/tr/lhs"
, " xxx m0/prog4/LIVE/discharge/tr/rhs"
, " o m0/tr0/TR/evt/EN"
, " o m0/tr0/TR/evt/NEG"
, "passed 73 / 77"
]
path6 :: FilePath
path6 = [path|Tests/cubes-t5.tex|]
case7 :: IO (String, Map Label Sequent)
case7 = verify path7 0
result7 :: String
result7 = unlines
[ " o m0/INIT/INV/inv0"
, " o m0/INIT/INV/inv1"
, " o m0/INIT/INV/inv2"
, " o m0/INIT/INV/inv3/goal"
, " o m0/INIT/INV/inv3/hypotheses"
, " o m0/INIT/INV/inv3/relation"
, " o m0/INIT/INV/inv3/step 1"
, " o m0/INIT/INV/inv3/step 2"
, " o m0/INIT/INV/inv3/step 3"
, " o m0/INIT/INV/inv4"
, " o m0/INIT/INV/inv5"
, " o m0/INIT/INV/inv6"
, " o m0/INV/WD"
, " o m0/evt/FIS/a@prime"
, " o m0/evt/FIS/b@prime"
, " o m0/evt/FIS/c@prime"
, " o m0/evt/FIS/f@prime"
, " o m0/evt/FIS/n@prime"
, " o m0/evt/INV/inv0/goal"
, " o m0/evt/INV/inv0/hypotheses"
, " o m0/evt/INV/inv0/relation"
, " o m0/evt/INV/inv0/step 1"
, " o m0/evt/INV/inv0/step 2"
, " o m0/evt/INV/inv0/step 3"
, " o m0/evt/INV/inv0/step 4"
, " o m0/evt/INV/inv0/step 5"
, " o m0/evt/INV/inv1/goal"
, " o m0/evt/INV/inv1/hypotheses"
, " o m0/evt/INV/inv1/relation"
, " o m0/evt/INV/inv1/step 1"
, " o m0/evt/INV/inv1/step 2"
, " o m0/evt/INV/inv1/step 3"
, " o m0/evt/INV/inv1/step 4"
, " o m0/evt/INV/inv1/step 5"
, " o m0/evt/INV/inv1/step 6"
, " o m0/evt/INV/inv1/step 7"
, " o m0/evt/INV/inv2/easy"
, " o m0/evt/INV/inv3/goal"
, " o m0/evt/INV/inv3/hypotheses"
, " o m0/evt/INV/inv3/relation"
, " o m0/evt/INV/inv3/step 1"
, " o m0/evt/INV/inv3/step 2"
, " o m0/evt/INV/inv3/step 3"
, " o m0/evt/INV/inv3/step 4"
, " o m0/evt/INV/inv3/step 5"
, " o m0/evt/INV/inv4"
, " o m0/evt/INV/inv5/assertion/asm0/easy"
, " o m0/evt/INV/inv5/main goal/goal"
, " o m0/evt/INV/inv5/main goal/hypotheses"
, " o m0/evt/INV/inv5/main goal/relation"
, " o m0/evt/INV/inv5/main goal/step 1"
, " o m0/evt/INV/inv5/main goal/step 2"
, " o m0/evt/INV/inv5/main goal/step 3"
, " o m0/evt/INV/inv5/main goal/step 4"
, " o m0/evt/INV/inv5/main goal/step 5"
, " o m0/evt/INV/inv6/goal"
, " o m0/evt/INV/inv6/hypotheses"
, " o m0/evt/INV/inv6/relation"
, " o m0/evt/INV/inv6/step 1"
, " o m0/evt/INV/inv6/step 2"
, " o m0/evt/INV/inv6/step 3"
, " o m0/evt/INV/inv6/step 4"
, " xxx m0/evt/INV/inv6/step 5"
, " o m0/evt/SAF/saf0"
, " o m0/prog0/LIVE/monotonicity/rhs"
, " xxx m0/prog1/LIVE/add"
, " xxx m0/prog10/LIVE/add"
, " xxx m0/prog2/LIVE/trading/lhs"
, " o m0/prog2/LIVE/trading/rhs"
, " xxx m0/prog3/LIVE/PSP/lhs"
, " xxx m0/prog3/LIVE/PSP/rhs"
, " xxx m0/prog4/LIVE/add"
, " xxx m0/prog5/LIVE/transitivity/lhs"
, " o m0/prog5/LIVE/transitivity/mhs/0/1"
, " o m0/prog5/LIVE/transitivity/rhs"
, " xxx m0/prog6/LIVE/add"
, " xxx m0/prog7/LIVE/add"
, " o m0/prog8/LIVE/transitivity/mhs/0/1"
, " o m0/prog8/LIVE/transitivity/rhs"
, " xxx m0/prog9/LIVE/add"
, "passed 69 / 80"
]
path7 :: FilePath
path7 = [path|Tests/cubes-t4.tex|]
case8 :: IO (String, Map Label Sequent)
case8 = verify path8 0
result8 :: String
result8 = unlines
[ " o m0/INIT/INV/inv0"
, " o m0/INIT/INV/inv1"
, " o m0/INIT/INV/inv2"
, " o m0/INIT/INV/inv3/goal"
, " o m0/INIT/INV/inv3/hypotheses"
, " o m0/INIT/INV/inv3/relation"
, " o m0/INIT/INV/inv3/step 1"
, " o m0/INIT/INV/inv3/step 2"
, " o m0/INIT/INV/inv3/step 3"
, " o m0/INIT/INV/inv4"
, " o m0/INIT/INV/inv5"
, " o m0/INIT/INV/inv6"
, " o m0/INIT/INV/inv7"
, " o m0/INV/WD"
, " o m0/evt/FIS/a@prime"
, " o m0/evt/FIS/b@prime"
, " o m0/evt/FIS/c@prime"
, " o m0/evt/FIS/f@prime"
, " o m0/evt/FIS/n@prime"
, " o m0/evt/INV/inv0/goal"
, " o m0/evt/INV/inv0/hypotheses"
, " o m0/evt/INV/inv0/relation"
, " o m0/evt/INV/inv0/step 1"
, " o m0/evt/INV/inv0/step 2"
, " o m0/evt/INV/inv0/step 3"
, " o m0/evt/INV/inv0/step 4"
, " o m0/evt/INV/inv0/step 5"
, " o m0/evt/INV/inv1/goal"
, " o m0/evt/INV/inv1/hypotheses"
, " o m0/evt/INV/inv1/relation"
, " o m0/evt/INV/inv1/step 1"
, " o m0/evt/INV/inv1/step 2"
, " o m0/evt/INV/inv1/step 3"
, " o m0/evt/INV/inv1/step 4"
, " o m0/evt/INV/inv1/step 5"
, " o m0/evt/INV/inv1/step 6"
, " o m0/evt/INV/inv1/step 7"
, " o m0/evt/INV/inv2/easy"
, " o m0/evt/INV/inv3/goal"
, " o m0/evt/INV/inv3/hypotheses"
, " o m0/evt/INV/inv3/relation"
, " o m0/evt/INV/inv3/step 1"
, " o m0/evt/INV/inv3/step 2"
, " o m0/evt/INV/inv3/step 3"
, " o m0/evt/INV/inv3/step 4"
, " o m0/evt/INV/inv3/step 5"
, " o m0/evt/INV/inv4"
, " o m0/evt/INV/inv5/goal"
, " o m0/evt/INV/inv5/hypotheses"
, " o m0/evt/INV/inv5/relation"
, " o m0/evt/INV/inv5/step 1"
, " o m0/evt/INV/inv5/step 2"
, " o m0/evt/INV/inv5/step 3"
, " o m0/evt/INV/inv5/step 4"
, " o m0/evt/INV/inv5/step 5"
, " o m0/evt/INV/inv6/goal"
, " o m0/evt/INV/inv6/hypotheses"
, " o m0/evt/INV/inv6/relation"
, " o m0/evt/INV/inv6/step 1"
, " o m0/evt/INV/inv6/step 2"
, " o m0/evt/INV/inv6/step 3"
, " o m0/evt/INV/inv6/step 4"
, " xxx m0/evt/INV/inv6/step 5"
, " o m0/evt/INV/inv7"
, " o m0/evt/SAF/saf0"
, " o m0/evt/SAF/saf1"
, " o m0/evt/SCH/grd0"
, " o m0/prog0/LIVE/monotonicity/rhs"
, " o m0/prog1/LIVE/induction/lhs"
, " o m0/prog1/LIVE/induction/rhs"
, " o m0/prog2/LIVE/trading/lhs"
, " o m0/prog2/LIVE/trading/rhs"
, " o m0/prog3/LIVE/PSP/lhs"
, " o m0/prog3/LIVE/PSP/rhs"
, " o m0/prog4/LIVE/discharge/saf/lhs"
, " o m0/prog4/LIVE/discharge/saf/rhs"
, " o m0/prog4/LIVE/discharge/tr"
, " o m0/tr0/TR/evt/EN"
, " o m0/tr0/TR/evt/NEG"
, "passed 78 / 79"
]
path8 :: FilePath
path8 = [path|Tests/cubes-t7.tex|]
result9 :: String
result9 = unlines
[ " o m0/INIT/INV/inv0"
, " o m0/INIT/INV/inv1"
, " o m0/INIT/INV/inv2"
, " o m0/INIT/INV/inv3/goal"
, " o m0/INIT/INV/inv3/hypotheses"
, " o m0/INIT/INV/inv3/relation"
, " o m0/INIT/INV/inv3/step 1"
, " o m0/INIT/INV/inv3/step 2"
, " o m0/INIT/INV/inv3/step 3"
, " o m0/INIT/INV/inv4"
, " o m0/INIT/INV/inv5"
, " o m0/INIT/INV/inv6"
, " o m0/INIT/INV/inv7"
, " o m0/INV/WD"
, " o m0/evt/INV/inv0/goal"
, " o m0/evt/INV/inv0/hypotheses"
, " o m0/evt/INV/inv0/relation"
, " o m0/evt/INV/inv0/step 1"
, " o m0/evt/INV/inv0/step 2"
, " o m0/evt/INV/inv0/step 3"
, " o m0/evt/INV/inv0/step 4"
, " o m0/evt/INV/inv0/step 5"
, " o m0/evt/INV/inv1/goal"
, " o m0/evt/INV/inv1/hypotheses"
, " o m0/evt/INV/inv1/relation"
, " o m0/evt/INV/inv1/step 1"
, " o m0/evt/INV/inv1/step 2"
, " o m0/evt/INV/inv1/step 3"
, " o m0/evt/INV/inv1/step 4"
, " o m0/evt/INV/inv1/step 5"
, " o m0/evt/INV/inv1/step 6"
, " o m0/evt/INV/inv1/step 7"
, " o m0/evt/INV/inv2/easy"
, " o m0/evt/INV/inv3/goal"
, " o m0/evt/INV/inv3/hypotheses"
, " o m0/evt/INV/inv3/relation"
, " o m0/evt/INV/inv3/step 1"
, " o m0/evt/INV/inv3/step 2"
, " o m0/evt/INV/inv3/step 3"
, " o m0/evt/INV/inv3/step 4"
, " o m0/evt/INV/inv3/step 5"
, " o m0/evt/INV/inv4"
, " o m0/evt/INV/inv5/goal"
, " o m0/evt/INV/inv5/hypotheses"
, " o m0/evt/INV/inv5/relation"
, " o m0/evt/INV/inv5/step 1"
, " o m0/evt/INV/inv5/step 2"
, " o m0/evt/INV/inv5/step 3"
, " o m0/evt/INV/inv5/step 4"
, " o m0/evt/INV/inv5/step 5"
, " o m0/evt/INV/inv6/goal"
, " o m0/evt/INV/inv6/hypotheses"
, " o m0/evt/INV/inv6/relation"
, " o m0/evt/INV/inv6/step 1"
, " o m0/evt/INV/inv6/step 2"
, " o m0/evt/INV/inv6/step 3"
, " o m0/evt/INV/inv6/step 4"
, " xxx m0/evt/INV/inv6/step 5"
, " o m0/evt/INV/inv7"
, " o m0/evt/SAF/saf0"
, " o m0/evt/SAF/saf1"
, " o m0/evt/SCH/grd0"
, " o m0/prog0/LIVE/monotonicity/rhs"
, " o m0/prog1/LIVE/induction/lhs"
, " o m0/prog1/LIVE/induction/rhs"
, " o m0/prog2/LIVE/trading/lhs"
, " o m0/prog2/LIVE/trading/rhs"
, " o m0/prog3/LIVE/PSP/lhs"
, " o m0/prog3/LIVE/PSP/rhs"
, " o m0/prog4/LIVE/discharge/saf/lhs"
, " o m0/prog4/LIVE/discharge/saf/rhs"
, " o m0/prog4/LIVE/discharge/tr"
, " o m0/prog5/LIVE/disjunction/lhs"
, " o m0/prog5/LIVE/disjunction/rhs"
, " xxx m0/prog6/LIVE/add"
, " xxx m0/prog7/LIVE/add"
, " xxx m0/prog8/LIVE/add"
, " o m0/tr0/TR/evt/EN"
, " o m0/tr0/TR/evt/NEG"
, "passed 75 / 79"
]
path9 :: FilePath
path9 = [path|Tests/cubes-t8.tex|]
path10 :: FilePath
path10 = [path|Tests/cubes-t9.tex|]
result10 :: String
result10 = unlines
[ "A cycle exists in the liveness proof"
, "error 339:1:"
, "\tProgress property prog0 (refined in m0)"
, ""
, "error 341:1:"
, "\tProgress property prog1 (refined in m0)"
, ""
, "error 343:1:"
, "\tProgress property prog2 (refined in m0)"
, ""
, "error 347:1:"
, "\tProgress property prog3 (refined in m0)"
, ""
]
case11 :: IO String
case11 = do
proof_obligation path2 "m0/evt/INV/inv5/main goal/step 4" 0
-- pos <- list_file_obligations path2
-- case pos of
-- Right [(_,pos)] -> do
-- let po = pos ! label "m0/evt/INV/inv5/main goal/step (287,1)"
-- cmd = unlines $ map pretty_print' $ z3_code po
-- return cmd
-- x -> return $ show x
result11 :: String
result11 = unlines
[ "; m0/evt/INV/inv5/main goal/step 4"
, "(set-option :auto-config false)"
, "(set-option :smt.timeout 3000)"
, "(declare-datatypes (a) ( (Maybe (Just (fromJust a)) Nothing) ))"
, "(declare-datatypes () ( (Null null) ))"
, "(declare-datatypes (a b) ( (Pair (pair (first a) (second b))) ))"
, "(define-sort guarded (a) (Maybe a))"
, "; comment: we don't need to declare the sort Bool"
, "; comment: we don't need to declare the sort Int"
, "; comment: we don't need to declare the sort Real"
, "(define-sort pfun (a b) (Array a (Maybe b)))"
, "(define-sort set (a) (Array a Bool))"
, "(declare-const a Int)"
, "(declare-const a@prime Int)"
, "(declare-const b Int)"
, "(declare-const b@prime Int)"
, "(declare-const c Int)"
, "(declare-const c@prime Int)"
, "(declare-const f (pfun Int Int))"
, "(declare-const f@prime (pfun Int Int))"
, "(declare-const i Int)"
, "(declare-const n Int)"
, "(declare-const n@prime Int)"
, "(declare-fun apply@@Int@@Int ( (pfun Int Int) Int ) Int)"
, "(declare-fun card@@Int ( (set Int) ) Int)"
, "(declare-fun dom@@Int@@Int ( (pfun Int Int) ) (set Int))"
, "(declare-fun dom-rest@@Int@@Int"
, " ( (set Int)"
, " (pfun Int Int) )"
, " (pfun Int Int))"
, "(declare-fun dom-subt@@Int@@Int"
, " ( (set Int)"
, " (pfun Int Int) )"
, " (pfun Int Int))"
, "(declare-fun empty-fun@@Int@@Int () (pfun Int Int))"
, "(declare-fun finite@@Int ( (set Int) ) Bool)"
, "(declare-fun injective@@Int@@Int ( (pfun Int Int) ) Bool)"
, "(declare-fun mk-fun@@Int@@Int (Int Int) (pfun Int Int))"
, "(declare-fun mk-set@@Int (Int) (set Int))"
, "(declare-fun ovl@@Int@@Int"
, " ( (pfun Int Int)"
, " (pfun Int Int) )"
, " (pfun Int Int))"
, "(declare-fun ran@@Int@@Int ( (pfun Int Int) ) (set Int))"
, "(define-fun all@@Int () (set Int) ( (as const (set Int)) true ))"
, "(define-fun compl@@Int"
, " ( (s1 (set Int)) )"
, " (set Int)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun elem@@Int"
, " ( (x Int)"
, " (s1 (set Int)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun empty-set@@Int"
, " ()"
, " (set Int)"
, " ( (as const (set Int))"
, " false ))"
, "(define-fun set-diff@@Int"
, " ( (s1 (set Int))"
, " (s2 (set Int)) )"
, " (set Int)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun st-subset@@Int"
, " ( (s1 (set Int))"
, " (s2 (set Int)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(assert (forall ( (i Int) )"
, " (! (= (elem@@Int i (dom@@Int@@Int f))"
, " (and (<= 0 i) (< i n)))"
, " :pattern"
, " ( (elem@@Int i (dom@@Int@@Int f)) ))))"
, "(assert (= f@prime (ovl@@Int@@Int f (mk-fun@@Int@@Int n a))))"
, "(assert (forall ( (r (set Int)) )"
, " (! (=> (finite@@Int r) (<= 0 (card@@Int r)))"
, " :pattern"
, " ( (<= 0 (card@@Int r)) ))))"
, "(assert (forall ( (r (set Int)) )"
, " (! (= (= (card@@Int r) 0) (= r empty-set@@Int))"
, " :pattern"
, " ( (card@@Int r) ))))"
, "(assert (forall ( (x Int) )"
, " (! (= (card@@Int (mk-set@@Int x)) 1)"
, " :pattern"
, " ( (card@@Int (mk-set@@Int x)) ))))"
, "(assert (forall ( (r (set Int)) )"
, " (! (= (= (card@@Int r) 1)"
, " (exists ( (x Int) ) (and true (= r (mk-set@@Int x)))))"
, " :pattern"
, " ( (card@@Int r) ))))"
, "(assert (forall ( (r (set Int))"
, " (r0 (set Int)) )"
, " (! (=> (= (intersect r r0) empty-set@@Int)"
, " (= (card@@Int (union r r0))"
, " (+ (card@@Int r) (card@@Int r0))))"
, " :pattern"
, " ( (card@@Int (union r r0)) ))))"
, "(assert (= (dom@@Int@@Int empty-fun@@Int@@Int)"
, " empty-set@@Int))"
, "(assert (forall ( (f1 (pfun Int Int)) )"
, " (! (= (ovl@@Int@@Int f1 empty-fun@@Int@@Int) f1)"
, " :pattern"
, " ( (ovl@@Int@@Int f1 empty-fun@@Int@@Int) ))))"
, "(assert (forall ( (f1 (pfun Int Int)) )"
, " (! (= (ovl@@Int@@Int empty-fun@@Int@@Int f1) f1)"
, " :pattern"
, " ( (ovl@@Int@@Int empty-fun@@Int@@Int f1) ))))"
, "(assert (forall ( (x Int)"
, " (y Int) )"
, " (! (= (dom@@Int@@Int (mk-fun@@Int@@Int x y))"
, " (mk-set@@Int x))"
, " :pattern"
, " ( (dom@@Int@@Int (mk-fun@@Int@@Int x y)) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (f2 (pfun Int Int))"
, " (x Int) )"
, " (! (=> (elem@@Int x (dom@@Int@@Int f2))"
, " (= (apply@@Int@@Int (ovl@@Int@@Int f1 f2) x)"
, " (apply@@Int@@Int f2 x)))"
, " :pattern"
, " ( (apply@@Int@@Int (ovl@@Int@@Int f1 f2) x) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (f2 (pfun Int Int))"
, " (x Int) )"
, " (! (=> (and (elem@@Int x (dom@@Int@@Int f1))"
, " (not (elem@@Int x (dom@@Int@@Int f2))))"
, " (= (apply@@Int@@Int (ovl@@Int@@Int f1 f2) x)"
, " (apply@@Int@@Int f1 x)))"
, " :pattern"
, " ( (apply@@Int@@Int (ovl@@Int@@Int f1 f2) x) ))))"
, "(assert (forall ( (x Int)"
, " (y Int) )"
, " (! (= (apply@@Int@@Int (mk-fun@@Int@@Int x y) x) y)"
, " :pattern"
, " ( (apply@@Int@@Int (mk-fun@@Int@@Int x y) x) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (s1 (set Int))"
, " (x Int) )"
, " (! (=> (and (elem@@Int x s1) (elem@@Int x (dom@@Int@@Int f1)))"
, " (= (apply@@Int@@Int (dom-rest@@Int@@Int s1 f1) x)"
, " (apply@@Int@@Int f1 x)))"
, " :pattern"
, " ( (apply@@Int@@Int (dom-rest@@Int@@Int s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (s1 (set Int))"
, " (x Int) )"
, " (! (=> (elem@@Int x (set-diff@@Int (dom@@Int@@Int f1) s1))"
, " (= (apply@@Int@@Int (dom-subt@@Int@@Int s1 f1) x)"
, " (apply@@Int@@Int f1 x)))"
, " :pattern"
, " ( (apply@@Int@@Int (dom-subt@@Int@@Int s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (f2 (pfun Int Int)) )"
, " (! (= (dom@@Int@@Int (ovl@@Int@@Int f1 f2))"
, " (union (dom@@Int@@Int f1) (dom@@Int@@Int f2)))"
, " :pattern"
, " ( (dom@@Int@@Int (ovl@@Int@@Int f1 f2)) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (s1 (set Int)) )"
, " (! (= (dom@@Int@@Int (dom-rest@@Int@@Int s1 f1))"
, " (intersect s1 (dom@@Int@@Int f1)))"
, " :pattern"
, " ( (dom@@Int@@Int (dom-rest@@Int@@Int s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (s1 (set Int)) )"
, " (! (= (dom@@Int@@Int (dom-subt@@Int@@Int s1 f1))"
, " (set-diff@@Int (dom@@Int@@Int f1) s1))"
, " :pattern"
, " ( (dom@@Int@@Int (dom-subt@@Int@@Int s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (x Int)"
, " (y Int) )"
, " (! (= (and (elem@@Int x (dom@@Int@@Int f1))"
, " (= (apply@@Int@@Int f1 x) y))"
, " (= (select f1 x) (Just y)))"
, " :pattern"
, " ( (elem@@Int x (dom@@Int@@Int f1))"
, " (apply@@Int@@Int f1 x)"
, " (select f1 x)"
, " (Just y) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (x Int)"
, " (x2 Int)"
, " (y Int) )"
, " (! (=> (not (= x x2))"
, " (= (apply@@Int@@Int (ovl@@Int@@Int f1 (mk-fun@@Int@@Int x y)) x2)"
, " (apply@@Int@@Int f1 x2)))"
, " :pattern"
, " ( (apply@@Int@@Int (ovl@@Int@@Int f1 (mk-fun@@Int@@Int x y)) x2) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (x Int)"
, " (y Int) )"
, " (! (= (apply@@Int@@Int (ovl@@Int@@Int f1 (mk-fun@@Int@@Int x y)) x)"
, " y)"
, " :pattern"
, " ( (apply@@Int@@Int (ovl@@Int@@Int f1 (mk-fun@@Int@@Int x y)) x) ))))"
, "(assert (= (ran@@Int@@Int empty-fun@@Int@@Int)"
, " empty-set@@Int))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (y Int) )"
, " (! (= (elem@@Int y (ran@@Int@@Int f1))"
, " (exists ( (x Int) )"
, " (and true"
, " (and (elem@@Int x (dom@@Int@@Int f1))"
, " (= (apply@@Int@@Int f1 x) y)))))"
, " :pattern"
, " ( (elem@@Int y (ran@@Int@@Int f1)) ))))"
, "(assert (forall ( (x Int)"
, " (y Int) )"
, " (! (= (ran@@Int@@Int (mk-fun@@Int@@Int x y))"
, " (mk-set@@Int y))"
, " :pattern"
, " ( (ran@@Int@@Int (mk-fun@@Int@@Int x y)) ))))"
, "(assert (forall ( (f1 (pfun Int Int)) )"
, " (! (= (injective@@Int@@Int f1)"
, " (forall ( (x Int)"
, " (x2 Int) )"
, " (=> (and (elem@@Int x (dom@@Int@@Int f1))"
, " (elem@@Int x2 (dom@@Int@@Int f1)))"
, " (=> (= (apply@@Int@@Int f1 x) (apply@@Int@@Int f1 x2))"
, " (= x x2)))))"
, " :pattern"
, " ( (injective@@Int@@Int f1) ))))"
, "(assert (injective@@Int@@Int empty-fun@@Int@@Int))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (x Int) )"
, " (! (=> (elem@@Int x (dom@@Int@@Int f1))"
, " (elem@@Int (apply@@Int@@Int f1 x) (ran@@Int@@Int f1)))"
, " :pattern"
, " ( (elem@@Int (apply@@Int@@Int f1 x) (ran@@Int@@Int f1)) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (s1 (set Int))"
, " (x Int) )"
, " (! (=> (elem@@Int x (set-diff@@Int (dom@@Int@@Int f1) s1))"
, " (elem@@Int (apply@@Int@@Int f1 x)"
, " (ran@@Int@@Int (dom-subt@@Int@@Int s1 f1))))"
, " :pattern"
, " ( (elem@@Int (apply@@Int@@Int f1 x)"
, " (ran@@Int@@Int (dom-subt@@Int@@Int s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (s1 (set Int))"
, " (x Int) )"
, " (! (=> (elem@@Int x (intersect (dom@@Int@@Int f1) s1))"
, " (elem@@Int (apply@@Int@@Int f1 x)"
, " (ran@@Int@@Int (dom-rest@@Int@@Int s1 f1))))"
, " :pattern"
, " ( (elem@@Int (apply@@Int@@Int f1 x)"
, " (ran@@Int@@Int (dom-rest@@Int@@Int s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (x Int)"
, " (y Int) )"
, " (! (=> (and (elem@@Int x (dom@@Int@@Int f1))"
, " (injective@@Int@@Int f1))"
, " (= (ran@@Int@@Int (ovl@@Int@@Int f1 (mk-fun@@Int@@Int x y)))"
, " (union (set-diff@@Int (ran@@Int@@Int f1)"
, " (mk-set@@Int (apply@@Int@@Int f1 x)))"
, " (mk-set@@Int y))))"
, " :pattern"
, " ( (ran@@Int@@Int (ovl@@Int@@Int f1 (mk-fun@@Int@@Int x y))) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (x Int)"
, " (y Int) )"
, " (! (=> (not (elem@@Int x (dom@@Int@@Int f1)))"
, " (= (ran@@Int@@Int (ovl@@Int@@Int f1 (mk-fun@@Int@@Int x y)))"
, " (union (ran@@Int@@Int f1) (mk-set@@Int y))))"
, " :pattern"
, " ( (ran@@Int@@Int (ovl@@Int@@Int f1 (mk-fun@@Int@@Int x y))) ))))"
, "(assert (forall ( (x Int)"
, " (y Int) )"
, " (! (= (elem@@Int x (mk-set@@Int y)) (= x y))"
, " :pattern"
, " ( (elem@@Int x (mk-set@@Int y)) ))))"
, "(assert (forall ( (s1 (set Int))"
, " (s2 (set Int)) )"
, " (! (=> (finite@@Int s1)"
, " (finite@@Int (set-diff@@Int s1 s2)))"
, " :pattern"
, " ( (finite@@Int (set-diff@@Int s1 s2)) ))))"
, "(assert (forall ( (s1 (set Int))"
, " (s2 (set Int)) )"
, " (! (=> (and (finite@@Int s1) (finite@@Int s2))"
, " (finite@@Int (union s1 s2)))"
, " :pattern"
, " ( (finite@@Int (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set Int))"
, " (s2 (set Int)) )"
, " (! (=> (and (finite@@Int s2) (not (finite@@Int s1)))"
, " (not (finite@@Int (set-diff@@Int s1 s2))))"
, " :pattern"
, " ( (finite@@Int (set-diff@@Int s1 s2)) ))))"
, "(assert (forall ( (x Int) )"
, " (! (finite@@Int (mk-set@@Int x))"
, " :pattern"
, " ( (finite@@Int (mk-set@@Int x)) ))))"
, "(assert (finite@@Int empty-set@@Int))"
, "(assert (forall ( (i Int) )"
, " (! (= (elem@@Int i (dom@@Int@@Int f))"
, " (and (<= 0 i) (< i n)))"
, " :pattern"
, " ( (elem@@Int i (dom@@Int@@Int f)) ))))"
, "(assert (not (= (forall ( (i Int) )"
, " (=> (and (<= 0 i) (< i n))"
, " (= (apply@@Int@@Int f@prime i) (^ i 3))))"
, " (forall ( (i Int) )"
, " (=> (and (<= 0 i) (< i n))"
, " (= (apply@@Int@@Int f i) (^ i 3)))))))"
, "(assert (not (forall ( (i Int) )"
, " (=> true"
, " (= (=> (and (<= 0 i) (< i n))"
, " (= (apply@@Int@@Int f@prime i) (^ i 3)))"
, " (=> (and (<= 0 i) (< i n))"
, " (= (apply@@Int@@Int f i) (^ i 3))))))))"
, "(assert (not (= (=> (and (<= 0 i) (< i n))"
, " (= (apply@@Int@@Int f@prime i) (^ i 3)))"
, " (=> (and (<= 0 i) (< i n))"
, " (= (apply@@Int@@Int f i) (^ i 3))))))"
, "(assert (not (= (= (apply@@Int@@Int f@prime i) (^ i 3))"
, " (= (apply@@Int@@Int f i) (^ i 3)))))"
, "(assert (not (= (apply@@Int@@Int f@prime i) (apply@@Int@@Int f i))))"
, "(assert (not (= f@prime f)))"
, "(check-sat-using (or-else (then qe smt)"
, " (then simplify smt)"
, " (then skip smt)"
, " (then (using-params simplify :expand-power true) smt)))"
, "; m0/evt/INV/inv5/main goal/step 4"
]
path12 :: FilePath
path12 = [path|Tests/cubes-t10.tex|]
result12 :: String
result12 = unlines
[ "error 274:3:\n type of j is ill-defined: _a"
]
case12 :: IO String
case12 = find_errors path12
case13 :: IO String
case13 = proof_obligation path3 "m0/evt/INV/inv6" 0
result13 :: String
result13 = unlines
[ "; m0/evt/INV/inv6"
, "(set-option :auto-config false)"
, "(set-option :smt.timeout 3000)"
, "(declare-datatypes (a) ( (Maybe (Just (fromJust a)) Nothing) ))"
, "(declare-datatypes () ( (Null null) ))"
, "(declare-datatypes (a b) ( (Pair (pair (first a) (second b))) ))"
, "(define-sort guarded (a) (Maybe a))"
, "; comment: we don't need to declare the sort Bool"
, "; comment: we don't need to declare the sort Int"
, "; comment: we don't need to declare the sort Real"
, "(define-sort pfun (a b) (Array a (Maybe b)))"
, "(define-sort set (a) (Array a Bool))"
, "(declare-const a Int)"
, "(declare-const a@prime Int)"
, "(declare-const b Int)"
, "(declare-const b@prime Int)"
, "(declare-const c Int)"
, "(declare-const c@prime Int)"
, "(declare-const f (pfun Int Int))"
, "(declare-const f@prime (pfun Int Int))"
, "(declare-const n Int)"
, "(declare-const n@prime Int)"
, "(declare-fun apply@@Int@@Int ( (pfun Int Int) Int ) Int)"
, "(declare-fun card@@Int ( (set Int) ) Int)"
, "(declare-fun const@@Int@@Int (Int) (Array Int Int))"
, "(declare-fun dom@@Int@@Int ( (pfun Int Int) ) (set Int))"
, "(declare-fun dom-rest@@Int@@Int"
, " ( (set Int)"
, " (pfun Int Int) )"
, " (pfun Int Int))"
, "(declare-fun dom-subt@@Int@@Int"
, " ( (set Int)"
, " (pfun Int Int) )"
, " (pfun Int Int))"
, "(declare-fun empty-fun@@Int@@Int () (pfun Int Int))"
, "(declare-fun finite@@Int ( (set Int) ) Bool)"
, "(declare-fun ident@@Int () (Array Int Int))"
, "(declare-fun injective@@Int@@Int ( (pfun Int Int) ) Bool)"
, "(declare-fun lambda@@Int@@Int"
, " ( (set Int)"
, " (Array Int Int) )"
, " (pfun Int Int))"
, "(declare-fun mk-fun@@Int@@Int (Int Int) (pfun Int Int))"
, "(declare-fun mk-set@@Int (Int) (set Int))"
, "(declare-fun ovl@@Int@@Int"
, " ( (pfun Int Int)"
, " (pfun Int Int) )"
, " (pfun Int Int))"
, "(declare-fun qsum@@Int ( (set Int) (Array Int Int) ) Int)"
, "(declare-fun ran@@Int@@Int ( (pfun Int Int) ) (set Int))"
, "(declare-fun set@@Int@@Int"
, " ( (set Int)"
, " (Array Int Int) )"
, " (set Int))"
, "(declare-fun @@lambda@@_0 (Int Int) (set Int))"
, "(declare-fun @@lambda@@_1 (Int) (Array Int Int))"
, "(define-fun all@@Int () (set Int) ( (as const (set Int)) true ))"
, "(define-fun compl@@Int"
, " ( (s1 (set Int)) )"
, " (set Int)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun elem@@Int"
, " ( (x Int)"
, " (s1 (set Int)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun empty-set@@Int"
, " ()"
, " (set Int)"
, " ( (as const (set Int))"
, " false ))"
, "(define-fun set-diff@@Int"
, " ( (s1 (set Int))"
, " (s2 (set Int)) )"
, " (set Int)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun st-subset@@Int"
, " ( (s1 (set Int))"
, " (s2 (set Int)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(assert (forall ( (term (Array Int Int)) )"
, " (! (= (qsum@@Int empty-set@@Int term) 0)"
, " :pattern"
, " ( (qsum@@Int empty-set@@Int term) ))))"
, "(assert (forall ( (r (set Int))"
, " (term (Array Int Int))"
, " (x Int) )"
, " (! (=> (not (elem@@Int x r))"
, " (= (qsum@@Int (union r (mk-set@@Int x)) term)"
, " (+ (qsum@@Int r term) (select term x))))"
, " :pattern"
, " ( (qsum@@Int (union r (mk-set@@Int x)) term) ))))"
, "(assert (forall ( (r (set Int))"
, " (r0 (set Int))"
, " (term (Array Int Int)) )"
, " (! (=> (= (intersect r r0) empty-set@@Int)"
, " (= (qsum@@Int (union r r0) term)"
, " (+ (qsum@@Int r term) (qsum@@Int r0 term))))"
, " :pattern"
, " ( (qsum@@Int (union r r0) term) ))))"
, "(assert (forall ( (r (set Int)) )"
, " (! (=> (finite@@Int r) (<= 0 (card@@Int r)))"
, " :pattern"
, " ( (<= 0 (card@@Int r)) ))))"
, "(assert (forall ( (r (set Int)) )"
, " (! (= (= (card@@Int r) 0) (= r empty-set@@Int))"
, " :pattern"
, " ( (card@@Int r) ))))"
, "(assert (forall ( (x Int) )"
, " (! (= (card@@Int (mk-set@@Int x)) 1)"
, " :pattern"
, " ( (card@@Int (mk-set@@Int x)) ))))"
, "(assert (forall ( (r (set Int)) )"
, " (! (= (= (card@@Int r) 1)"
, " (exists ( (x Int) ) (and true (= r (mk-set@@Int x)))))"
, " :pattern"
, " ( (card@@Int r) ))))"
, "(assert (forall ( (r (set Int))"
, " (r0 (set Int)) )"
, " (! (=> (= (intersect r r0) empty-set@@Int)"
, " (= (card@@Int (union r r0))"
, " (+ (card@@Int r) (card@@Int r0))))"
, " :pattern"
, " ( (card@@Int (union r r0)) ))))"
, "(assert (forall ( (r (set Int)) )"
, " (! (= (card@@Int r) (qsum@@Int r (const@@Int@@Int 1)))"
, " :pattern"
, " ( (card@@Int r) ))))"
, "(assert (forall ( (x Int)"
, " (y Int) )"
, " (! (= (select (const@@Int@@Int x) y) x)"
, " :pattern"
, " ( (select (const@@Int@@Int x) y) ))))"
, "(assert (forall ( (x Int) )"
, " (! (= (select ident@@Int x) x)"
, " :pattern"
, " ( (select ident@@Int x) ))))"
, "(assert (= (dom@@Int@@Int empty-fun@@Int@@Int)"
, " empty-set@@Int))"
, "(assert (forall ( (t (Array Int Int)) )"
, " (! (= (lambda@@Int@@Int empty-set@@Int t)"
, " empty-fun@@Int@@Int)"
, " :pattern"
, " ( (lambda@@Int@@Int empty-set@@Int t) ))))"
, "(assert (forall ( (r (set Int))"
, " (t (Array Int Int)) )"
, " (! (= (dom@@Int@@Int (lambda@@Int@@Int r t)) r)"
, " :pattern"
, " ( (dom@@Int@@Int (lambda@@Int@@Int r t)) ))))"
, "(assert (forall ( (t (Array Int Int))"
, " (x Int) )"
, " (! (= (lambda@@Int@@Int (mk-set@@Int x) t)"
, " (mk-fun@@Int@@Int x (select t x)))"
, " :pattern"
, " ( (lambda@@Int@@Int (mk-set@@Int x) t) ))))"
, "(assert (forall ( (r (set Int))"
, " (t (Array Int Int))"
, " (x Int) )"
, " (! (= (ovl@@Int@@Int (lambda@@Int@@Int r t)"
, " (mk-fun@@Int@@Int x (select t x)))"
, " (lambda@@Int@@Int (union r (mk-set@@Int x)) t))"
, " :pattern"
, " ( (ovl@@Int@@Int (lambda@@Int@@Int r t)"
, " (mk-fun@@Int@@Int x (select t x))) ))))"
, "(assert (forall ( (r (set Int))"
, " (r0 (set Int))"
, " (t (Array Int Int)) )"
, " (! (= (ovl@@Int@@Int (lambda@@Int@@Int r t) (lambda@@Int@@Int r0 t))"
, " (lambda@@Int@@Int (union r r0) t))"
, " :pattern"
, " ( (ovl@@Int@@Int (lambda@@Int@@Int r t) (lambda@@Int@@Int r0 t)) ))))"
, "(assert (forall ( (f1 (pfun Int Int)) )"
, " (! (= (ovl@@Int@@Int f1 empty-fun@@Int@@Int) f1)"
, " :pattern"
, " ( (ovl@@Int@@Int f1 empty-fun@@Int@@Int) ))))"
, "(assert (forall ( (f1 (pfun Int Int)) )"
, " (! (= (ovl@@Int@@Int empty-fun@@Int@@Int f1) f1)"
, " :pattern"
, " ( (ovl@@Int@@Int empty-fun@@Int@@Int f1) ))))"
, "(assert (forall ( (x Int)"
, " (y Int) )"
, " (! (= (dom@@Int@@Int (mk-fun@@Int@@Int x y))"
, " (mk-set@@Int x))"
, " :pattern"
, " ( (dom@@Int@@Int (mk-fun@@Int@@Int x y)) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (f2 (pfun Int Int))"
, " (x Int) )"
, " (! (=> (elem@@Int x (dom@@Int@@Int f2))"
, " (= (apply@@Int@@Int (ovl@@Int@@Int f1 f2) x)"
, " (apply@@Int@@Int f2 x)))"
, " :pattern"
, " ( (apply@@Int@@Int (ovl@@Int@@Int f1 f2) x) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (f2 (pfun Int Int))"
, " (x Int) )"
, " (! (=> (and (elem@@Int x (dom@@Int@@Int f1))"
, " (not (elem@@Int x (dom@@Int@@Int f2))))"
, " (= (apply@@Int@@Int (ovl@@Int@@Int f1 f2) x)"
, " (apply@@Int@@Int f1 x)))"
, " :pattern"
, " ( (apply@@Int@@Int (ovl@@Int@@Int f1 f2) x) ))))"
, "(assert (forall ( (x Int)"
, " (y Int) )"
, " (! (= (apply@@Int@@Int (mk-fun@@Int@@Int x y) x) y)"
, " :pattern"
, " ( (apply@@Int@@Int (mk-fun@@Int@@Int x y) x) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (s1 (set Int))"
, " (x Int) )"
, " (! (=> (and (elem@@Int x s1) (elem@@Int x (dom@@Int@@Int f1)))"
, " (= (apply@@Int@@Int (dom-rest@@Int@@Int s1 f1) x)"
, " (apply@@Int@@Int f1 x)))"
, " :pattern"
, " ( (apply@@Int@@Int (dom-rest@@Int@@Int s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (s1 (set Int))"
, " (x Int) )"
, " (! (=> (elem@@Int x (set-diff@@Int (dom@@Int@@Int f1) s1))"
, " (= (apply@@Int@@Int (dom-subt@@Int@@Int s1 f1) x)"
, " (apply@@Int@@Int f1 x)))"
, " :pattern"
, " ( (apply@@Int@@Int (dom-subt@@Int@@Int s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (f2 (pfun Int Int)) )"
, " (! (= (dom@@Int@@Int (ovl@@Int@@Int f1 f2))"
, " (union (dom@@Int@@Int f1) (dom@@Int@@Int f2)))"
, " :pattern"
, " ( (dom@@Int@@Int (ovl@@Int@@Int f1 f2)) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (s1 (set Int)) )"
, " (! (= (dom@@Int@@Int (dom-rest@@Int@@Int s1 f1))"
, " (intersect s1 (dom@@Int@@Int f1)))"
, " :pattern"
, " ( (dom@@Int@@Int (dom-rest@@Int@@Int s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (s1 (set Int)) )"
, " (! (= (dom@@Int@@Int (dom-subt@@Int@@Int s1 f1))"
, " (set-diff@@Int (dom@@Int@@Int f1) s1))"
, " :pattern"
, " ( (dom@@Int@@Int (dom-subt@@Int@@Int s1 f1)) ))))"
, "(assert (forall ( (r (set Int))"
, " (t (Array Int Int))"
, " (x Int) )"
, " (! (=> (elem@@Int x r)"
, " (= (apply@@Int@@Int (lambda@@Int@@Int r t) x)"
, " (select t x)))"
, " :pattern"
, " ( (apply@@Int@@Int (lambda@@Int@@Int r t) x) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (x Int)"
, " (y Int) )"
, " (! (= (and (elem@@Int x (dom@@Int@@Int f1))"
, " (= (apply@@Int@@Int f1 x) y))"
, " (= (select f1 x) (Just y)))"
, " :pattern"
, " ( (elem@@Int x (dom@@Int@@Int f1))"
, " (apply@@Int@@Int f1 x)"
, " (select f1 x)"
, " (Just y) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (x Int)"
, " (x2 Int)"
, " (y Int) )"
, " (! (=> (not (= x x2))"
, " (= (apply@@Int@@Int (ovl@@Int@@Int f1 (mk-fun@@Int@@Int x y)) x2)"
, " (apply@@Int@@Int f1 x2)))"
, " :pattern"
, " ( (apply@@Int@@Int (ovl@@Int@@Int f1 (mk-fun@@Int@@Int x y)) x2) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (x Int)"
, " (y Int) )"
, " (! (= (apply@@Int@@Int (ovl@@Int@@Int f1 (mk-fun@@Int@@Int x y)) x)"
, " y)"
, " :pattern"
, " ( (apply@@Int@@Int (ovl@@Int@@Int f1 (mk-fun@@Int@@Int x y)) x) ))))"
, "(assert (= (ran@@Int@@Int empty-fun@@Int@@Int)"
, " empty-set@@Int))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (y Int) )"
, " (! (= (elem@@Int y (ran@@Int@@Int f1))"
, " (exists ( (x Int) )"
, " (and true"
, " (and (elem@@Int x (dom@@Int@@Int f1))"
, " (= (apply@@Int@@Int f1 x) y)))))"
, " :pattern"
, " ( (elem@@Int y (ran@@Int@@Int f1)) ))))"
, "(assert (forall ( (x Int)"
, " (y Int) )"
, " (! (= (ran@@Int@@Int (mk-fun@@Int@@Int x y))"
, " (mk-set@@Int y))"
, " :pattern"
, " ( (ran@@Int@@Int (mk-fun@@Int@@Int x y)) ))))"
, "(assert (forall ( (f1 (pfun Int Int)) )"
, " (! (= (injective@@Int@@Int f1)"
, " (forall ( (x Int)"
, " (x2 Int) )"
, " (=> (and (elem@@Int x (dom@@Int@@Int f1))"
, " (elem@@Int x2 (dom@@Int@@Int f1)))"
, " (=> (= (apply@@Int@@Int f1 x) (apply@@Int@@Int f1 x2))"
, " (= x x2)))))"
, " :pattern"
, " ( (injective@@Int@@Int f1) ))))"
, "(assert (injective@@Int@@Int empty-fun@@Int@@Int))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (x Int) )"
, " (! (=> (elem@@Int x (dom@@Int@@Int f1))"
, " (elem@@Int (apply@@Int@@Int f1 x) (ran@@Int@@Int f1)))"
, " :pattern"
, " ( (elem@@Int (apply@@Int@@Int f1 x) (ran@@Int@@Int f1)) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (s1 (set Int))"
, " (x Int) )"
, " (! (=> (elem@@Int x (set-diff@@Int (dom@@Int@@Int f1) s1))"
, " (elem@@Int (apply@@Int@@Int f1 x)"
, " (ran@@Int@@Int (dom-subt@@Int@@Int s1 f1))))"
, " :pattern"
, " ( (elem@@Int (apply@@Int@@Int f1 x)"
, " (ran@@Int@@Int (dom-subt@@Int@@Int s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (s1 (set Int))"
, " (x Int) )"
, " (! (=> (elem@@Int x (intersect (dom@@Int@@Int f1) s1))"
, " (elem@@Int (apply@@Int@@Int f1 x)"
, " (ran@@Int@@Int (dom-rest@@Int@@Int s1 f1))))"
, " :pattern"
, " ( (elem@@Int (apply@@Int@@Int f1 x)"
, " (ran@@Int@@Int (dom-rest@@Int@@Int s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (x Int)"
, " (y Int) )"
, " (! (=> (and (elem@@Int x (dom@@Int@@Int f1))"
, " (injective@@Int@@Int f1))"
, " (= (ran@@Int@@Int (ovl@@Int@@Int f1 (mk-fun@@Int@@Int x y)))"
, " (union (set-diff@@Int (ran@@Int@@Int f1)"
, " (mk-set@@Int (apply@@Int@@Int f1 x)))"
, " (mk-set@@Int y))))"
, " :pattern"
, " ( (ran@@Int@@Int (ovl@@Int@@Int f1 (mk-fun@@Int@@Int x y))) ))))"
, "(assert (forall ( (f1 (pfun Int Int))"
, " (x Int)"
, " (y Int) )"
, " (! (=> (not (elem@@Int x (dom@@Int@@Int f1)))"
, " (= (ran@@Int@@Int (ovl@@Int@@Int f1 (mk-fun@@Int@@Int x y)))"
, " (union (ran@@Int@@Int f1) (mk-set@@Int y))))"
, " :pattern"
, " ( (ran@@Int@@Int (ovl@@Int@@Int f1 (mk-fun@@Int@@Int x y))) ))))"
, "(assert (forall ( (x Int)"
, " (y Int) )"
, " (! (= (elem@@Int x (mk-set@@Int y)) (= x y))"
, " :pattern"
, " ( (elem@@Int x (mk-set@@Int y)) ))))"
, "(assert (forall ( (r1 (set Int))"
, " (term (Array Int Int))"
, " (y Int) )"
, " (! (= (elem@@Int y (set@@Int@@Int r1 term))"
, " (exists ( (x Int) )"
, " (and (elem@@Int x r1) (= (select term x) y))))"
, " :pattern"
, " ( (elem@@Int y (set@@Int@@Int r1 term)) ))))"
, "(assert (forall ( (r1 (set Int))"
, " (term (Array Int Int))"
, " (y Int) )"
, " (! (= (= (set@@Int@@Int r1 term) (mk-set@@Int y))"
, " (forall ( (x Int) )"
, " (=> (elem@@Int x r1) (= (select term x) y))))"
, " :pattern"
, " ( (set@@Int@@Int r1 term)"
, " (mk-set@@Int y) ))))"
, "(assert (forall ( (s1 (set Int))"
, " (s2 (set Int)) )"
, " (! (=> (finite@@Int s1)"
, " (finite@@Int (set-diff@@Int s1 s2)))"
, " :pattern"
, " ( (finite@@Int (set-diff@@Int s1 s2)) ))))"
, "(assert (forall ( (s1 (set Int))"
, " (s2 (set Int)) )"
, " (! (=> (and (finite@@Int s1) (finite@@Int s2))"
, " (finite@@Int (union s1 s2)))"
, " :pattern"
, " ( (finite@@Int (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set Int))"
, " (s2 (set Int)) )"
, " (! (=> (and (finite@@Int s2) (not (finite@@Int s1)))"
, " (not (finite@@Int (set-diff@@Int s1 s2))))"
, " :pattern"
, " ( (finite@@Int (set-diff@@Int s1 s2)) ))))"
, "(assert (forall ( (x Int) )"
, " (! (finite@@Int (mk-set@@Int x))"
, " :pattern"
, " ( (finite@@Int (mk-set@@Int x)) ))))"
, "(assert (finite@@Int empty-set@@Int))"
, "(assert (forall ( (r1 (set Int)) )"
, " (! (= (set@@Int@@Int r1 ident@@Int) r1)"
, " :pattern"
, " ( (set@@Int@@Int r1 ident@@Int) ))))"
, "(assert (forall ( (@@fv@@_0 Int)"
, " (@@bv@@_0 Int) )"
, " (! (= (select (@@lambda@@_1 @@fv@@_0) @@bv@@_0)"
, " (^ @@bv@@_0 @@fv@@_0))"
, " :pattern"
, " ( (select (@@lambda@@_1 @@fv@@_0) @@bv@@_0) ))))"
, "(assert (forall ( (@@fv@@_0 Int)"
, " (@@fv@@_1 Int)"
, " (@@bv@@_0 Int) )"
, " (! (= (elem@@Int @@bv@@_0 (@@lambda@@_0 @@fv@@_0 @@fv@@_1))"
, " (and (<= @@fv@@_0 @@bv@@_0) (< @@bv@@_0 @@fv@@_1)))"
, " :pattern"
, " ( (elem@@Int @@bv@@_0 (@@lambda@@_0 @@fv@@_0 @@fv@@_1)) ))))"
, "; a0"
, "(assert (= n@prime (+ n 1)))"
, "; a1"
, "(assert (= a@prime (+ a b)))"
, "; a2"
, "(assert (= b@prime (+ b c)))"
, "; a3"
, "(assert (= c@prime (+ c 6)))"
, "; a4"
, "(assert (= f@prime (ovl@@Int@@Int f (mk-fun@@Int@@Int n a))))"
, "; inv0"
, "(assert (= a (^ n 3)))"
, "; inv1"
, "(assert (= b (+ (+ (* 3 (^ n 2)) (* 3 n)) 1)))"
, "; inv2"
, "(assert (= c (+ (* 6 n) 6)))"
, "; inv3"
, "(assert (= f"
, " (lambda@@Int@@Int (@@lambda@@_0 0 n) (@@lambda@@_1 3))))"
, "; inv4"
, "(assert (<= 0 n))"
, "; inv5"
, "(assert (forall ( (i Int) )"
, " (! (=> (and (<= 0 i) (< i n))"
, " (= (apply@@Int@@Int f i) (^ i 3)))"
, " :pattern"
, " ( (apply@@Int@@Int f i) ))))"
, "; inv6"
, "(assert (= (dom@@Int@@Int f)"
, " (set@@Int@@Int (@@lambda@@_0 0 n) ident@@Int)))"
, "(assert (not (= (dom@@Int@@Int f@prime)"
, " (set@@Int@@Int (@@lambda@@_0 0 n@prime) ident@@Int))))"
, "(check-sat-using (or-else (then qe smt)"
, " (then simplify smt)"
, " (then skip smt)"
, " (then (using-params simplify :expand-power true) smt)))"
, "; m0/evt/INV/inv6"
]
| literate-unitb/literate-unitb | src/Document/Tests/Lambdas.hs | mit | 65,368 | 0 | 17 | 25,962 | 5,827 | 3,664 | 2,163 | -1 | -1 |
module ParserTests where
class C a where
c :: a -> a
a1 :: C a => a -> a
a1 = c
a2 :: (a -> b) -> a -> b
a2 x = x
| antalsz/hs-to-coq | examples/tests/ParserTests.hs | mit | 119 | 0 | 7 | 41 | 71 | 38 | 33 | 7 | 1 |
{--
Copyright (c) 2014 Gorka Suárez García
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--}
{- ***************************************************************
You are given the following information, but you may prefer
to do some research for yourself.
+ 1 Jan 1900 was a Monday.
+ Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
+ A leap year occurs on any year evenly divisible by 4,
but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the
twentieth century (1 Jan 1901 to 31 Dec 2000)?
*************************************************************** -}
module Problem0019 (main) where
isDiv :: (Integral a) => a -> a -> Bool
isDiv a b = (0 == mod a b)
inRange :: (Integral a) => a -> a -> a -> Bool
inRange x min max = min <= x && x <= max
-- ***************************************************************
type Year = Integer
type Month = Int
type Day = Int
type WeekDay = Int
type Date = (Year, Month, Day)
-- ***************************************************************
daysByYear = 365
daysByYear' = 366
daysByMonth = [31,28,31,30,31,30,31,31,30,31,30,31]
daysByMonth' = [31,29,31,30,31,30,31,31,30,31,30,31]
months = ["January","February","March","April",
"May","June","July","August",
"September","October","November","December"]
sundayId = 1
mondayId = 2
tuesdayId = 3
wednesdayId = 4
thursdayId = 5
fridayId = 6
saturdayId = 7
days = ["Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday"]
monthToString :: Int -> String
monthToString m = if isValid then value else ""
where isValid = inRange m 1 12
value = months !! (m - 1)
dayToString :: Int -> String
dayToString d = if isValid then value else ""
where isValid = inRange d 1 7
value = days !! (d - 1)
-- ***************************************************************
isLeapYear :: (Integral a) => a -> Bool
isLeapYear y = (fid 4) && ((fid 400) || not (fid 100))
where fid b = isDiv y b
getDaysByYear :: (Integral a) => a -> Int
getDaysByYear y = if isLeapYear y then daysByYear'
else daysByYear
getDaysByYear' :: (Integral a) => a -> Integer
getDaysByYear' y = toInteger $ getDaysByYear y
getDaysByMonth :: (Integral a) => a -> [Int]
getDaysByMonth y = if isLeapYear y then daysByMonth'
else daysByMonth
-- ***************************************************************
dateToInt :: Date -> Integer
dateToInt (y, m, d)
| y < 0 = -((toInteger d) + dm + (yti' y))
| otherwise = (toInteger d) + dm + (yti y)
where dm = toInteger $ sum $ take (m - 1) (getDaysByMonth y)
yti x = if x <= 0 then 0 else dby + (yti (x - 1))
where dby = getDaysByYear' (x - 1)
yti' x = if x >= -1 then 0 else dby + (yti' (x + 1))
where dby = getDaysByYear' (x + 1)
getYearFromInt :: Integer -> Integer
getYearFromInt n
| n < 0 = fndy' n (-1) 0
| otherwise = fndy n 0 0
where fndy m y c = if v < m then fndy m (y+1) v else y
where v = c + getDaysByYear' y
fndy' m y c = if v > m then fndy' m (y-1) v else y
where v = c - getDaysByYear' y
remYearFromInt :: Integer -> Integer
remYearFromInt n = abs(n - m)
where y = getYearFromInt n
m = dateToInt (y, 0, 0)
remYearFromInt' :: Integer -> Integer -> Integer
remYearFromInt' n y = abs(n - m)
where m = dateToInt (y, 0, 0)
intToDate :: Integer -> Date
intToDate n = (y, m, d)
where y = getYearFromInt n
md = fromIntegral $ remYearFromInt' n y
dbm = getDaysByMonth y
gdm md' m'
| md' > d' = gdm (md' - d') (m' + 1)
| otherwise = (m', md')
where d' = dbm !! (m' - 1)
(m, d) = gdm md 1
-- ***************************************************************
-- (1900, 1, 1) -> Monday
firstDay1900 :: Date
firstDay1900 = (1900, 1, 1)
firstDay1900' = dateToInt firstDay1900
getWeekDay :: Date -> WeekDay
getWeekDay d = fromIntegral ((mod delta 7) + 1)
where delta = (dateToInt d) - (firstDay1900' - 1)
getWeekDay' :: Integer -> WeekDay
getWeekDay' n = fromIntegral ((mod delta 7) + 1)
where delta = n - (firstDay1900' - 1)
-- ***************************************************************
findNextDay :: WeekDay -> Integer -> Integer
findNextDay wd n
| wd == v = n
| otherwise = findNextDay wd (n + 1)
where v = getWeekDay' n
-- findSundaysOnFirst 1901 2000 = 171
findSundaysOnFirst :: Year -> Year -> Integer
findSundaysOnFirst y1 y2 = toInteger $ length lst
where d1 = dateToInt (y1, 1, 1)
d2 = dateToInt (y2, 12, 31)
d1a = findNextDay sundayId d1
d1b = d1a + 7
lst = [(y,m,d) | (y,m,d) <- [intToDate x | x <-
[d1a,d1b..d2]], d == 1]
-- findSundaysOn1st 1901 2000 = 171
findSundaysOn1st :: Year -> Year -> Integer
findSundaysOn1st y1 y2 = toInteger $ length lst
where d1 = (y1, 1, 1)
d2 = (y2, 12, 31)
getLst (ya,ma,da) (yb,mb,db)
| ya <= yb = (ya,ma,da) : next
| otherwise = []
where aux = ma + 1
ma' = if aux > 12 then 1 else aux
ya' = if aux > 12 then ya + 1 else ya
next = getLst (ya',ma',da) (yb,mb,db)
lst = [x | x <- getLst d1 d2, sundayId == getWeekDay x]
main = do putStr "The number of Sundays that fell on the first "
putStr "of the month during the 20th century is "
putStrLn (show result ++ ".")
where result = findSundaysOn1st 1901 2000 | gorkinovich/Haskell | Problems/Problem0019.hs | mit | 6,830 | 0 | 13 | 1,789 | 1,915 | 1,048 | 867 | 117 | 3 |
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE GADTs #-}
module Editor where
import Reflex
import Reflex.Dom
import Reflex.Dom.Class
import Control.Monad.IO.Class
import Data.Set (Set)
import Text.Pandoc
import Reflex.Dynamic.TH
import Data.Bool (bool)
import Data.Map (findWithDefault)
import qualified Data.Set as Set
import GHCJS.Foreign
import LocalStorage (getPref)
import Widgets.CodeMirror
import Widgets.Dialog.Location
import Widgets.Dialog.OpenFile
import Example
import Widgets.Setting
import Formats
import Widgets.Menu
import Widgets.Misc (icon, lastDoc, lastExt)
data Component = Reader | Writer
editor :: (MonadWidget t m)
=> m (Selection t,CodeMirror t,Dynamic t (Set Extension))
editor =
do (openFileModal,(fileContents,fileExt)) <- openFileDialog
(locationModal,(locationContents,locationExt)) <- locationDialog
rec ext <- liftIO lastExt
doc <- liftIO lastDoc
d <-
divClass "ui top left attached label" $
selection $
SelectionConfig ext
(findWithDefault "Markdown" ext resultFormats)
(constDyn sourceFormats)
(leftmost [locationExt,dropboxExt, fileExt])
((advancedEditor,insertSp,exts), (dropboxContents,dropboxExt)) <-
divClass "ui top right attached label" $
do dbox <- openMenu openFileModal locationModal
let input = attachDyn (_selection_value d) (updated $ value t)
makeSaveMenu "Save" input (ext,doc)
s <- settings
return (s, dbox)
cmEnabled <-
liftIO $
getPref "CodeMirror Editor" True
t <-
codeMirror
def {_codeMirrorConfig_initialValue = doc
,_codeMirrorConfig_enabled = cmEnabled
,_codeMirrorConfig_enableCodeMirror =
updated advancedEditor
,_codeMirrorConfig_insertSpaces =
updated insertSp
,_codeMirrorConfig_changeLang =
updated (value d)
,_codeMirrorConfig_setValue =
leftmost [locationContents,dropboxContents, fileContents]}
return (d,t,exts)
settings :: (MonadWidget t m)
=> m (Dynamic t Bool, Dynamic t Bool, Dynamic t (Set Extension))
settings =
do (menu,children) <-
elAttr' "div" ("class" =: "ui left dropdown compact icon button") $
do icon "settings"
divClass "menu" $
do divClass "header" (text "Source Settings")
(advancedEditor,insertSp) <-
divClass "item" $
do advancedEditor <-
setting "CodeMirror Editor" True
insertSp <-
divClass "left menu" $
do divClass "item" $
setting "Use spaces for indentation" False
return ((value advancedEditor),(value insertSp))
divClass "header" (text "Markdown")
exts <- extensions Reader "md"
return (advancedEditor,insertSp,exts)
liftIO $
enableMenu (_el_element menu)
(toJSString "nothing")
return children
extensions :: (MonadWidget t m)
=> Component -> String -> m (Dynamic t (Set Extension))
extensions component lang =
do exts <-
do exts <-
mapM (\(label,modifier) ->
do s <-
divClass "item" $
setting label False
mapDyn (bool id modifier)
(_setting_value s))
(stringToExtensions component "md")
mconcatDyn exts
$(qDyn [|$(unqDyn [|exts|]) defaultExtensions|])
stringToExtensions :: Component
-> String
-> [(String,Set Extension -> Set Extension)]
stringToExtensions Reader "md" =
[("Hard Line Breaks",Set.insert Ext_hard_line_breaks)
,("GitHub Flavored"
,Set.delete Ext_hard_line_breaks .
Set.delete Ext_emoji .
Set.union githubMarkdownExtensions)]
stringToExtensions _ _ = []
defaultExtensions :: Set Extension
defaultExtensions =
Set.difference pandocExtensions
(Set.fromList [Ext_raw_tex,Ext_latex_macros])
| osener/markup.rocks | src/Editor.hs | mit | 4,673 | 1 | 24 | 1,739 | 1,098 | 568 | 530 | 114 | 1 |
{-# LANGUAGE
RecordWildCards,
ExplicitNamespaces,
PolyKinds,
DataKinds,
ScopedTypeVariables
#-}
module ZipperN (
type ZipperN
) where
import Data.Array
import Data.List
import Data.Functor
import Data.Foldable
import Data.Traversable
import Data.Proxy
import Control.Applicative
import Control.Comonad
import GHC.TypeLits
import Vector
data ZipperN (n :: Nat) a = ZipperN {
_pos :: !(Vector n Integer),
_max :: !(Vector n Integer),
_arr :: (Array (Vector n Integer) a)
}
dimension :: KnownNat n => ZipperN n a -> Integer
dimension (z :: ZipperN n a) = natVal (Proxy :: Proxy n)
-- | Smart constructor
zipper :: KnownNat n => Vector n Integer -> [(Vector n Integer, a)] -> ZipperN n a
zipper hiBound vals = ZipperN { _pos = repeatV 0, _max = hiBound, _arr = array (repeatV 0, hiBound) vals }
posZ, sizeZ :: ZipperN n a -> Vector n Integer
posZ = _pos
sizeZ = _max
-- | Generate a zipper from its size and an expression for its elements
generateZipper :: KnownNat n => Vector n Integer -> (Vector n Integer -> a) -> ZipperN n a
generateZipper hiBound f = zipper hiBound [(ix, f ix) | ix <- range (repeatV 0, hiBound)]
-- | Set the zipper's pointer to a position
(|=>) :: (KnownNat n, Integral i) => ZipperN n a -> Vector n i -> ZipperN n a
z |=> p | p `within` z = z { _pos = fmap toInteger p }
-- | Move the zipper's pointer by a delta
(||=>) :: (KnownNat n, Integral i) => ZipperN n a -> Vector n i -> ZipperN n a
z ||=> d = z |=> ((+) <$> _pos z <*> fmap toInteger d)
-- | Same as ||=>, but wraps around instead of erroring if it goes out of bounds.
(||@>) :: (KnownNat n, Integral i) => ZipperN n a -> Vector n i -> ZipperN n a
z ||@> d = z |=> (mod <$> ((+) <$> _pos z <*> fmap toInteger d) <*> _max z)
-- | Get the zipper's value at a point
(|=?) :: (KnownNat n, Integral i) => ZipperN n a -> Vector n i -> a
z |=? p = extract $ z |=> p
-- | Get the zipper's value at an offset
(||=?) :: (KnownNat n, Integral i) => ZipperN n a -> Vector n i -> a
z ||=? p = extract $ z ||=> p
-- | Get the zipper's value at an offset (wraparound)
(||@?) :: (KnownNat n, Integral i) => ZipperN n a -> Vector n i -> a
z ||@? p = extract $ z ||@> p
-- | Check that a vector points into the zipper
within :: (KnownNat n, Integral i) => Vector n i -> ZipperN n a -> Bool
p `within` z = inRange (repeatV 0, fmap (\x -> x - 1) $ _max z) (fmap toInteger p)
-- | We do not show all the elements,
-- because in most cases there are way too many.
instance (Show a, KnownNat n) => Show (ZipperN n a) where
show z@(ZipperN{..}) = (show $ sizeV _max)
++ "-dimensional tensor zipper, sized "
++ intercalate "x" (map show $ toList _max)
++ " with "
++ show (product $ toList _max)
++ " entries total. The focus is on the element ("
++ show (extract z)
++ "), positioned at "
++ show _pos
instance KnownNat n => Functor (ZipperN n) where
fmap f z = z { _arr = fmap f (_arr z) }
instance KnownNat n => Foldable (ZipperN n) where
foldr f x0 z = foldr f x0 (_arr z)
instance KnownNat n => Traversable (ZipperN n) where
sequenceA ZipperN{..} = ZipperN _pos _max <$> sequenceA _arr
instance KnownNat n => Comonad (ZipperN n) where
extract ZipperN{..} = _arr ! _pos
duplicate z@(ZipperN{..}) = generateZipper _max (\ix -> ZipperN {_pos = ix, ..}) | Solonarv/Zipper | ZipperN.hs | mit | 3,507 | 0 | 16 | 937 | 1,295 | 670 | 625 | 68 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
import Gelatin.SDL2 hiding (move)
import SDL
import Gelatin.FreeType2
import Odin.GUI
import Odin.Core
import Control.Lens
import Halive.Utils
import qualified Demos.Physics as Physics
import qualified Demos.Animation as Animation
runFrame :: MonadIO m => UpdateT m a -> StateT Frame m a
runFrame f = do
io $ glClearColor 0.5 0.5 0.5 1
use rez >>= io . clearFrame
tickTime
tickUIPrepare
e <- runEventT f
use window >>= io . updateWindowSDL2
case e of
Left g -> runFrame g
Right a -> return a
data DemoSelection = DemoPhysics | DemoAnimation
demoSelectTask :: MonadIO m => UpdateT m ()
demoSelectTask = withDefaultStatusBar white $ \status ->
withDefaultButton "Physics" $ \physBtn -> do
V2 physw physh <- sizeOfButton physBtn
withDefaultButton "Animation" $ \aniBtn -> do
selection <- slot DemoAnimation
physDemo <- Physics.allocDemo
aniDemo <- Animation.allocDemo
fix $ \continue -> do
V2 _ ch <- (io . SDL.get . windowSize) =<< use window
let wh = fromIntegral ch
renderStatusBar status [move 0 $ wh - 2]
renderButton physBtn [] >>= \case
ButtonStateClicked -> do
reslot selection DemoPhysics
Physics.resumeDemo physDemo
_ -> return ()
renderButton aniBtn [move (physw + 4) 0] >>= \case
ButtonStateClicked -> do
reslot selection DemoAnimation
Physics.pauseDemo physDemo
_ -> return ()
let rs = [move 0 $ physh + 4]
unslot selection >>= \case
DemoPhysics -> Physics.renderDemo physDemo rs
DemoAnimation -> Animation.renderDemo aniDemo rs
next continue
main :: IO ()
main = do
(rz,win) <- reacquire 0 $ startupSDL2Backend 800 600 "Entity Sandbox" True
t <- newTime
let firstFrame = Frame { _frameTime = t
, _frameEvents = []
, _frameNextK = 0
, _frameWindow = win
, _frameRez = rz
, _frameFonts = mempty
}
void $ runStateT (runFrame demoSelectTask) firstFrame
| schell/odin | app/EntityMain.hs | mit | 2,378 | 0 | 26 | 779 | 677 | 328 | 349 | 63 | 4 |
{-# LANGUAGE ViewPatterns #-}
{- |
Used for building symmetrical sequences from one half of the symmetrical shape.
Eg: An oval can be described by giving the radius of the first 180 degrees, then reversing these first 180 degrees, and adding them on to the tail.
Note though, that the 180th degree would be there twice, which has to be handled.
-}
module Tests.Symmetrical.SequenceTest where
import qualified Data.Sequence as S
import qualified Data.Foldable as F
import Test.HUnit
import qualified Helpers.Symmetrical.Sequence as SS (mirror, mirrorPlusMidPoint, mirrorMinusMidPoint)
import qualified Helpers.Symmetrical.List as SL (mirror, mirrorPlusMidPoint, mirrorMinusMidPoint)
sequenceTestDo = do
-- ================================================= Sequence =======================================
let mirrorTestSeq = TestCase $ assertEqual
"mirrorTestSeq"
[1,2,3,3,2,1]
(
F.toList $ SS.mirror $ S.fromList [1,2,3]
)
runTestTT mirrorTestSeq
let mirrorPlusMidPointSeqTest = TestCase $ assertEqual
"mirrorPlusMidPointSeqTest"
[1,2,3,2,1]
(
F.toList $ SS.mirrorPlusMidPoint (S.fromList [1,2]) 3
)
runTestTT mirrorPlusMidPointSeqTest
let mirrorMinusMidPointSeqTest = TestCase $ assertEqual
"mirrorMinusMidPointSeqTest"
[1,2,3,2,1]
(
F.toList $ SS.mirrorMinusMidPoint (S.fromList [1,2,3])
)
runTestTT mirrorMinusMidPointSeqTest
-- ================================================== List ===========================================
let mirrorTestList = TestCase $ assertEqual
"mirrorTestList"
[1,2,3,3,2,1]
(
SL.mirror [1,2,3]
)
runTestTT mirrorTestList
let mirrorPlusMidPointListTest = TestCase $ assertEqual
"mirrorPlusMidPointListTest"
[1,2,3,2,1]
(
SL.mirrorPlusMidPoint [1,2] 3
)
runTestTT mirrorPlusMidPointListTest
let mirrorMinusMidPointListTest = TestCase $ assertEqual
"mirrorMinusMidPointListTest"
[1,2,3,2,1]
(
SL.mirrorMinusMidPoint [1,2,3]
)
runTestTT mirrorMinusMidPointListTest
| heathweiss/Tricad | src/Tests/Symmetrical/SequenceTest.hs | gpl-2.0 | 2,242 | 0 | 17 | 548 | 469 | 263 | 206 | 44 | 1 |
{-# OPTIONS -w -O0 #-}
{- |
Module : ExtModal/ATC_ExtModal.der.hs
Description : generated Typeable, ShATermConvertible instances
Copyright : (c) DFKI Bremen 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : non-portable(overlapping Typeable instances)
Automatic derivation of instances via DrIFT-rule Typeable, ShATermConvertible
for the type(s):
'ExtModal.AS_ExtModal.ModDefn'
'ExtModal.AS_ExtModal.EM_BASIC_ITEM'
'ExtModal.AS_ExtModal.ModOp'
'ExtModal.AS_ExtModal.MODALITY'
'ExtModal.AS_ExtModal.EM_SIG_ITEM'
'ExtModal.AS_ExtModal.EM_FORMULA'
'ExtModal.ExtModalSign.EModalSign'
'ExtModal.MorphismExtension.MorphExtension'
'ExtModal.Sublogic.Frequency'
'ExtModal.Sublogic.Sublogic'
-}
{-
Generated by 'genRules' (automatic rule generation for DrIFT). Don't touch!!
dependency files:
ExtModal/AS_ExtModal.hs
ExtModal/ExtModalSign.hs
ExtModal/MorphismExtension.hs
ExtModal/Sublogic.hs
-}
module ExtModal.ATC_ExtModal () where
import ATerm.Lib
import CASL.AS_Basic_CASL
import CASL.ATC_CASL
import CASL.MapSentence
import CASL.Morphism
import CASL.Sign
import Common.AS_Annotation
import Common.Doc
import Common.DocUtils
import Common.Id
import Common.Utils
import Data.Typeable
import ExtModal.AS_ExtModal
import ExtModal.ExtModalSign
import ExtModal.MorphismExtension
import ExtModal.Print_AS ()
import ExtModal.Sublogic
import qualified Common.Lib.MapSet as MapSet
import qualified Data.Map as Map
import qualified Data.Set as Set
{-! for ExtModal.AS_ExtModal.ModDefn derive : Typeable !-}
{-! for ExtModal.AS_ExtModal.EM_BASIC_ITEM derive : Typeable !-}
{-! for ExtModal.AS_ExtModal.ModOp derive : Typeable !-}
{-! for ExtModal.AS_ExtModal.MODALITY derive : Typeable !-}
{-! for ExtModal.AS_ExtModal.EM_SIG_ITEM derive : Typeable !-}
{-! for ExtModal.AS_ExtModal.EM_FORMULA derive : Typeable !-}
{-! for ExtModal.ExtModalSign.EModalSign derive : Typeable !-}
{-! for ExtModal.MorphismExtension.MorphExtension derive : Typeable !-}
{-! for ExtModal.Sublogic.Frequency derive : Typeable !-}
{-! for ExtModal.Sublogic.Sublogic derive : Typeable !-}
{-! for ExtModal.AS_ExtModal.ModDefn derive : ShATermConvertible !-}
{-! for ExtModal.AS_ExtModal.EM_BASIC_ITEM derive : ShATermConvertible !-}
{-! for ExtModal.AS_ExtModal.ModOp derive : ShATermConvertible !-}
{-! for ExtModal.AS_ExtModal.MODALITY derive : ShATermConvertible !-}
{-! for ExtModal.AS_ExtModal.EM_SIG_ITEM derive : ShATermConvertible !-}
{-! for ExtModal.AS_ExtModal.EM_FORMULA derive : ShATermConvertible !-}
{-! for ExtModal.ExtModalSign.EModalSign derive : ShATermConvertible !-}
{-! for ExtModal.MorphismExtension.MorphExtension derive : ShATermConvertible !-}
{-! for ExtModal.Sublogic.Frequency derive : ShATermConvertible !-}
{-! for ExtModal.Sublogic.Sublogic derive : ShATermConvertible !-}
| nevrenato/Hets_Fork | ExtModal/ATC_ExtModal.der.hs | gpl-2.0 | 2,873 | 0 | 4 | 308 | 145 | 101 | 44 | 22 | 0 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, DeriveDataTypeable
, FlexibleInstances, UndecidableInstances, ExistentialQuantification #-}
{- |
Module : $Header$
Description : interface and class for logic translations
Copyright : (c) Till Mossakowski, Uni Bremen 2002-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : till@informatik.uni-bremen.de
Stability : provisional
Portability : non-portable (via Logic)
Central interface (type class) for logic translations (comorphisms) in Hets
These are just collections of
functions between (some of) the types of logics.
References: see Logic.hs
-}
module Logic.Comorphism
( CompComorphism (..)
, InclComorphism
, inclusion_logic
, inclusion_source_sublogic
, inclusion_target_sublogic
, mkInclComorphism
, mkIdComorphism
, Comorphism (..)
, targetSublogic
, map_sign
, wrapMapTheory
, mkTheoryMapping
, AnyComorphism (..)
, idComorphism
, isIdComorphism
, isModelTransportable
, hasModelExpansion
, isWeaklyAmalgamable
, compComorphism
) where
import Logic.Logic
import Logic.Coerce
import Common.AS_Annotation
import Common.Doc
import Common.DocUtils
import Common.Id
import Common.LibName
import Common.ProofUtils
import Common.Result
import Data.Maybe
import qualified Data.Set as Set
import Data.Typeable
class (Language cid,
Logic lid1 sublogics1
basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1,
Logic lid2 sublogics2
basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2) =>
Comorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2
| cid -> lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2
where
{- source and target logic and sublogic
the source sublogic is the maximal one for which the comorphism works -}
sourceLogic :: cid -> lid1
sourceSublogic :: cid -> sublogics1
sourceSublogic cid = top_sublogic $ sourceLogic cid
minSourceTheory :: cid -> Maybe (LibName, String)
minSourceTheory _ = Nothing
targetLogic :: cid -> lid2
{- finer information of target sublogics corresponding to source sublogics
this function must be partial because mapTheory is partial -}
mapSublogic :: cid -> sublogics1 -> Maybe sublogics2
mapSublogic cid _ = Just $ top_sublogic $ targetLogic cid
{- the translation functions are partial
because the target may be a sublanguage
map_basic_spec :: cid -> basic_spec1 -> Result basic_spec2
cover theoroidal comorphisms as well -}
map_theory :: cid -> (sign1, [Named sentence1])
-> Result (sign2, [Named sentence2])
-- map_theory but also consider sentence marks
mapMarkedTheory :: cid -> (sign1, [Named sentence1])
-> Result (sign2, [Named sentence2])
mapMarkedTheory cid (sig, sens) = do
(sig2, sens2) <- map_theory cid (sig, map unmark sens)
return (sig2, map (markSen $ language_name cid) sens2)
map_morphism :: cid -> morphism1 -> Result morphism2
map_morphism = mapDefaultMorphism
map_sentence :: cid -> sign1 -> sentence1 -> Result sentence2
{- also covers semi-comorphisms
with no sentence translation
- but these are spans! -}
map_sentence = failMapSentence
map_symbol :: cid -> sign1 -> symbol1 -> Set.Set symbol2
map_symbol = errMapSymbol
extractModel :: cid -> sign1 -> proof_tree2
-> Result (sign1, [Named sentence1])
extractModel cid _ _ = fail
$ "extractModel not implemented for comorphism "
++ language_name cid
-- properties of comorphisms
is_model_transportable :: cid -> Bool
{- a comorphism (\phi, \alpha, \beta) is model-transportable
if for any signature \Sigma,
any \Sigma-model M and any \phi(\Sigma)-model N
for any isomorphism h : \beta_\Sigma(N) -> M
there exists an isomorphism h': N -> M' such that \beta_\Sigma(h') = h -}
is_model_transportable _ = False
has_model_expansion :: cid -> Bool
has_model_expansion _ = False
is_weakly_amalgamable :: cid -> Bool
is_weakly_amalgamable _ = False
constituents :: cid -> [String]
constituents cid = [language_name cid]
isInclusionComorphism :: cid -> Bool
isInclusionComorphism _ = False
targetSublogic :: Comorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2
=> cid -> sublogics2
targetSublogic cid = fromMaybe (top_sublogic $ targetLogic cid)
$ mapSublogic cid $ sourceSublogic cid
-- | this function is based on 'map_theory' using no sentences as input
map_sign :: Comorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2
=> cid -> sign1 -> Result (sign2, [Named sentence2])
map_sign cid sign = wrapMapTheory cid (sign, [])
mapDefaultMorphism :: Comorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2
=> cid -> morphism1 -> Result morphism2
mapDefaultMorphism cid mor = do
(sig1, _) <- map_sign cid $ dom mor
(sig2, _) <- map_sign cid $ cod mor
inclusion (targetLogic cid) sig1 sig2
failMapSentence :: Comorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2
=> cid -> sign1 -> sentence1 -> Result sentence2
failMapSentence cid _ _ =
fail $ "Unsupported sentence translation " ++ show cid
errMapSymbol :: Comorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2
=> cid -> sign1 -> symbol1 -> Set.Set symbol2
errMapSymbol cid _ _ = error $ "no symbol mapping for " ++ show cid
-- | use this function instead of 'mapMarkedTheory'
wrapMapTheory :: Comorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2
=> cid -> (sign1, [Named sentence1])
-> Result (sign2, [Named sentence2])
wrapMapTheory cid (sign, sens) =
let res = mapMarkedTheory cid (sign, sens)
lid1 = sourceLogic cid
thDoc = show (vcat $ pretty sign : map (print_named lid1) sens)
in
if isIdComorphism $ Comorphism cid then res else case sourceSublogic cid of
sub -> case minSublogic sign of
sigLog -> case foldl lub sigLog
$ map (minSublogic . sentence) sens of
senLog ->
if isSubElem senLog sub
then res
else Result
[ Diag Hint thDoc nullRange
, Diag Error
("for '" ++ language_name cid ++
"' expected sublogic '" ++
sublogicName sub ++
"'\n but found sublogic '" ++
sublogicName senLog ++
"' with signature sublogic '" ++
sublogicName sigLog ++ "'") nullRange] Nothing
mkTheoryMapping :: Monad m => (sign1 -> m (sign2, [Named sentence2]))
-> (sign1 -> sentence1 -> m sentence2)
-> (sign1, [Named sentence1])
-> m (sign2, [Named sentence2])
mkTheoryMapping mapSig mapSen (sign, sens) = do
(sign', sens') <- mapSig sign
sens'' <- mapM (mapNamedM (mapSen sign) . unmark) sens
return (sign', nameAndDisambiguate
$ map (markSen "SignatureProperty") sens' ++ sens'')
data InclComorphism lid sublogics = InclComorphism
{ inclusion_logic :: lid
, inclusion_source_sublogic :: sublogics
, inclusion_target_sublogic :: sublogics }
deriving Show
-- | construction of an identity comorphism
mkIdComorphism :: (Logic lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism symbol raw_symbol proof_tree) =>
lid -> sublogics -> InclComorphism lid sublogics
mkIdComorphism lid sub = InclComorphism
{ inclusion_logic = lid
, inclusion_source_sublogic = sub
, inclusion_target_sublogic = sub }
-- | construction of an inclusion comorphism
mkInclComorphism :: (Logic lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism symbol raw_symbol proof_tree,
Monad m) =>
lid -> sublogics -> sublogics
-> m (InclComorphism lid sublogics)
mkInclComorphism lid srcSub trgSub =
if isSubElem srcSub trgSub
then return InclComorphism
{ inclusion_logic = lid
, inclusion_source_sublogic = srcSub
, inclusion_target_sublogic = trgSub }
else fail ("mkInclComorphism: first sublogic must be a " ++
"subElem of the second sublogic")
instance (Language lid, Eq sublogics, Show sublogics, SublogicName sublogics)
=> Language (InclComorphism lid sublogics) where
language_name (InclComorphism lid sub_src sub_trg) =
let sblName = sublogicName sub_src
lname = language_name lid
in if sub_src == sub_trg
then "id_" ++ lname ++
if null sblName then "" else '.' : sblName
else "incl_" ++ lname ++ ':'
: sblName ++ "->" ++ sublogicName sub_trg
instance Logic lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism symbol raw_symbol proof_tree =>
Comorphism (InclComorphism lid sublogics)
lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism symbol raw_symbol proof_tree
lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism symbol raw_symbol proof_tree
where
sourceLogic = inclusion_logic
targetLogic = inclusion_logic
sourceSublogic = inclusion_source_sublogic
mapSublogic cid subl =
if isSubElem subl $ inclusion_source_sublogic cid
then Just subl
else Nothing
map_theory _ = return
map_morphism _ = return
map_sentence _ _ = return
map_symbol _ _ = Set.singleton
constituents cid =
if inclusion_source_sublogic cid
== inclusion_target_sublogic cid
then []
else [language_name cid]
is_model_transportable _ = True
has_model_expansion _ = True
is_weakly_amalgamable _ = True
isInclusionComorphism _ = True
data CompComorphism cid1 cid2 = CompComorphism cid1 cid2 deriving Show
instance (Language cid1, Language cid2)
=> Language (CompComorphism cid1 cid2) where
language_name (CompComorphism cid1 cid2) =
language_name cid1 ++ ";" ++ language_name cid2
instance (Comorphism cid1
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2,
Comorphism cid2
lid4 sublogics4 basic_spec4 sentence4 symb_items4 symb_map_items4
sign4 morphism4 symbol4 raw_symbol4 proof_tree4
lid3 sublogics3 basic_spec3 sentence3 symb_items3 symb_map_items3
sign3 morphism3 symbol3 raw_symbol3 proof_tree3)
=> Comorphism (CompComorphism cid1 cid2)
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid3 sublogics3 basic_spec3 sentence3 symb_items3 symb_map_items3
sign3 morphism3 symbol3 raw_symbol3 proof_tree3 where
sourceLogic (CompComorphism cid1 _) =
sourceLogic cid1
targetLogic (CompComorphism _ cid2) =
targetLogic cid2
sourceSublogic (CompComorphism cid1 _) =
sourceSublogic cid1
mapSublogic (CompComorphism cid1 cid2) sl =
mapSublogic cid1 sl >>=
mapSublogic cid2 .
forceCoerceSublogic (targetLogic cid1) (sourceLogic cid2)
map_sentence (CompComorphism cid1 cid2) si1 se1 =
do (si2, _) <- map_sign cid1 si1
se2 <- map_sentence cid1 si1 se1
(si2', se2') <- coerceBasicTheory
(targetLogic cid1) (sourceLogic cid2)
"Mapping sentence along comorphism" (si2, [makeNamed "" se2])
case se2' of
[x] -> map_sentence cid2 si2' $ sentence x
_ -> error "CompComorphism.map_sentence"
map_theory (CompComorphism cid1 cid2) ti1 =
do ti2 <- map_theory cid1 ti1
ti2' <- coerceBasicTheory (targetLogic cid1) (sourceLogic cid2)
"Mapping theory along comorphism" ti2
wrapMapTheory cid2 ti2'
map_morphism (CompComorphism cid1 cid2) m1 =
do m2 <- map_morphism cid1 m1
m3 <- coerceMorphism (targetLogic cid1) (sourceLogic cid2)
"Mapping signature morphism along comorphism" m2
map_morphism cid2 m3
map_symbol (CompComorphism cid1 cid2) sig1 = let
th = map_sign cid1 sig1 in
case maybeResult th of
Nothing -> error "failed translating signature"
Just (sig2', _) -> let
th2 = coerceBasicTheory
(targetLogic cid1) (sourceLogic cid2)
"Mapping symbol along comorphism" (sig2', [])
in case maybeResult th2 of
Nothing -> error "failed coercing"
Just (sig2, _) ->
\ s1 ->
let mycast = coerceSymbol (targetLogic cid1) (sourceLogic cid2)
in Set.unions
(map (map_symbol cid2 sig2 . mycast)
(Set.toList (map_symbol cid1 sig1 s1)))
extractModel (CompComorphism cid1 cid2) sign pt3 =
let lid1 = sourceLogic cid1
lid3 = sourceLogic cid2
in if language_name lid1 == language_name lid3 then do
bTh1 <- map_sign cid1 sign
(sign1, _) <-
coerceBasicTheory (targetLogic cid1) lid3 "extractModel1" bTh1
bTh2 <- extractModel cid2 sign1 pt3
coerceBasicTheory lid3 lid1 "extractModel2" bTh2
else fail $ "extractModel not implemented for comorphism composition with "
++ language_name cid1
constituents (CompComorphism cid1 cid2) =
constituents cid1 ++ constituents cid2
is_model_transportable (CompComorphism cid1 cid2) =
is_model_transportable cid1 && is_model_transportable cid2
has_model_expansion (CompComorphism cid1 cid2) =
has_model_expansion cid1 && has_model_expansion cid2
is_weakly_amalgamable (CompComorphism cid1 cid2) =
is_weakly_amalgamable cid1 && is_weakly_amalgamable cid2
isInclusionComorphism (CompComorphism cid1 cid2) =
isInclusionComorphism cid1 && isInclusionComorphism cid2
-- * Comorphisms and existential types for the logic graph
-- | Existential type for comorphisms
data AnyComorphism = forall cid lid1 sublogics1
basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2
basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2 .
Comorphism cid
lid1 sublogics1 basic_spec1 sentence1
symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2
symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2 =>
Comorphism cid deriving Typeable -- used for GTheory
instance Eq AnyComorphism where
a == b = compare a b == EQ
instance Ord AnyComorphism where
compare (Comorphism cid1) (Comorphism cid2) = compare
(language_name cid1, constituents cid1)
(language_name cid2, constituents cid2)
-- maybe needs to be refined, using comorphism translations?
instance Show AnyComorphism where
show (Comorphism cid) = language_name cid
++ " : " ++ language_name (sourceLogic cid)
++ " -> " ++ language_name (targetLogic cid)
instance Pretty AnyComorphism where
pretty = text . show
-- | compute the identity comorphism for a logic
idComorphism :: AnyLogic -> AnyComorphism
idComorphism (Logic lid) = Comorphism (mkIdComorphism lid (top_sublogic lid))
-- | Test whether a comporphism is the identity
isIdComorphism :: AnyComorphism -> Bool
isIdComorphism (Comorphism cid) = null $ constituents cid
-- * Properties of comorphisms
-- | Test whether a comorphism is model-transportable
isModelTransportable :: AnyComorphism -> Bool
isModelTransportable (Comorphism cid) = is_model_transportable cid
-- | Test whether a comorphism has model expansion
hasModelExpansion :: AnyComorphism -> Bool
hasModelExpansion (Comorphism cid) = has_model_expansion cid
-- | Test whether a comorphism is weakly amalgamable
isWeaklyAmalgamable :: AnyComorphism -> Bool
isWeaklyAmalgamable (Comorphism cid) = is_weakly_amalgamable cid
-- | Compose comorphisms
compComorphism :: Monad m => AnyComorphism -> AnyComorphism -> m AnyComorphism
compComorphism (Comorphism cid1) (Comorphism cid2) =
let l1 = targetLogic cid1
l2 = sourceLogic cid2
msg = "ogic mismatch in composition of " ++ language_name cid1
++ " and " ++ language_name cid2
in
if language_name l1 == language_name l2 then
if isSubElem (forceCoerceSublogic l1 l2 $ targetSublogic cid1)
$ sourceSublogic cid2
then return $ Comorphism (CompComorphism cid1 cid2)
else fail $ "Subl" ++ msg ++ " (Expected sublogic "
++ sublogicName (sourceSublogic cid2)
++ " but found sublogic "
++ sublogicName (targetSublogic cid1) ++ ")"
else fail $ 'L' : msg ++ " (Expected logic "
++ language_name l2
++ " but found logic "
++ language_name l1 ++ ")"
| nevrenato/HetsAlloy | Logic/Comorphism.hs | gpl-2.0 | 19,889 | 0 | 30 | 5,582 | 4,158 | 2,128 | 2,030 | 370 | 3 |
// Functor composition between Maybe and []
//
maybeTail :: [a] -> Maybe [a]
maybeTail [] = Nothing
maybeTail (x:xs) = Just xs
// The result of maybeTail is of a type thats a composition of two functors,
// Maybe and [], acting on a. Each of these functors has its own version of fmap.
square x = x * x
mis :: Maybe [Int]
mis = Just [1, 2, 3]
mis2 = fmap (fmap square) mis
// The compiler, after analyzing the types, will figure out that, for the outer fmap,
// it should use the implementation from the Maybe instance, and for the inner one,
// the list functor implementation.
// It may not be immediately obvious that the above code may be rewritten as:
mis3 = (fmap . fmap) square mis
// the first fmap is:
// fmap1 :: (Int -> Int) -> [Int] -> [Int]
// the second is
// fmap2 :: ([Int] -> [Int]) -> Maybe [Int] -> Maybe [Int]
//
// the composed function looks like
// fmap2 . fmap1 :: (Int -> Int) -> Maybe [Int] -> Maybe [Int]
//
| sujeet4github/MyLangUtils | CategoryTheory_BartoszMilewsky/PI_07_Functors/MaybeTail.hs | gpl-3.0 | 944 | 39 | 9 | 195 | 469 | 242 | 227 | 8 | 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.AdExchangeBuyer2.Accounts.PublisherProFiles.List
-- 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)
--
-- List all publisher profiles visible to the buyer
--
-- /See:/ <https://developers.google.com/authorized-buyers/apis/reference/rest/ Ad Exchange Buyer API II Reference> for @adexchangebuyer2.accounts.publisherProfiles.list@.
module Network.Google.Resource.AdExchangeBuyer2.Accounts.PublisherProFiles.List
(
-- * REST Resource
AccountsPublisherProFilesListResource
-- * Creating a Request
, accountsPublisherProFilesList
, AccountsPublisherProFilesList
-- * Request Lenses
, appflXgafv
, appflUploadProtocol
, appflAccessToken
, appflUploadType
, appflAccountId
, appflPageToken
, appflPageSize
, appflCallback
) where
import Network.Google.AdExchangeBuyer2.Types
import Network.Google.Prelude
-- | A resource alias for @adexchangebuyer2.accounts.publisherProfiles.list@ method which the
-- 'AccountsPublisherProFilesList' request conforms to.
type AccountsPublisherProFilesListResource =
"v2beta1" :>
"accounts" :>
Capture "accountId" Text :>
"publisherProfiles" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListPublisherProFilesResponse
-- | List all publisher profiles visible to the buyer
--
-- /See:/ 'accountsPublisherProFilesList' smart constructor.
data AccountsPublisherProFilesList =
AccountsPublisherProFilesList'
{ _appflXgafv :: !(Maybe Xgafv)
, _appflUploadProtocol :: !(Maybe Text)
, _appflAccessToken :: !(Maybe Text)
, _appflUploadType :: !(Maybe Text)
, _appflAccountId :: !Text
, _appflPageToken :: !(Maybe Text)
, _appflPageSize :: !(Maybe (Textual Int32))
, _appflCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountsPublisherProFilesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'appflXgafv'
--
-- * 'appflUploadProtocol'
--
-- * 'appflAccessToken'
--
-- * 'appflUploadType'
--
-- * 'appflAccountId'
--
-- * 'appflPageToken'
--
-- * 'appflPageSize'
--
-- * 'appflCallback'
accountsPublisherProFilesList
:: Text -- ^ 'appflAccountId'
-> AccountsPublisherProFilesList
accountsPublisherProFilesList pAppflAccountId_ =
AccountsPublisherProFilesList'
{ _appflXgafv = Nothing
, _appflUploadProtocol = Nothing
, _appflAccessToken = Nothing
, _appflUploadType = Nothing
, _appflAccountId = pAppflAccountId_
, _appflPageToken = Nothing
, _appflPageSize = Nothing
, _appflCallback = Nothing
}
-- | V1 error format.
appflXgafv :: Lens' AccountsPublisherProFilesList (Maybe Xgafv)
appflXgafv
= lens _appflXgafv (\ s a -> s{_appflXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
appflUploadProtocol :: Lens' AccountsPublisherProFilesList (Maybe Text)
appflUploadProtocol
= lens _appflUploadProtocol
(\ s a -> s{_appflUploadProtocol = a})
-- | OAuth access token.
appflAccessToken :: Lens' AccountsPublisherProFilesList (Maybe Text)
appflAccessToken
= lens _appflAccessToken
(\ s a -> s{_appflAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
appflUploadType :: Lens' AccountsPublisherProFilesList (Maybe Text)
appflUploadType
= lens _appflUploadType
(\ s a -> s{_appflUploadType = a})
-- | Account ID of the buyer.
appflAccountId :: Lens' AccountsPublisherProFilesList Text
appflAccountId
= lens _appflAccountId
(\ s a -> s{_appflAccountId = a})
-- | The page token as return from ListPublisherProfilesResponse.
appflPageToken :: Lens' AccountsPublisherProFilesList (Maybe Text)
appflPageToken
= lens _appflPageToken
(\ s a -> s{_appflPageToken = a})
-- | Specify the number of results to include per page.
appflPageSize :: Lens' AccountsPublisherProFilesList (Maybe Int32)
appflPageSize
= lens _appflPageSize
(\ s a -> s{_appflPageSize = a})
. mapping _Coerce
-- | JSONP
appflCallback :: Lens' AccountsPublisherProFilesList (Maybe Text)
appflCallback
= lens _appflCallback
(\ s a -> s{_appflCallback = a})
instance GoogleRequest AccountsPublisherProFilesList
where
type Rs AccountsPublisherProFilesList =
ListPublisherProFilesResponse
type Scopes AccountsPublisherProFilesList =
'["https://www.googleapis.com/auth/adexchange.buyer"]
requestClient AccountsPublisherProFilesList'{..}
= go _appflAccountId _appflXgafv _appflUploadProtocol
_appflAccessToken
_appflUploadType
_appflPageToken
_appflPageSize
_appflCallback
(Just AltJSON)
adExchangeBuyer2Service
where go
= buildClient
(Proxy ::
Proxy AccountsPublisherProFilesListResource)
mempty
| brendanhay/gogol | gogol-adexchangebuyer2/gen/Network/Google/Resource/AdExchangeBuyer2/Accounts/PublisherProFiles/List.hs | mpl-2.0 | 6,107 | 0 | 19 | 1,396 | 882 | 509 | 373 | 132 | 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.CloudIdentity.Groups.Memberships.Create
-- 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)
--
-- Creates a \`Membership\`.
--
-- /See:/ <https://cloud.google.com/identity/ Cloud Identity API Reference> for @cloudidentity.groups.memberships.create@.
module Network.Google.Resource.CloudIdentity.Groups.Memberships.Create
(
-- * REST Resource
GroupsMembershipsCreateResource
-- * Creating a Request
, groupsMembershipsCreate
, GroupsMembershipsCreate
-- * Request Lenses
, gmcParent
, gmcXgafv
, gmcUploadProtocol
, gmcAccessToken
, gmcUploadType
, gmcPayload
, gmcCallback
) where
import Network.Google.CloudIdentity.Types
import Network.Google.Prelude
-- | A resource alias for @cloudidentity.groups.memberships.create@ method which the
-- 'GroupsMembershipsCreate' request conforms to.
type GroupsMembershipsCreateResource =
"v1" :>
Capture "parent" Text :>
"memberships" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Membership :> Post '[JSON] Operation
-- | Creates a \`Membership\`.
--
-- /See:/ 'groupsMembershipsCreate' smart constructor.
data GroupsMembershipsCreate =
GroupsMembershipsCreate'
{ _gmcParent :: !Text
, _gmcXgafv :: !(Maybe Xgafv)
, _gmcUploadProtocol :: !(Maybe Text)
, _gmcAccessToken :: !(Maybe Text)
, _gmcUploadType :: !(Maybe Text)
, _gmcPayload :: !Membership
, _gmcCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GroupsMembershipsCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gmcParent'
--
-- * 'gmcXgafv'
--
-- * 'gmcUploadProtocol'
--
-- * 'gmcAccessToken'
--
-- * 'gmcUploadType'
--
-- * 'gmcPayload'
--
-- * 'gmcCallback'
groupsMembershipsCreate
:: Text -- ^ 'gmcParent'
-> Membership -- ^ 'gmcPayload'
-> GroupsMembershipsCreate
groupsMembershipsCreate pGmcParent_ pGmcPayload_ =
GroupsMembershipsCreate'
{ _gmcParent = pGmcParent_
, _gmcXgafv = Nothing
, _gmcUploadProtocol = Nothing
, _gmcAccessToken = Nothing
, _gmcUploadType = Nothing
, _gmcPayload = pGmcPayload_
, _gmcCallback = Nothing
}
-- | Required. The parent \`Group\` resource under which to create the
-- \`Membership\`. Must be of the form \`groups\/{group_id}\`.
gmcParent :: Lens' GroupsMembershipsCreate Text
gmcParent
= lens _gmcParent (\ s a -> s{_gmcParent = a})
-- | V1 error format.
gmcXgafv :: Lens' GroupsMembershipsCreate (Maybe Xgafv)
gmcXgafv = lens _gmcXgafv (\ s a -> s{_gmcXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
gmcUploadProtocol :: Lens' GroupsMembershipsCreate (Maybe Text)
gmcUploadProtocol
= lens _gmcUploadProtocol
(\ s a -> s{_gmcUploadProtocol = a})
-- | OAuth access token.
gmcAccessToken :: Lens' GroupsMembershipsCreate (Maybe Text)
gmcAccessToken
= lens _gmcAccessToken
(\ s a -> s{_gmcAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
gmcUploadType :: Lens' GroupsMembershipsCreate (Maybe Text)
gmcUploadType
= lens _gmcUploadType
(\ s a -> s{_gmcUploadType = a})
-- | Multipart request metadata.
gmcPayload :: Lens' GroupsMembershipsCreate Membership
gmcPayload
= lens _gmcPayload (\ s a -> s{_gmcPayload = a})
-- | JSONP
gmcCallback :: Lens' GroupsMembershipsCreate (Maybe Text)
gmcCallback
= lens _gmcCallback (\ s a -> s{_gmcCallback = a})
instance GoogleRequest GroupsMembershipsCreate where
type Rs GroupsMembershipsCreate = Operation
type Scopes GroupsMembershipsCreate =
'["https://www.googleapis.com/auth/cloud-identity.groups",
"https://www.googleapis.com/auth/cloud-platform"]
requestClient GroupsMembershipsCreate'{..}
= go _gmcParent _gmcXgafv _gmcUploadProtocol
_gmcAccessToken
_gmcUploadType
_gmcCallback
(Just AltJSON)
_gmcPayload
cloudIdentityService
where go
= buildClient
(Proxy :: Proxy GroupsMembershipsCreateResource)
mempty
| brendanhay/gogol | gogol-cloudidentity/gen/Network/Google/Resource/CloudIdentity/Groups/Memberships/Create.hs | mpl-2.0 | 5,199 | 0 | 17 | 1,173 | 783 | 457 | 326 | 114 | 1 |
{-
tempgres, REST service for creating temporary PostgreSQL databases.
Copyright (C) 2014-2020 Bardur Arantsson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
module Tempgres.Mutex
( Mutex
, mkMutex
, withMutex
) where
import Control.Exception (bracket_)
import Control.Concurrent.QSem (QSem, newQSem, waitQSem, signalQSem)
-- Mutex type
newtype Mutex = Mutex QSem
-- Creates a mutex based on semaphores. The mutex takes the form a
-- function which can be called with an IO action to perform that
-- action in a critical section.
mkMutex :: IO Mutex
mkMutex = do
semaphore <- newQSem 1
return $ Mutex semaphore
-- Run a computation in a critical section.
withMutex :: Mutex -> IO a -> IO a
withMutex (Mutex semaphore) action =
bracket_ (waitQSem semaphore) (signalQSem semaphore) action
| ClockworkConsulting/tempgres-server | server/src/Tempgres/Mutex.hs | agpl-3.0 | 1,452 | 0 | 8 | 298 | 148 | 82 | 66 | 14 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module SchemaScaffold (prefixesOf, classInfos, scaffold) where
import Data.List (partition)
import Text.XML.Light
import Data.Text (unpack, toLower)
import Data.Map (toList)
import Swish.RDF
import Swish.Namespace (ScopedName, getScopeLocal)
import Swish.QName (getLName, LName)
import Swish.RDF.Vocabulary.OWL
import Swish.RDF.Query (rdfFindValSubj, rdfFindPredVal)
import System.Directory
import System.FilePath( (</>), (<.>) )
mkDir :: FilePath -> IO ()
mkDir = createDirectoryIfMissing True
instancesOf :: RDFLabel -> RDFGraph -> [RDFLabel]
instancesOf = rdfFindValSubj resRdfType
classesOf :: RDFGraph -> [RDFLabel]
classesOf = instancesOf resRdfsClass
xmlns :: String -> String -> Attr
xmlns prefix = Attr $ QName prefix Nothing (Just "xmlns")
data Subject = Subject {
name :: ScopedName,
dataProps :: [(String, String, String)],
objectProps :: [(String, String)]
} deriving (Show, Eq)
prefixesOf :: NSGraph lb -> [Attr]
prefixesOf g = [ xmlns (unpack p) (show u) | (Just p, u) <- toList $ namespaces g ]
--classNames g = [ getScopeLocal sn | Res sn <- classesOf g ]
classInfos :: NSGraph RDFLabel -> [Subject]
classInfos g = map classInfo $ classesOf g
where
classInfo klass = Subject (getScopedName klass) dataProps' objectProps'
where
props = rdfFindValSubj resRdfsDomain klass g
graphDataProps = rdfFindValSubj resRdfType (Res owlDatatypeProperty) g
(dataProperties, objectProperties) = partition (\p-> elem p graphDataProps) props
dataProps' = [ (show p, (unpack . getLName . localName) p, show $ head $ rdfFindPredVal p resRdfsRange g) | p <- dataProperties ]
objectProps' = [ (show p, (unpack . getLName . localName) p) | p <- objectProperties ]
localName :: RDFLabel -> LName
localName = getScopeLocal . getScopedName
layout :: [Attr] -> [Element] -> Element
layout prefixes content =
unode "html" (prefixes, [
unode "head" (),
unode "body" content
])
index :: Subject -> [Element]
index subject =
[
unode "div" ([about ("[" ++ show (name subject) ++ "]"), rev "rdf:type"], individual subject)
]
individual :: Subject -> [Element]
individual (Subject name dataProps objectProps) =
[
unode "div" [
unode "p" [
unode "b" (l ++ ":"),
unode "span" [property p, datatype t]
]
| (p, l, t) <- dataProps ],
unode "div" [
unode "p" ([rel p], [
Text $ blank_cdata {cdData = (l ++ ":")},
Elem $ unode "a" (href "_", unode "span" (property "rdfs:label"))
])
| (p, l) <- objectProps ]
]
attr :: String -> String -> Attr
attr name = Attr (unqual name)
rel, rev, href, about, resource, property, datatype :: String -> Attr
rel = attr "rel"
rev = attr "rev"
href = attr "href"
about = attr "about"
resource = attr "resource"
property = attr "property"
datatype = attr "datatype"
label :: Subject -> String
label = unpack . toLower . getLName . getScopeLocal . name
scaffold :: String -> [Attr] -> Subject -> IO ()
scaffold baseDir prefixes subject = do
let dir = baseDir </> label subject
mkDir dir
writeFile (dir </> "index" <.> "html") $ ppElement $ layout prefixes $ index subject
writeFile (dir </> "_wildcard" <.> "html") $ ppElement $ layout prefixes $ individual subject
| LeifW/yaml2owl | src/SchemaScaffold.hs | lgpl-2.1 | 3,302 | 0 | 16 | 676 | 1,179 | 636 | 543 | 78 | 1 |
import System.Cmd
import System.Environment
import Control.Monad(when)
import Text.JSON
import Data.Array
import DataTypes
import Board
gameOver :: Board -> Bool
gameOver b = not (hasMovesFor b X || hasMovesFor b O)
count :: Board -> State -> Int
count b s = sum [ 1 | (i,j) <- indexes b , value b (i,j) == s ]
winner :: Board -> State
winner b
| gameOver b && ( count b X > count b O ) = X
| gameOver b && ( count b O > count b X ) = O
instance JSON State where
showJSON X = showJSON "X"
showJSON O = showJSON "O"
showJSON E = showJSON "E"
readJSON (JSString s)
| str == "X" = Text.JSON.Ok $ X
| str == "O" = Text.JSON.Ok $ O
| otherwise = Text.JSON.Ok $ E
where str = fromJSString s
boardR :: Result Board -> Board
boardR (Text.JSON.Ok b) = b
moveR :: Result Move -> Move
moveR (Text.JSON.Ok m) = m
main = do
(cmd:args) <- getArgs
if cmd == "play"
then do
let board = (boardR (decode (args!!0) :: Result Board) )
let m = (moveR (decode (args!!1) :: Result Move))
if check board m
then do
let new = flipChains (move board m) (fst m)
if gameOver new
then do
let result = encode (toJSObject [("result", (winner new))])
putStrLn result
else do
putStrLn (encode new)
else
putStrLn (encode board)
else do
putStrLn (encode makeBoard)
| guiocavalcanti/haskell-reversi | MainCommand.hs | lgpl-3.0 | 1,416 | 0 | 25 | 426 | 629 | 312 | 317 | 46 | 4 |
{-# LANGUAGE NamedFieldPuns #-}
module Hecate.Backend.JSON.AppState
( EntriesMap
, AppState (..)
, mkAppState
, put
, delete
, query
, selectAll
, getCount
, getCountOfKeyId
) where
import qualified Data.Maybe as Maybe
import Data.Multimap (Multimap)
import qualified Data.Multimap as Multimap
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Text as Text
import Hecate.Data hiding (query)
type EntriesMap = Multimap Description Entry
data AppState = AppState
{ appStateDirty :: Bool
, appStateData :: EntriesMap
} deriving (Show, Eq)
mkAppState :: [Entry] -> AppState
mkAppState entries = AppState
{ appStateDirty = False
, appStateData = Multimap.fromList (tupler <$> entries)
}
where
tupler ent = (entryDescription ent, ent)
update :: (EntriesMap -> EntriesMap) -> AppState -> AppState
update f state = state{appStateDirty = True, appStateData = updated}
where
updated = f (appStateData state)
put :: Entry -> AppState -> AppState
delete :: Entry -> AppState -> AppState
put ent = update (Multimap.insert (entryDescription ent) ent)
delete ent = update (Multimap.delete (entryDescription ent) ent)
idenIsInfixOf :: Identity -> Identity -> Bool
descIsInfixOf :: Description -> Description -> Bool
idenIsInfixOf (Identity needle) (Identity haystack) = Text.isInfixOf needle haystack
descIsInfixOf (Description needle) (Description haystack) = Text.isInfixOf needle haystack
idenMatcher :: Maybe Identity -> Maybe Identity -> Bool
idenMatcher queryIden entryIden = Maybe.fromMaybe True (idenIsInfixOf <$> queryIden <*> entryIden)
filterEntries :: (Maybe Identity -> Bool) -> Set Entry -> [Entry]
filterEntries predicate = Set.foldr f []
where
f e acc | predicate (entryIdentity e) = e : acc
| otherwise = acc
queryFolder :: Query -> Description -> Set Entry -> [Entry] -> [Entry]
queryFolder (Query (Just eid) Nothing Nothing Nothing) _ es acc
= Set.toList matches ++ acc
where
matches = Set.filter (\ e -> entryId e == eid) es
queryFolder q d es acc
| Just True <- descMatches = filterEntries idenMatches es ++ acc
| otherwise = acc
where
descMatches = descIsInfixOf <$> queryDescription q <*> pure d
idenMatches = idenMatcher (queryIdentity q)
query :: Query -> AppState -> [Entry]
query q AppState{appStateData} = Multimap.foldrWithKey (queryFolder q) [] appStateData
selectAll :: AppState -> [Entry]
selectAll = Multimap.elems . appStateData
getCount :: AppState -> Int
getCount = Multimap.size . appStateData
getCountOfKeyId :: KeyId -> AppState -> Int
getCountOfKeyId keyid = length . filter (\ e -> entryKeyId e == keyid) . selectAll
| henrytill/hecate | src/Hecate/Backend/JSON/AppState.hs | apache-2.0 | 2,775 | 0 | 12 | 585 | 889 | 473 | 416 | 62 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Quasar.Api.Http.Request where
import Control.Applicative
import Control.Lens
import qualified Data.ByteString as BS
import Data.Conduit.List (consume)
import Data.Conduit
import qualified Data.Text as T
import Data.Monoid
import Network.HTTP.Types.Method
import Network.HTTP.Types.URI
import Network.HTTP.Types.Header
import qualified Network.Wai as W
data Request a = Request
{ _requestMethod :: StdMethod
, _requestHeaders :: RequestHeaders
, _requestQuery :: Query
, _requestPath :: [T.Text]
, _requestBody :: a
}
deriving (Eq, Show)
$(makeLenses ''Request)
filterHeaders :: Request a -> (Header -> Bool) -> Request a
filterHeaders request f = requestHeaders .~ (filter f $ request^.requestHeaders) $ request
mapRequestBody :: (a -> b) -> Request a -> Request b
mapRequestBody f request = requestBody .~ (f $ request^.requestBody) $ request
eitherMapRequestBody :: (a -> Either String b) -> Request a -> Either String (Request b)
eitherMapRequestBody f request = case f $ request^.requestBody of
Left error -> Left error
Right body -> Right (requestBody .~ body $ request)
parseRawRequestBody :: W.Request -> IO BS.ByteString
parseRawRequestBody warpRequest = mconcat <$> runResourceT (W.requestBody warpRequest $$ consume)
buildRequest :: W.Request -> BS.ByteString -> Maybe (Request BS.ByteString)
buildRequest warpRequest body = case parseMethod . W.requestMethod $ warpRequest of
Left _ -> Nothing
Right stdMethod -> Just Request
{ _requestMethod = stdMethod
, _requestHeaders = W.requestHeaders warpRequest
, _requestQuery = W.queryString warpRequest
, _requestPath = W.pathInfo warpRequest
, _requestBody = body
} | xdcrafts/Quasar | src/Quasar/Api/Http/Request.hs | apache-2.0 | 1,789 | 0 | 12 | 317 | 526 | 286 | 240 | 41 | 2 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGraphicsPixmapItem_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:16
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QGraphicsPixmapItem_h where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QGraphicsItem
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QGraphicsPixmapItem ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPixmapItem_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QGraphicsPixmapItem_unSetUserMethod" qtc_QGraphicsPixmapItem_unSetUserMethod :: Ptr (TQGraphicsPixmapItem a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QGraphicsPixmapItemSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPixmapItem_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QGraphicsPixmapItem ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPixmapItem_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QGraphicsPixmapItemSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPixmapItem_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QGraphicsPixmapItem ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPixmapItem_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QGraphicsPixmapItemSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPixmapItem_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGraphicsPixmapItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGraphicsPixmapItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsPixmapItem_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setUserMethod" qtc_QGraphicsPixmapItem_setUserMethod :: Ptr (TQGraphicsPixmapItem a) -> CInt -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsPixmapItem :: (Ptr (TQGraphicsPixmapItem x0) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsPixmapItem_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGraphicsPixmapItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGraphicsPixmapItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsPixmapItem_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGraphicsPixmapItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGraphicsPixmapItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsPixmapItem_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setUserMethodVariant" qtc_QGraphicsPixmapItem_setUserMethodVariant :: Ptr (TQGraphicsPixmapItem a) -> CInt -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsPixmapItem :: (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsPixmapItem_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGraphicsPixmapItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGraphicsPixmapItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsPixmapItem_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QGraphicsPixmapItem ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGraphicsPixmapItem_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QGraphicsPixmapItem_unSetHandler" qtc_QGraphicsPixmapItem_unSetHandler :: Ptr (TQGraphicsPixmapItem a) -> CWString -> IO (CBool)
instance QunSetHandler (QGraphicsPixmapItemSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGraphicsPixmapItem_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> IO (QRectF t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> IO (Ptr (TQRectF t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler1" qtc_QGraphicsPixmapItem_setHandler1 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> IO (Ptr (TQRectF t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem1 :: (Ptr (TQGraphicsPixmapItem x0) -> IO (Ptr (TQRectF t0))) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> IO (Ptr (TQRectF t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> IO (QRectF t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> IO (Ptr (TQRectF t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqqboundingRect_h (QGraphicsPixmapItem ()) (()) where
qqboundingRect_h x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPixmapItem_boundingRect cobj_x0
foreign import ccall "qtc_QGraphicsPixmapItem_boundingRect" qtc_QGraphicsPixmapItem_boundingRect :: Ptr (TQGraphicsPixmapItem a) -> IO (Ptr (TQRectF ()))
instance QqqboundingRect_h (QGraphicsPixmapItemSc a) (()) where
qqboundingRect_h x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPixmapItem_boundingRect cobj_x0
instance QqboundingRect_h (QGraphicsPixmapItem ()) (()) where
qboundingRect_h x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPixmapItem_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
foreign import ccall "qtc_QGraphicsPixmapItem_boundingRect_qth" qtc_QGraphicsPixmapItem_boundingRect_qth :: Ptr (TQGraphicsPixmapItem a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QqboundingRect_h (QGraphicsPixmapItemSc a) (()) where
qboundingRect_h x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPixmapItem_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> QPointF t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPointF t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler2" qtc_QGraphicsPixmapItem_setHandler2 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem2 :: (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPointF t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> QPointF t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPointF t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qqcontains_h (QGraphicsPixmapItem ()) ((PointF)) where
qcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsPixmapItem_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y
foreign import ccall "qtc_QGraphicsPixmapItem_contains_qth" qtc_QGraphicsPixmapItem_contains_qth :: Ptr (TQGraphicsPixmapItem a) -> CDouble -> CDouble -> IO CBool
instance Qqcontains_h (QGraphicsPixmapItemSc a) ((PointF)) where
qcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsPixmapItem_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y
instance Qqqcontains_h (QGraphicsPixmapItem ()) ((QPointF t1)) where
qqcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_contains cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_contains" qtc_QGraphicsPixmapItem_contains :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQPointF t1) -> IO CBool
instance Qqqcontains_h (QGraphicsPixmapItemSc a) ((QPointF t1)) where
qqcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_contains cobj_x0 cobj_x1
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> QGraphicsItem t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler3" qtc_QGraphicsPixmapItem_setHandler3 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem3 :: (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> QGraphicsItem t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQObject t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler4" qtc_QGraphicsPixmapItem_setHandler4 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQObject t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem4 :: (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQObject t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQObject t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQObject t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QisObscuredBy_h (QGraphicsPixmapItem ()) ((QGraphicsItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_isObscuredBy cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_isObscuredBy" qtc_QGraphicsPixmapItem_isObscuredBy :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QisObscuredBy_h (QGraphicsPixmapItemSc a) ((QGraphicsItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_isObscuredBy cobj_x0 cobj_x1
instance QisObscuredBy_h (QGraphicsPixmapItem ()) ((QGraphicsTextItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_isObscuredBy_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_isObscuredBy_graphicstextitem" qtc_QGraphicsPixmapItem_isObscuredBy_graphicstextitem :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QisObscuredBy_h (QGraphicsPixmapItemSc a) ((QGraphicsTextItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_isObscuredBy_graphicstextitem cobj_x0 cobj_x1
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> IO (QPainterPath t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> IO (Ptr (TQPainterPath t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler5" qtc_QGraphicsPixmapItem_setHandler5 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> IO (Ptr (TQPainterPath t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem5 :: (Ptr (TQGraphicsPixmapItem x0) -> IO (Ptr (TQPainterPath t0))) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> IO (Ptr (TQPainterPath t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> IO (QPainterPath t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> IO (Ptr (TQPainterPath t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QopaqueArea_h (QGraphicsPixmapItem ()) (()) where
opaqueArea_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPixmapItem_opaqueArea cobj_x0
foreign import ccall "qtc_QGraphicsPixmapItem_opaqueArea" qtc_QGraphicsPixmapItem_opaqueArea :: Ptr (TQGraphicsPixmapItem a) -> IO (Ptr (TQPainterPath ()))
instance QopaqueArea_h (QGraphicsPixmapItemSc a) (()) where
opaqueArea_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPixmapItem_opaqueArea cobj_x0
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- qObjectFromPtr x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler6" qtc_QGraphicsPixmapItem_setHandler6 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem6 :: (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- qObjectFromPtr x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qpaint_h (QGraphicsPixmapItem ()) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where
paint_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGraphicsPixmapItem_paint cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QGraphicsPixmapItem_paint" qtc_QGraphicsPixmapItem_paint :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionGraphicsItem t2) -> Ptr (TQWidget t3) -> IO ()
instance Qpaint_h (QGraphicsPixmapItemSc a) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where
paint_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGraphicsPixmapItem_paint cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance Qshape_h (QGraphicsPixmapItem ()) (()) where
shape_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPixmapItem_shape cobj_x0
foreign import ccall "qtc_QGraphicsPixmapItem_shape" qtc_QGraphicsPixmapItem_shape :: Ptr (TQGraphicsPixmapItem a) -> IO (Ptr (TQPainterPath ()))
instance Qshape_h (QGraphicsPixmapItemSc a) (()) where
shape_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPixmapItem_shape cobj_x0
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler7" qtc_QGraphicsPixmapItem_setHandler7 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem7 :: (Ptr (TQGraphicsPixmapItem x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qqtype_h (QGraphicsPixmapItem ()) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPixmapItem_type cobj_x0
foreign import ccall "qtc_QGraphicsPixmapItem_type" qtc_QGraphicsPixmapItem_type :: Ptr (TQGraphicsPixmapItem a) -> IO CInt
instance Qqtype_h (QGraphicsPixmapItemSc a) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPixmapItem_type cobj_x0
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> CInt -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1int = fromCInt x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler8" qtc_QGraphicsPixmapItem_setHandler8 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem8 :: (Ptr (TQGraphicsPixmapItem x0) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> CInt -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1int = fromCInt x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qadvance_h (QGraphicsPixmapItem ()) ((Int)) where
advance_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPixmapItem_advance cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGraphicsPixmapItem_advance" qtc_QGraphicsPixmapItem_advance :: Ptr (TQGraphicsPixmapItem a) -> CInt -> IO ()
instance Qadvance_h (QGraphicsPixmapItemSc a) ((Int)) where
advance_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPixmapItem_advance cobj_x0 (toCInt x1)
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler9" qtc_QGraphicsPixmapItem_setHandler9 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem9 :: (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler10" qtc_QGraphicsPixmapItem_setHandler10 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem10 :: (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QcollidesWithItem_h (QGraphicsPixmapItem ()) ((QGraphicsItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_collidesWithItem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_collidesWithItem" qtc_QGraphicsPixmapItem_collidesWithItem :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QcollidesWithItem_h (QGraphicsPixmapItemSc a) ((QGraphicsItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_collidesWithItem cobj_x0 cobj_x1
instance QcollidesWithItem_h (QGraphicsPixmapItem ()) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsPixmapItem_collidesWithItem1" qtc_QGraphicsPixmapItem_collidesWithItem1 :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsItem t1) -> CLong -> IO CBool
instance QcollidesWithItem_h (QGraphicsPixmapItemSc a) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcollidesWithItem_h (QGraphicsPixmapItem ()) ((QGraphicsTextItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_collidesWithItem_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_collidesWithItem_graphicstextitem" qtc_QGraphicsPixmapItem_collidesWithItem_graphicstextitem :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QcollidesWithItem_h (QGraphicsPixmapItemSc a) ((QGraphicsTextItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_collidesWithItem_graphicstextitem cobj_x0 cobj_x1
instance QcollidesWithItem_h (QGraphicsPixmapItem ()) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsPixmapItem_collidesWithItem1_graphicstextitem" qtc_QGraphicsPixmapItem_collidesWithItem1_graphicstextitem :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsTextItem t1) -> CLong -> IO CBool
instance QcollidesWithItem_h (QGraphicsPixmapItemSc a) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> QPainterPath t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler11" qtc_QGraphicsPixmapItem_setHandler11 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem11 :: (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> QPainterPath t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler12" qtc_QGraphicsPixmapItem_setHandler12 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem12 :: (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QcollidesWithPath_h (QGraphicsPixmapItem ()) ((QPainterPath t1)) where
collidesWithPath_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_collidesWithPath cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_collidesWithPath" qtc_QGraphicsPixmapItem_collidesWithPath :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQPainterPath t1) -> IO CBool
instance QcollidesWithPath_h (QGraphicsPixmapItemSc a) ((QPainterPath t1)) where
collidesWithPath_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_collidesWithPath cobj_x0 cobj_x1
instance QcollidesWithPath_h (QGraphicsPixmapItem ()) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsPixmapItem_collidesWithPath1" qtc_QGraphicsPixmapItem_collidesWithPath1 :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQPainterPath t1) -> CLong -> IO CBool
instance QcollidesWithPath_h (QGraphicsPixmapItemSc a) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler13" qtc_QGraphicsPixmapItem_setHandler13 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem13 :: (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QcontextMenuEvent_h (QGraphicsPixmapItem ()) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_contextMenuEvent" qtc_QGraphicsPixmapItem_contextMenuEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsSceneContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QGraphicsPixmapItemSc a) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_contextMenuEvent cobj_x0 cobj_x1
instance QdragEnterEvent_h (QGraphicsPixmapItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_dragEnterEvent" qtc_QGraphicsPixmapItem_dragEnterEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragEnterEvent_h (QGraphicsPixmapItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QGraphicsPixmapItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_dragLeaveEvent" qtc_QGraphicsPixmapItem_dragLeaveEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragLeaveEvent_h (QGraphicsPixmapItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QGraphicsPixmapItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_dragMoveEvent" qtc_QGraphicsPixmapItem_dragMoveEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragMoveEvent_h (QGraphicsPixmapItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QGraphicsPixmapItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_dropEvent" qtc_QGraphicsPixmapItem_dropEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdropEvent_h (QGraphicsPixmapItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_dropEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QGraphicsPixmapItem ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_focusInEvent" qtc_QGraphicsPixmapItem_focusInEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QGraphicsPixmapItemSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QGraphicsPixmapItem ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_focusOutEvent" qtc_QGraphicsPixmapItem_focusOutEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QGraphicsPixmapItemSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_focusOutEvent cobj_x0 cobj_x1
instance QhoverEnterEvent_h (QGraphicsPixmapItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_hoverEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_hoverEnterEvent" qtc_QGraphicsPixmapItem_hoverEnterEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverEnterEvent_h (QGraphicsPixmapItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_hoverEnterEvent cobj_x0 cobj_x1
instance QhoverLeaveEvent_h (QGraphicsPixmapItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_hoverLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_hoverLeaveEvent" qtc_QGraphicsPixmapItem_hoverLeaveEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverLeaveEvent_h (QGraphicsPixmapItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_hoverLeaveEvent cobj_x0 cobj_x1
instance QhoverMoveEvent_h (QGraphicsPixmapItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_hoverMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_hoverMoveEvent" qtc_QGraphicsPixmapItem_hoverMoveEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverMoveEvent_h (QGraphicsPixmapItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_hoverMoveEvent cobj_x0 cobj_x1
instance QinputMethodEvent_h (QGraphicsPixmapItem ()) ((QInputMethodEvent t1)) where
inputMethodEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_inputMethodEvent" qtc_QGraphicsPixmapItem_inputMethodEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent_h (QGraphicsPixmapItemSc a) ((QInputMethodEvent t1)) where
inputMethodEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_inputMethodEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler14" qtc_QGraphicsPixmapItem_setHandler14 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem14 :: (Ptr (TQGraphicsPixmapItem x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QinputMethodQuery_h (QGraphicsPixmapItem ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPixmapItem_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsPixmapItem_inputMethodQuery" qtc_QGraphicsPixmapItem_inputMethodQuery :: Ptr (TQGraphicsPixmapItem a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QGraphicsPixmapItemSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPixmapItem_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum x2obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler15" qtc_QGraphicsPixmapItem_setHandler15 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem15 :: (Ptr (TQGraphicsPixmapItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem15_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum x2obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QitemChange_h (QGraphicsPixmapItem ()) ((GraphicsItemChange, QVariant t2)) where
itemChange_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPixmapItem_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
foreign import ccall "qtc_QGraphicsPixmapItem_itemChange" qtc_QGraphicsPixmapItem_itemChange :: Ptr (TQGraphicsPixmapItem a) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant ()))
instance QitemChange_h (QGraphicsPixmapItemSc a) ((GraphicsItemChange, QVariant t2)) where
itemChange_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPixmapItem_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
instance QkeyPressEvent_h (QGraphicsPixmapItem ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_keyPressEvent" qtc_QGraphicsPixmapItem_keyPressEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QGraphicsPixmapItemSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_keyPressEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QGraphicsPixmapItem ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_keyReleaseEvent" qtc_QGraphicsPixmapItem_keyReleaseEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QGraphicsPixmapItemSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_keyReleaseEvent cobj_x0 cobj_x1
instance QmouseDoubleClickEvent_h (QGraphicsPixmapItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_mouseDoubleClickEvent" qtc_QGraphicsPixmapItem_mouseDoubleClickEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QGraphicsPixmapItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QGraphicsPixmapItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_mouseMoveEvent" qtc_QGraphicsPixmapItem_mouseMoveEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QGraphicsPixmapItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QGraphicsPixmapItem ()) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_mousePressEvent" qtc_QGraphicsPixmapItem_mousePressEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QGraphicsPixmapItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QGraphicsPixmapItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_mouseReleaseEvent" qtc_QGraphicsPixmapItem_mouseReleaseEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QGraphicsPixmapItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_mouseReleaseEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler16" qtc_QGraphicsPixmapItem_setHandler16 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem16 :: (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem16_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsceneEvent_h (QGraphicsPixmapItem ()) ((QEvent t1)) where
sceneEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_sceneEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_sceneEvent" qtc_QGraphicsPixmapItem_sceneEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQEvent t1) -> IO CBool
instance QsceneEvent_h (QGraphicsPixmapItemSc a) ((QEvent t1)) where
sceneEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_sceneEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler17" qtc_QGraphicsPixmapItem_setHandler17 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem17 :: (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem17_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetHandler (QGraphicsPixmapItem ()) (QGraphicsPixmapItem x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsPixmapItem_setHandler18" qtc_QGraphicsPixmapItem_setHandler18 :: Ptr (TQGraphicsPixmapItem a) -> CWString -> Ptr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem18 :: (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPixmapItem18_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPixmapItemSc a) (QGraphicsPixmapItem x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPixmapItem18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPixmapItem18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPixmapItem_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPixmapItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsceneEventFilter_h (QGraphicsPixmapItem ()) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPixmapItem_sceneEventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsPixmapItem_sceneEventFilter" qtc_QGraphicsPixmapItem_sceneEventFilter :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter_h (QGraphicsPixmapItemSc a) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPixmapItem_sceneEventFilter cobj_x0 cobj_x1 cobj_x2
instance QsceneEventFilter_h (QGraphicsPixmapItem ()) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPixmapItem_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsPixmapItem_sceneEventFilter_graphicstextitem" qtc_QGraphicsPixmapItem_sceneEventFilter_graphicstextitem :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter_h (QGraphicsPixmapItemSc a) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPixmapItem_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2
instance QwheelEvent_h (QGraphicsPixmapItem ()) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPixmapItem_wheelEvent" qtc_QGraphicsPixmapItem_wheelEvent :: Ptr (TQGraphicsPixmapItem a) -> Ptr (TQGraphicsSceneWheelEvent t1) -> IO ()
instance QwheelEvent_h (QGraphicsPixmapItemSc a) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPixmapItem_wheelEvent cobj_x0 cobj_x1
| keera-studios/hsQt | Qtc/Gui/QGraphicsPixmapItem_h.hs | bsd-2-clause | 99,447 | 0 | 18 | 20,812 | 30,664 | 14,671 | 15,993 | -1 | -1 |
module Widgets where
import Import
submitWidget :: GGWidget Jabaraster (GHandler Jabaraster Jabaraster) ()
submitWidget = do
addScriptRemote "https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"
$(widgetFile "submit")
submitWidget' :: Text -> GGWidget Jabaraster (GHandler Jabaraster Jabaraster) ()
submitWidget' tagId = do
addScriptRemote "https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"
$(widgetFile "submit2")
data SubmitWidgetContext = SubmitWidgetContext {
submitTagId :: Text
, submitOther :: Text
}
submitWidget'' :: SubmitWidgetContext -> GGWidget Jabaraster (GHandler Jabaraster Jabaraster) ()
submitWidget'' context = do
addScriptRemote "https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"
$(widgetFile "submit3")
| jabaraster/yefib | Widgets.hs | bsd-2-clause | 790 | 0 | 9 | 90 | 171 | 84 | 87 | 17 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# OPTIONS_HADDOCK hide #-}
module System.Hardware.Serialport.Windows where
import Data.Bits
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Unsafe as BU
import qualified System.Win32.Comm as Comm
import System.Win32.Types
import System.Win32.File
import Foreign.Marshal.Alloc
import System.Hardware.Serialport.Types
import Control.Monad
import GHC.IO.Handle
import GHC.IO.Device
import GHC.IO.BufferedIO
import Data.Typeable
import GHC.IO.Buffer
data SerialPort = SerialPort {
handle :: HANDLE,
portSettings :: SerialPortSettings
}
deriving (Typeable)
instance RawIO SerialPort where
read (SerialPort h _) ptr n = return . fromIntegral =<< win32_ReadFile h ptr (fromIntegral n) Nothing
readNonBlocking _ _ _ = error "readNonBlocking not implemented"
write (SerialPort h _) ptr n = void (win32_WriteFile h ptr (fromIntegral n) Nothing)
writeNonBlocking _ _ _ = error "writenonblocking not implemented"
instance IODevice SerialPort where
ready _ _ _ = return True
close = closeSerial
isTerminal _ = return False
isSeekable _ = return False
seek _ _ _ = return ()
tell _ = return 0
getSize _ = return 0
setSize _ _ = return ()
setEcho _ _ = return ()
getEcho _ = return False
setRaw _ _ = return ()
devType _ = return Stream
instance BufferedIO SerialPort where
newBuffer _ = newByteBuffer 100
fillReadBuffer = readBuf
fillReadBuffer0 = readBufNonBlocking
flushWriteBuffer = writeBuf
flushWriteBuffer0 = writeBufNonBlocking
-- |Open and configure a serial port returning a standard Handle.
hOpenSerial :: String
-> SerialPortSettings
-> IO Handle
hOpenSerial dev settings = do
ser <- openSerial dev settings
h <- mkDuplexHandle ser dev Nothing noNewlineTranslation
hSetBuffering h NoBuffering
return h
-- | Open and configure a serial port
openSerial :: String -- ^ Serial port, such as @COM5@ or @CNCA0@
-> SerialPortSettings
-> IO SerialPort
openSerial dev settings = do
h <- createFile ("\\\\.\\" ++ dev) access_mode share_mode security_attr create_mode file_attr template_file
let serial_port = SerialPort h defaultSerialSettings
return =<< setSerialSettings serial_port settings
where
access_mode = gENERIC_READ .|. gENERIC_WRITE
share_mode = fILE_SHARE_NONE
security_attr = Nothing
create_mode = oPEN_EXISTING
file_attr = fILE_ATTRIBUTE_NORMAL -- .|. fILE_FLAG_OVERLAPPED
template_file = Nothing
-- |Receive bytes, given the maximum number
recv :: SerialPort -> Int -> IO B.ByteString
recv (SerialPort h _) n =
allocaBytes n $ \p -> do
recv_cnt <- win32_ReadFile h p count overlapped
B.packCStringLen (p, fromIntegral recv_cnt)
where
count = fromIntegral n
overlapped = Nothing
-- |Send bytes
send :: SerialPort
-> B.ByteString
-> IO Int -- ^ Number of bytes actually sent
send (SerialPort h _) msg =
BU.unsafeUseAsCString msg $ \p ->
fromIntegral `fmap` win32_WriteFile h p count overlapped
where
count = fromIntegral $ B.length msg
overlapped = Nothing
-- |Flush buffers
flush :: SerialPort -> IO ()
flush s@(SerialPort h _) =
flushFileBuffers h
>> consumeIncomingChars
where
consumeIncomingChars = do
ch <- recv s 1
unless (ch == B.empty) consumeIncomingChars
-- |Close the serial port
closeSerial :: SerialPort -> IO ()
closeSerial = closeHandle . handle
-- |Set the Data Terminal Ready level
setDTR :: SerialPort -> Bool -> IO ()
setDTR (SerialPort h _ ) True = Comm.escapeCommFunction h Comm.setDTR
setDTR (SerialPort h _ ) False = Comm.escapeCommFunction h Comm.clrDTR
-- |Set the Ready to send level
setRTS :: SerialPort -> Bool -> IO ()
setRTS (SerialPort h _ ) True = Comm.escapeCommFunction h Comm.setRTS
setRTS (SerialPort h _ ) False = Comm.escapeCommFunction h Comm.clrRTS
-- |Configure the serial port
setSerialSettings :: SerialPort -- ^ The currently opened serial port
-> SerialPortSettings -- ^ The new settings
-> IO SerialPort -- ^ New serial port
setSerialSettings (SerialPort h _) new_settings = do
let ct = Comm.COMMTIMEOUTS {
Comm.readIntervalTimeout = maxBound :: DWORD,
Comm.readTotalTimeoutMultiplier = maxBound :: DWORD,
Comm.readTotalTimeoutConstant = fromIntegral (timeout new_settings) * 100,
Comm.writeTotalTimeoutMultiplier = 0,
Comm.writeTotalTimeoutConstant = 0 }
Comm.setCommTimeouts h ct
Comm.setCommState h new_settings
return (SerialPort h new_settings)
-- |Get configuration from serial port
getSerialSettings :: SerialPort -> SerialPortSettings
getSerialSettings = portSettings
| jputcu/serialport | System/Hardware/Serialport/Windows.hs | bsd-3-clause | 4,880 | 0 | 15 | 1,113 | 1,226 | 636 | 590 | 111 | 1 |
{-# OPTIONS_GHC -Wno-orphans #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE StandaloneDeriving #-}
{-|
Module : AERN2.MP.WithCurrentPrec.Limit
Description : WithCurrentPrec limits
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : mikkonecny@gmail.com
Stability : experimental
Portability : portable
WithCurrentPrec limits
-}
module AERN2.MP.WithCurrentPrec.Limit
()
where
import MixedTypesNumPrelude
-- import qualified Prelude as P
-- import Text.Printf
-- import qualified Numeric.CollectErrors as CN
import GHC.TypeLits
import Control.Monad (join)
import AERN2.MP.Ball
import AERN2.Limit
import AERN2.MP.WithCurrentPrec.Type
instance
(HasLimits ix (CN MPBall -> CN MPBall)
, LimitType ix (CN MPBall -> CN MPBall) ~ (CN MPBall -> CN MPBall)
, KnownNat p)
=>
HasLimits ix (WithCurrentPrec p (CN MPBall))
where
type LimitType ix (WithCurrentPrec p (CN MPBall)) = WithCurrentPrec p (CN MPBall)
limit s = limit $ cn . s
instance
(HasLimits ix (CN MPBall -> CN MPBall)
, LimitType ix (CN MPBall -> CN MPBall) ~ (CN MPBall -> CN MPBall)
, KnownNat p)
=>
HasLimits ix (CN (WithCurrentPrec p (CN MPBall)))
where
type LimitType ix (CN (WithCurrentPrec p (CN MPBall))) = WithCurrentPrec p (CN MPBall)
limit (s :: ix -> CN (WithCurrentPrec p (CN MPBall))) =
WithCurrentPrec $ limit (snop) $ sample
where
sample :: CN MPBall
sample = setPrecision (getCurrentPrecision sampleP) (cn $ mpBall 0)
sampleP :: WithCurrentPrec p MPBall
sampleP = error "sampleP is not defined, it is only a type proxy"
snop :: ix -> (CN MPBall -> CN MPBall)
snop ix _sample = join $ fmap unWithCurrentPrec $ s ix
| michalkonecny/aern2 | aern2-mp/src/AERN2/MP/WithCurrentPrec/Limit.hs | bsd-3-clause | 1,881 | 0 | 14 | 450 | 493 | 255 | 238 | -1 | -1 |
{-# LANGUAGE FlexibleInstances #-}
module Sodium.Pascal.Convert (convert) where
import Prelude hiding (mapM)
import Control.Applicative
import Control.Monad.Reader hiding (mapM)
import qualified Data.Map as M
import Data.Traversable
import Control.Lens
-- S for Src, D for Dest
import qualified Sodium.Pascal.Program as S
import qualified Sodium.Chloride.Program.Scalar as D
convert :: S.Program -> D.Program
convert = flip runReader [] . conv
type ConvEnv = [S.Name]
class Conv s d | s -> d where
conv :: s -> Reader ConvEnv d
instance Conv S.Program D.Program where
conv (S.Program funcs vars body) = do
clMain <- do
clBody <- conv (VB vars body)
let clFuncSig = D.FuncSig D.NameMain M.empty D.ClVoid
return $ D.Func clFuncSig clBody []
clFuncs <- mapM conv funcs
return $ D.Program (clMain:clFuncs)
convBodyStatement statement
= review D.bodySingleton
<$> conv statement
maybeBodySingleton
= maybe D.bodyEmpty
$ review D.bodySingleton
data VB = VB S.Vars S.Body
instance Conv VB D.Body where
conv (VB vardecls statements)
= D.Body
<$> (M.fromList <$> mapM conv (splitVarDecls vardecls))
<*> mapM conv statements
nameHook cs = do
names <- ask
let wrap = if cs `elem` names then D.NameUnique else id
wrap <$> conv cs
instance Conv S.Func D.Func where
conv (S.Func name params pasType vars body)
= withReaderT (name:) $ do
clFuncSig
<- D.FuncSig
<$> conv name
<*> (M.fromList <$> mapM conv (splitVarDecls params))
<*> conv pasType
clRetName <- nameHook name
let enclose = D.bodyVars %~
(M.insert clRetName $ clFuncSig ^. D.funcRetType)
clBody <- enclose <$> conv (VB vars body)
return $ D.Func clFuncSig clBody [D.Access clRetName]
instance Conv S.Name D.Name where
conv = return . D.Name
splitVarDecls vardecls
= [VarDecl name t | S.VarDecl names t <- vardecls, name <- names]
data VarDecl = VarDecl S.Name S.PasType
instance Conv VarDecl (D.Name, D.ClType) where
conv (VarDecl name pasType)
= (,) <$> conv name <*> conv pasType
instance Conv S.PasType D.ClType where
conv = \case
S.PasInteger -> return D.ClInteger
S.PasLongInt -> return D.ClInteger
S.PasReal -> return D.ClDouble
S.PasBoolean -> return D.ClBoolean
S.PasString -> return D.ClString
S.PasType cs -> error "Custom types are not implemented"
binary op a b = D.Call op [a,b]
multifyIf expr bodyThen bodyElse = D.MultiIfBranch [(expr, bodyThen)] bodyElse
instance Conv S.Statement D.Statement where
conv = \case
S.BodyStatement body
-> D.BodyStatement
<$> conv (VB [] body)
S.Assign name expr -> D.Assign <$> nameHook name <*> conv expr
S.Execute name exprs
-> D.Execute Nothing
<$> case name of
"readln" -> return (D.OpReadLn undefined)
"writeln" -> return D.OpPrintLn
name -> D.OpName <$> conv name
<*> mapM conv exprs
S.ForCycle name fromExpr toExpr statement
-> (D.ForStatement <$>)
$ D.ForCycle
<$> nameHook name
<*> (binary D.OpRange <$> conv fromExpr <*> conv toExpr)
<*> convBodyStatement statement
S.IfBranch expr bodyThen mBodyElse
-> (D.MultiIfStatement <$>)
$ multifyIf
<$> conv expr
<*> convBodyStatement bodyThen
<*> (maybeBodySingleton <$> mapM conv mBodyElse)
S.CaseBranch expr leafs mBodyElse -> do
(clCaseExpr, wrap) <- case expr of
S.Access name -> (, id) <$> (D.Access <$> nameHook name)
expr -> do
clExpr <- conv expr
let clName = D.Name "__CASE'__" -- generate a name?
let clType = undefined -- typeof(expr)
let wrap statement
= D.BodyStatement
$ D.Body
(M.singleton clName clType)
[D.Assign clName clExpr, statement]
return (D.Access clName, wrap)
let instRange = \case
S.Binary S.OpRange exprFrom exprTo
-> (binary D.OpElem clCaseExpr)
<$> (binary D.OpRange <$> conv exprFrom <*> conv exprTo)
expr -> binary D.OpEquals clCaseExpr <$> conv expr
let instLeaf (exprs, body)
= (,)
<$> (foldl1 (binary D.OpOr) <$> mapM instRange exprs)
<*> convBodyStatement body
let multiIfBranch
= D.MultiIfBranch
<$> mapM instLeaf leafs
<*> (maybeBodySingleton <$> mapM conv mBodyElse)
wrap <$> (D.MultiIfStatement <$> multiIfBranch)
instance Conv S.Expression D.Expression where
conv = \case
S.Access name -> D.Access <$> nameHook name
S.Call name exprs
-> D.Call
<$> (D.OpName <$> conv name)
<*> mapM conv exprs
S.INumber intSection
-> return
$ D.Primary
$ D.INumber intSection
S.FNumber intSection fracSection
-> return
$ D.Primary
$ D.FNumber intSection fracSection
S.ENumber intSection fracSection eSign eSection
-> return
$ D.Primary
$ D.ENumber intSection fracSection eSign eSection
S.Quote cs -> return $ D.Primary (D.Quote cs)
S.BTrue -> return $ D.Primary D.BTrue
S.BFalse -> return $ D.Primary D.BFalse
S.Binary op x y -> binary <$> conv op <*> conv x <*> conv y
S.Unary op x -> case op of
S.UOpPlus -> conv x
S.UOpNegate
-> D.Call D.OpNegate
<$> mapM conv [x]
instance Conv S.Operator D.Operator where
conv = return . \case
S.OpAdd -> D.OpAdd
S.OpSubtract -> D.OpSubtract
S.OpMultiply -> D.OpMultiply
S.OpDivide -> D.OpDivide
S.OpLess -> D.OpLess
S.OpMore -> D.OpMore
S.OpEquals -> D.OpEquals
S.OpAnd -> D.OpAnd
S.OpOr -> D.OpOr
S.OpRange -> D.OpRange
| kirbyfan64/sodium | src/Sodium/Pascal/Convert.hs | bsd-3-clause | 5,352 | 51 | 23 | 1,157 | 2,018 | 1,001 | 1,017 | -1 | -1 |
{-# language CPP #-}
{-# language DeriveFunctor #-}
{-# language DeriveTraversable #-}
{-# language MultiParamTypeClasses #-}
{-# language NoImplicitPrelude #-}
{-# language QuasiQuotes #-}
{-# language TemplateHaskell #-}
{-# language UndecidableInstances #-}
#if __GLASGOW_HASKELL__ >= 800
{-# options_ghc -Wno-redundant-constraints #-}
#endif
module OpenCV.ImgProc.FeatureDetection
( canny
, goodFeaturesToTrack
, houghCircles
, houghLinesP
, GoodFeaturesToTrackDetectionMethod(..)
, CannyNorm(..)
, Circle(..)
, LineSegment(..)
) where
import "base" Control.Exception ( mask_ )
import "base" Data.Int
import "base" Data.Maybe
import qualified "vector" Data.Vector as V
import "base" Data.Word
import "base" Foreign.Marshal.Alloc ( alloca )
import "base" Foreign.Marshal.Array ( peekArray )
import "base" Foreign.Marshal.Utils ( fromBool )
import "base" Foreign.Ptr ( Ptr )
import "base" Foreign.Storable ( peek )
import "base" Prelude hiding ( lines )
import "base" System.IO.Unsafe ( unsafePerformIO )
import qualified "inline-c" Language.C.Inline as C
import qualified "inline-c" Language.C.Inline.Unsafe as CU
import qualified "inline-c-cpp" Language.C.Inline.Cpp as C
import "linear" Linear ( V2(..), V3(..), V4(..) )
import "primitive" Control.Monad.Primitive ( PrimMonad, PrimState, unsafePrimToPrim )
import "this" OpenCV.Core.Types
import "this" OpenCV.Internal.C.Inline ( openCvCtx )
import "this" OpenCV.Internal.C.Types
import "this" OpenCV.Internal.Core.Types.Mat
import "this" OpenCV.Internal.Exception
import "this" OpenCV.TypeLevel
#if MIN_VERSION_base(4,9,0)
import "base" Data.Foldable ( Foldable )
import "base" Data.Traversable ( Traversable )
#endif
--------------------------------------------------------------------------------
C.context openCvCtx
C.include "opencv2/core.hpp"
C.include "opencv2/imgproc.hpp"
C.using "namespace cv"
--------------------------------------------------------------------------------
-- Feature Detection
--------------------------------------------------------------------------------
{- |
Finds edges in an image using the
<http://docs.opencv.org/2.4/modules/imgproc/doc/feature_detection.html#canny86 Canny86>
algorithm.
Example:
@
cannyImg
:: forall shape channels depth
. (Mat shape channels depth ~ Lambda)
=> Mat shape ('S 1) depth
cannyImg = exceptError $
canny 30 200 Nothing CannyNormL1 lambda
@
<<doc/generated/examples/cannyImg.png cannyImg>>
-}
canny
:: Double
-- ^ First threshold for the hysteresis procedure.
-> Double
-- ^ Second threshold for the hysteresis procedure.
-> Maybe Int32
-- ^ Aperture size for the @Sobel()@ operator. If not specified defaults
-- to @3@. Must be 3, 5 or 7.
-> CannyNorm
-- ^ A flag, indicating whether to use the more accurate L2 norm or the default L1 norm.
-> Mat ('S [h, w]) channels ('S Word8)
-- ^ 8-bit input image.
-> CvExcept (Mat ('S [h, w]) ('S 1) ('S Word8))
canny threshold1 threshold2 apertureSize norm src = unsafeWrapException $ do
dst <- newEmptyMat
handleCvException (pure $ unsafeCoerceMat dst) $
withPtr src $ \srcPtr ->
withPtr dst $ \dstPtr ->
[cvExcept|
cv::Canny
( *$(Mat * srcPtr)
, *$(Mat * dstPtr)
, $(double c'threshold1)
, $(double c'threshold2)
, $(int32_t c'apertureSize)
, $(bool c'l2Gradient)
);
|]
where
c'threshold1 = realToFrac threshold1
c'threshold2 = realToFrac threshold2
c'apertureSize = fromMaybe 3 apertureSize
c'l2Gradient =
fromBool $
case norm of
CannyNormL1 -> False
CannyNormL2 -> True
-- | A flag, indicating whether to use the more accurate L2 norm or the default L1 norm.
data CannyNorm
= CannyNormL1
| CannyNormL2
deriving (Show, Eq)
data Circle
= Circle
{ circleCenter :: V2 Float
, circleRadius :: Float
} deriving (Show)
{- |
Determines strong corners on an image.
The function finds the most prominent corners in the image or in the specified image region.
* Function calculates the corner quality measure at every source image pixel using the cornerMinEigenVal or cornerHarris.
* Function performs a non-maximum suppression (the local maximums in 3 x 3 neighborhood are retained).
* The corners with the minimal eigenvalue less than @𝚚𝚞𝚊𝚕𝚒𝚝𝚢𝙻𝚎𝚟𝚎𝚕 * max(x,y) qualityMeasureMap(x,y)@ are rejected.
* The remaining corners are sorted by the quality measure in the descending order.
* Function throws away each corner for which there is a stronger corner at a distance less than maxDistance.
Example:
@
goodFeaturesToTrackTraces
:: forall (width :: Nat)
(height :: Nat)
(channels :: Nat)
(depth :: *)
. (Mat (ShapeT [height, width]) ('S channels) ('S depth) ~ Frog)
=> Mat (ShapeT [height, width]) ('S channels) ('S depth)
goodFeaturesToTrackTraces = exceptError $ do
imgG <- cvtColor bgr gray frog
let features = goodFeaturesToTrack imgG 20 0.01 0.5 Nothing Nothing CornerMinEigenVal
withMatM (Proxy :: Proxy [height, width])
(Proxy :: Proxy channels)
(Proxy :: Proxy depth)
white $ \imgM -> do
void $ matCopyToM imgM (V2 0 0) frog Nothing
forM_ features $ \f -> do
circle imgM (round \<$> f :: V2 Int32) 2 blue 5 LineType_AA 0
@
<<doc/generated/examples/goodFeaturesToTrackTraces.png goodFeaturesToTrackTraces>>
-}
goodFeaturesToTrack
:: (depth `In` ['S Word8, 'S Float, 'D])
=> Mat ('S [h, w]) ('S 1) depth
-- ^ Input 8-bit or floating-point 32-bit, single-channel image.
-> Int32
-- ^ Maximum number of corners to return. If there are more corners than are
-- found, the strongest of them is returned.
-> Double
-- ^ Parameter characterizing the minimal accepted quality of image corners.
-- The parameter value is multiplied by the best corner quality measure,
-- which is the minimal eigenvalue (see cornerMinEigenVal ) or the Harris
-- function response (see cornerHarris ). The corners with the quality measure
-- less than the product are rejected. For example, if the best corner has the
-- quality measure = 1500, and the qualityLevel=0.01 , then all the corners with
-- the quality measure less than 15 are rejected.
-> Double
-- ^ Minimum possible Euclidean distance between the returned corners.
-> Maybe (Mat ('S [h, w]) ('S 1) ('S Word8))
-- ^ Optional region of interest. If the image is not empty (it needs to have
-- the type CV_8UC1 and the same size as image ), it specifies the region in which
-- the corners are detected.
-> Maybe Int32
-- ^ Size of an average block for computing a derivative covariation matrix
-- over each pixel neighborhood. See cornerEigenValsAndVecs.
-> GoodFeaturesToTrackDetectionMethod
-- ^ Parameter indicating whether to use a Harris detector (see cornerHarris)
-- or cornerMinEigenVal.
-> V.Vector (V2 Float)
goodFeaturesToTrack src maxCorners qualityLevel minDistance mbMask blockSize detector = unsafePerformIO $ do
withPtr src $ \srcPtr ->
withPtr mbMask $ \mskPtr ->
alloca $ \(cornersLengthsPtr :: Ptr Int32) ->
alloca $ \(cornersPtrPtr :: Ptr (Ptr (Ptr C'Point2f))) -> mask_ $ do
[C.block| void {
std::vector<cv::Point2f> corners;
Mat * mskPtr = $(Mat * mskPtr);
cv::goodFeaturesToTrack
( *$(Mat * srcPtr)
, corners
, $(int32_t maxCorners)
, $(double c'qualityLevel)
, $(double c'minDistance)
, mskPtr ? _InputArray(*mskPtr) : _InputArray(cv::noArray())
, $(int32_t c'blockSize)
, $(bool c'useHarrisDetector)
, $(double c'harrisK)
);
cv::Point2f * * * cornersPtrPtr = $(Point2f * * * cornersPtrPtr);
cv::Point2f * * cornersPtr = new cv::Point2f * [corners.size()];
*cornersPtrPtr = cornersPtr;
*$(int32_t * cornersLengthsPtr) = corners.size();
for (std::vector<cv::Point2f>::size_type i = 0; i != corners.size(); i++) {
cornersPtr[i] = new cv::Point2f( corners[i] );
}
}|]
numCorners <- fromIntegral <$> peek cornersLengthsPtr
cornersPtr <- peek cornersPtrPtr
(corners :: [V2 Float]) <-
peekArray numCorners cornersPtr >>=
mapM (fmap (fmap fromCFloat . fromPoint) . fromPtr . pure)
[CU.block| void {
delete [] *$(Point2f * * * cornersPtrPtr);
}|]
pure (V.fromList corners)
where
c'qualityLevel = realToFrac qualityLevel
c'minDistance = realToFrac minDistance
c'blockSize = fromMaybe 3 blockSize
c'useHarrisDetector =
fromBool $
case detector of
HarrisDetector _kValue -> True
CornerMinEigenVal -> False
c'harrisK =
realToFrac $
case detector of
HarrisDetector kValue -> kValue
CornerMinEigenVal -> 0.04
data GoodFeaturesToTrackDetectionMethod
= HarrisDetector Double -- ^ Harris detector and it free k parameter
| CornerMinEigenVal
deriving (Show, Eq)
{- |
Finds circles in a grayscale image using a modification of the Hough
transformation.
Example:
@
houghCircleTraces
:: forall (width :: Nat)
(height :: Nat)
(channels :: Nat)
(depth :: *)
. (Mat (ShapeT [height, width]) ('S channels) ('S depth) ~ Circles_1000x625)
=> Mat (ShapeT [height, width]) ('S channels) ('S depth)
houghCircleTraces = exceptError $ do
imgG <- cvtColor bgr gray circles_1000x625
let circles = houghCircles 1 10 Nothing Nothing Nothing Nothing imgG
withMatM (Proxy :: Proxy [height, width])
(Proxy :: Proxy channels)
(Proxy :: Proxy depth)
white $ \imgM -> do
void $ matCopyToM imgM (V2 0 0) circles_1000x625 Nothing
forM_ circles $ \c -> do
circle imgM (round \<$> circleCenter c :: V2 Int32) (round (circleRadius c)) blue 1 LineType_AA 0
@
<<doc/generated/examples/houghCircleTraces.png houghCircleTraces>>
-}
houghCircles
:: Double
-- ^ Inverse ratio of the accumulator resolution to the image resolution.
-- For example, if @dp=1@, the accumulator has the same resolution as the
-- input image. If @dp=2@, the accumulator has half as big width and height.
-> Double
-- ^ Minimum distance between the centers of the detected circles. If the
-- parameter is too small, multiple neighbor circles may be falsely
-- detected in addition to a true one. If it is too large, some circles may
-- be missed.
-> Maybe Double
-- ^ The higher threshold of the two passed to the 'canny' edge detector
-- (the lower one is twice smaller). Default is 100.
-> Maybe Double
-- ^ The accumulator threshold for the circle centers at the detection
-- stage. The smaller it is, the more false circles may be detected.
-- Circles, corresponding to the larger accumulator values, will be returned
-- first. Default is 100.
-> Maybe Int32
-- ^ Minimum circle radius.
-> Maybe Int32
-- ^ Maximum circle radius.
-> Mat ('S [w,h]) ('S 1) ('S Word8)
-> V.Vector Circle
houghCircles dp minDist param1 param2 minRadius maxRadius src = unsafePerformIO $
withPtr src $ \srcPtr ->
alloca $ \(circleLengthsPtr :: Ptr Int32) ->
alloca $ \(circlesPtrPtr :: Ptr (Ptr (Ptr C'Vec3f))) -> mask_ $ do
_ <- [cvExcept|
std::vector<cv::Vec3f> circles;
cv::HoughCircles(
*$(Mat * srcPtr),
circles,
CV_HOUGH_GRADIENT,
$(double c'dp),
$(double c'minDist),
$(double c'param1),
$(double c'param2),
$(int32_t c'minRadius),
$(int32_t c'maxRadius)
);
cv::Vec3f * * * circlesPtrPtr = $(Vec3f * * * circlesPtrPtr);
cv::Vec3f * * circlesPtr = new cv::Vec3f * [circles.size()];
*circlesPtrPtr = circlesPtr;
*$(int32_t * circleLengthsPtr) = circles.size();
for (std::vector<cv::Vec3f>::size_type i = 0; i != circles.size(); i++) {
circlesPtr[i] = new cv::Vec3f( circles[i] );
}
|]
numCircles <- fromIntegral <$> peek circleLengthsPtr
circlesPtr <- peek circlesPtrPtr
(circles :: [V3 Float]) <-
peekArray numCircles circlesPtr >>=
mapM (fmap (fmap fromCFloat . fromVec) . fromPtr . pure)
pure (V.fromList (map (\(V3 x y r) -> Circle (V2 x y) r) circles))
where c'dp = realToFrac dp
c'minDist = realToFrac minDist
c'param1 = realToFrac (fromMaybe 100 param1)
c'param2 = realToFrac (fromMaybe 100 param2)
c'minRadius = fromIntegral (fromMaybe 0 minRadius)
c'maxRadius = fromIntegral (fromMaybe 0 maxRadius)
data LineSegment depth
= LineSegment
{ lineSegmentStart :: !(V2 depth)
, lineSegmentStop :: !(V2 depth)
} deriving (Foldable, Functor, Traversable, Show)
type instance VecDim LineSegment = 4
instance (IsVec V4 depth) => IsVec LineSegment depth where
toVec (LineSegment (V2 x1 y1) (V2 x2 y2)) =
toVec (V4 x1 y1 x2 y2)
fromVec vec =
LineSegment
{ lineSegmentStart = V2 x1 y1
, lineSegmentStop = V2 x2 y2
}
where
V4 x1 y1 x2 y2 = fromVec vec
{- |
Example:
@
houghLinesPTraces
:: forall (width :: Nat)
(height :: Nat)
(channels :: Nat)
(depth :: * )
. (Mat (ShapeT [height, width]) ('S channels) ('S depth) ~ Building_868x600)
=> Mat (ShapeT [height, width]) ('S channels) ('S depth)
houghLinesPTraces = exceptError $ do
edgeImg <- canny 50 200 Nothing CannyNormL1 building_868x600
edgeImgBgr <- cvtColor gray bgr edgeImg
withMatM (Proxy :: Proxy [height, width])
(Proxy :: Proxy channels)
(Proxy :: Proxy depth)
white $ \imgM -> do
edgeImgM <- thaw edgeImg
lineSegments <- houghLinesP 1 (pi / 180) 80 (Just 30) (Just 10) edgeImgM
void $ matCopyToM imgM (V2 0 0) edgeImgBgr Nothing
forM_ lineSegments $ \lineSegment -> do
line imgM
(lineSegmentStart lineSegment)
(lineSegmentStop lineSegment)
red 2 LineType_8 0
@
<<doc/generated/examples/houghLinesPTraces.png houghLinesPTraces>>
-}
houghLinesP
:: (PrimMonad m)
=> Double
-- ^ Distance resolution of the accumulator in pixels.
-> Double
-- ^ Angle resolution of the accumulator in radians.
-> Int32
-- ^ Accumulator threshold parameter. Only those lines are returned that
-- get enough votes (> threshold).
-> Maybe Double
-- ^ Minimum line length. Line segments shorter than that are rejected.
-> Maybe Double
-- ^ Maximum allowed gap between points on the same line to link them.
-> Mut (Mat ('S [h, w]) ('S 1) ('S Word8)) (PrimState m)
-- ^ Source image. May be modified by the function.
-> m (V.Vector (LineSegment Int32))
houghLinesP rho theta threshold minLineLength maxLineGap src = unsafePrimToPrim $
withPtr src $ \srcPtr ->
-- Pointer to number of lines.
alloca $ \(numLinesPtr :: Ptr Int32) ->
-- Pointer to array of Vec4i pointers. The array is allocated in
-- C++. Each element of the array points to a Vec4i that is also
-- allocated in C++.
alloca $ \(linesPtrPtr :: Ptr (Ptr (Ptr C'Vec4i))) -> mask_ $ do
[C.block| void {
std::vector<cv::Vec4i> lines = std::vector<cv::Vec4i>();
cv::HoughLinesP
( *$(Mat * srcPtr)
, lines
, $(double c'rho)
, $(double c'theta)
, $(int32_t threshold)
, $(double c'minLineLength)
, $(double c'maxLineGap)
);
*$(int32_t * numLinesPtr) = lines.size();
cv::Vec4i * * * linesPtrPtr = $(Vec4i * * * linesPtrPtr);
cv::Vec4i * * linesPtr = new cv::Vec4i * [lines.size()];
*linesPtrPtr = linesPtr;
for (std::vector<cv::Vec4i>::size_type ix = 0; ix != lines.size(); ix++)
{
cv::Vec4i & org = lines[ix];
cv::Vec4i * newLine = new cv::Vec4i(org[0], org[1], org[2], org[3]);
linesPtr[ix] = newLine;
}
}|]
numLines <- fromIntegral <$> peek numLinesPtr
linesPtr <- peek linesPtrPtr
lineSegments <- mapM (fmap fromVec . fromPtr . pure) =<< peekArray numLines linesPtr
-- Free the array of Vec4i pointers. This does not free the
-- Vec4i's pointed to by the elements of the array. That is the
-- responsibility of Haskell's Vec4i finalizer.
[CU.block| void {
delete [] *$(Vec4i * * * linesPtrPtr);
}|]
pure $ V.fromList lineSegments
where
c'rho = realToFrac rho
c'theta = realToFrac theta
c'minLineLength = maybe 0 realToFrac minLineLength
c'maxLineGap = maybe 0 realToFrac maxLineGap
| Cortlandd/haskell-opencv | src/OpenCV/ImgProc/FeatureDetection.hs | bsd-3-clause | 16,829 | 0 | 28 | 4,095 | 2,099 | 1,155 | 944 | -1 | -1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1998
\section[DataCon]{@DataCon@: Data Constructors}
-}
{-# LANGUAGE CPP, DeriveDataTypeable #-}
module DataCon (
-- * Main data types
DataCon, DataConRep(..),
SrcStrictness(..), SrcUnpackedness(..),
HsSrcBang(..), HsImplBang(..),
StrictnessMark(..),
ConTag,
-- ** Equality specs
EqSpec, mkEqSpec, eqSpecTyVar, eqSpecType,
eqSpecPair, eqSpecPreds,
substEqSpec, filterEqSpec,
-- ** Field labels
FieldLbl(..), FieldLabel, FieldLabelString,
-- ** Type construction
mkDataCon, buildAlgTyCon, buildSynTyCon, fIRST_TAG,
-- ** Type deconstruction
dataConRepType, dataConInstSig, dataConFullSig,
dataConName, dataConIdentity, dataConTag, dataConTagZ,
dataConTyCon, dataConOrigTyCon,
dataConUserType,
dataConUnivTyVars, dataConExTyCoVars, dataConUnivAndExTyCoVars,
dataConUserTyVars, dataConUserTyVarBinders,
dataConEqSpec, dataConTheta,
dataConStupidTheta,
dataConInstArgTys, dataConOrigArgTys, dataConOrigResTy,
dataConInstOrigArgTys, dataConRepArgTys,
dataConFieldLabels, dataConFieldType, dataConFieldType_maybe,
dataConSrcBangs,
dataConSourceArity, dataConRepArity,
dataConIsInfix,
dataConWorkId, dataConWrapId, dataConWrapId_maybe,
dataConImplicitTyThings,
dataConRepStrictness, dataConImplBangs, dataConBoxer,
splitDataProductType_maybe,
-- ** Predicates on DataCons
isNullarySrcDataCon, isNullaryRepDataCon, isTupleDataCon, isUnboxedTupleCon,
isUnboxedSumCon,
isVanillaDataCon, classDataCon, dataConCannotMatch,
dataConUserTyVarsArePermuted,
isBanged, isMarkedStrict, eqHsBang, isSrcStrict, isSrcUnpacked,
specialPromotedDc,
-- ** Promotion related functions
promoteDataCon
) where
#include "HsVersions.h"
import GhcPrelude
import {-# SOURCE #-} MkId( DataConBoxer )
import Type
import ForeignCall ( CType )
import Coercion
import Unify
import TyCon
import FieldLabel
import Class
import Name
import PrelNames
import Predicate
import Var
import VarSet( emptyVarSet )
import Outputable
import Util
import BasicTypes
import FastString
import Module
import Binary
import UniqSet
import Unique( mkAlphaTyVarUnique )
import Data.ByteString (ByteString)
import qualified Data.ByteString.Builder as BSB
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Data as Data
import Data.Char
import Data.List( find )
{-
Data constructor representation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following Haskell data type declaration
data T = T !Int ![Int]
Using the strictness annotations, GHC will represent this as
data T = T Int# [Int]
That is, the Int has been unboxed. Furthermore, the Haskell source construction
T e1 e2
is translated to
case e1 of { I# x ->
case e2 of { r ->
T x r }}
That is, the first argument is unboxed, and the second is evaluated. Finally,
pattern matching is translated too:
case e of { T a b -> ... }
becomes
case e of { T a' b -> let a = I# a' in ... }
To keep ourselves sane, we name the different versions of the data constructor
differently, as follows.
Note [Data Constructor Naming]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Each data constructor C has two, and possibly up to four, Names associated with it:
OccName Name space Name of Notes
---------------------------------------------------------------------------
The "data con itself" C DataName DataCon In dom( GlobalRdrEnv )
The "worker data con" C VarName Id The worker
The "wrapper data con" $WC VarName Id The wrapper
The "newtype coercion" :CoT TcClsName TyCon
EVERY data constructor (incl for newtypes) has the former two (the
data con itself, and its worker. But only some data constructors have a
wrapper (see Note [The need for a wrapper]).
Each of these three has a distinct Unique. The "data con itself" name
appears in the output of the renamer, and names the Haskell-source
data constructor. The type checker translates it into either the wrapper Id
(if it exists) or worker Id (otherwise).
The data con has one or two Ids associated with it:
The "worker Id", is the actual data constructor.
* Every data constructor (newtype or data type) has a worker
* The worker is very like a primop, in that it has no binding.
* For a *data* type, the worker *is* the data constructor;
it has no unfolding
* For a *newtype*, the worker has a compulsory unfolding which
does a cast, e.g.
newtype T = MkT Int
The worker for MkT has unfolding
\\(x:Int). x `cast` sym CoT
Here CoT is the type constructor, witnessing the FC axiom
axiom CoT : T = Int
The "wrapper Id", \$WC, goes as follows
* Its type is exactly what it looks like in the source program.
* It is an ordinary function, and it gets a top-level binding
like any other function.
* The wrapper Id isn't generated for a data type if there is
nothing for the wrapper to do. That is, if its defn would be
\$wC = C
Note [Data constructor workers and wrappers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Algebraic data types
- Always have a worker, with no unfolding
- May or may not have a wrapper; see Note [The need for a wrapper]
* Newtypes
- Always have a worker, which has a compulsory unfolding (just a cast)
- May or may not have a wrapper; see Note [The need for a wrapper]
* INVARIANT: the dictionary constructor for a class
never has a wrapper.
* Neither_ the worker _nor_ the wrapper take the dcStupidTheta dicts as arguments
* The wrapper (if it exists) takes dcOrigArgTys as its arguments
The worker takes dataConRepArgTys as its arguments
If the worker is absent, dataConRepArgTys is the same as dcOrigArgTys
* The 'NoDataConRep' case of DataConRep is important. Not only is it
efficient, but it also ensures that the wrapper is replaced by the
worker (because it *is* the worker) even when there are no
args. E.g. in
f (:) x
the (:) *is* the worker. This is really important in rule matching,
(We could match on the wrappers, but that makes it less likely that
rules will match when we bring bits of unfoldings together.)
Note [The need for a wrapper]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Why might the wrapper have anything to do? The full story is
in wrapper_reqd in MkId.mkDataConRep.
* Unboxing strict fields (with -funbox-strict-fields)
data T = MkT !(Int,Int)
\$wMkT :: (Int,Int) -> T
\$wMkT (x,y) = MkT x y
Notice that the worker has two fields where the wapper has
just one. That is, the worker has type
MkT :: Int -> Int -> T
* Equality constraints for GADTs
data T a where { MkT :: a -> T [a] }
The worker gets a type with explicit equality
constraints, thus:
MkT :: forall a b. (a=[b]) => b -> T a
The wrapper has the programmer-specified type:
\$wMkT :: a -> T [a]
\$wMkT a x = MkT [a] a [a] x
The third argument is a coercion
[a] :: [a]~[a]
* Data family instances may do a cast on the result
* Type variables may be permuted; see MkId
Note [Data con wrappers and GADT syntax]
Note [The stupid context]
~~~~~~~~~~~~~~~~~~~~~~~~~
Data types can have a context:
data (Eq a, Ord b) => T a b = T1 a b | T2 a
and that makes the constructors have a context too
(notice that T2's context is "thinned"):
T1 :: (Eq a, Ord b) => a -> b -> T a b
T2 :: (Eq a) => a -> T a b
Furthermore, this context pops up when pattern matching
(though GHC hasn't implemented this, but it is in H98, and
I've fixed GHC so that it now does):
f (T2 x) = x
gets inferred type
f :: Eq a => T a b -> a
I say the context is "stupid" because the dictionaries passed
are immediately discarded -- they do nothing and have no benefit.
It's a flaw in the language.
Up to now [March 2002] I have put this stupid context into the
type of the "wrapper" constructors functions, T1 and T2, but
that turned out to be jolly inconvenient for generics, and
record update, and other functions that build values of type T
(because they don't have suitable dictionaries available).
So now I've taken the stupid context out. I simply deal with
it separately in the type checker on occurrences of a
constructor, either in an expression or in a pattern.
[May 2003: actually I think this decision could easily be
reversed now, and probably should be. Generics could be
disabled for types with a stupid context; record updates now
(H98) needs the context too; etc. It's an unforced change, so
I'm leaving it for now --- but it does seem odd that the
wrapper doesn't include the stupid context.]
[July 04] With the advent of generalised data types, it's less obvious
what the "stupid context" is. Consider
C :: forall a. Ord a => a -> a -> T (Foo a)
Does the C constructor in Core contain the Ord dictionary? Yes, it must:
f :: T b -> Ordering
f = /\b. \x:T b.
case x of
C a (d:Ord a) (p:a) (q:a) -> compare d p q
Note that (Foo a) might not be an instance of Ord.
************************************************************************
* *
\subsection{Data constructors}
* *
************************************************************************
-}
-- | A data constructor
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose','ApiAnnotation.AnnComma'
-- For details on above see note [Api annotations] in ApiAnnotation
data DataCon
= MkData {
dcName :: Name, -- This is the name of the *source data con*
-- (see "Note [Data Constructor Naming]" above)
dcUnique :: Unique, -- Cached from Name
dcTag :: ConTag, -- ^ Tag, used for ordering 'DataCon's
-- Running example:
--
-- *** As declared by the user
-- data T a b c where
-- MkT :: forall c y x b. (x~y,Ord x) => x -> y -> T (x,y) b c
-- *** As represented internally
-- data T a b c where
-- MkT :: forall a b c. forall x y. (a~(x,y),x~y,Ord x)
-- => x -> y -> T a b c
--
-- The next six fields express the type of the constructor, in pieces
-- e.g.
--
-- dcUnivTyVars = [a,b,c]
-- dcExTyCoVars = [x,y]
-- dcUserTyVarBinders = [c,y,x,b]
-- dcEqSpec = [a~(x,y)]
-- dcOtherTheta = [x~y, Ord x]
-- dcOrigArgTys = [x,y]
-- dcRepTyCon = T
-- In general, the dcUnivTyVars are NOT NECESSARILY THE SAME AS THE
-- TYVARS FOR THE PARENT TyCon. (This is a change (Oct05): previously,
-- vanilla datacons guaranteed to have the same type variables as their
-- parent TyCon, but that seems ugly.) They can be different in the case
-- where a GADT constructor uses different names for the universal
-- tyvars than does the tycon. For example:
--
-- data H a where
-- MkH :: b -> H b
--
-- Here, the tyConTyVars of H will be [a], but the dcUnivTyVars of MkH
-- will be [b].
dcVanilla :: Bool, -- True <=> This is a vanilla Haskell 98 data constructor
-- Its type is of form
-- forall a1..an . t1 -> ... tm -> T a1..an
-- No existentials, no coercions, nothing.
-- That is: dcExTyCoVars = dcEqSpec = dcOtherTheta = []
-- NB 1: newtypes always have a vanilla data con
-- NB 2: a vanilla constructor can still be declared in GADT-style
-- syntax, provided its type looks like the above.
-- The declaration format is held in the TyCon (algTcGadtSyntax)
-- Universally-quantified type vars [a,b,c]
-- INVARIANT: length matches arity of the dcRepTyCon
-- INVARIANT: result type of data con worker is exactly (T a b c)
-- COROLLARY: The dcUnivTyVars are always in one-to-one correspondence with
-- the tyConTyVars of the parent TyCon
dcUnivTyVars :: [TyVar],
-- Existentially-quantified type and coercion vars [x,y]
-- For an example involving coercion variables,
-- Why tycovars? See Note [Existential coercion variables]
dcExTyCoVars :: [TyCoVar],
-- INVARIANT: the UnivTyVars and ExTyCoVars all have distinct OccNames
-- Reason: less confusing, and easier to generate Iface syntax
-- The type/coercion vars in the order the user wrote them [c,y,x,b]
-- INVARIANT: the set of tyvars in dcUserTyVarBinders is exactly the set
-- of tyvars (*not* covars) of dcExTyCoVars unioned with the
-- set of dcUnivTyVars whose tyvars do not appear in dcEqSpec
-- See Note [DataCon user type variable binders]
dcUserTyVarBinders :: [TyVarBinder],
dcEqSpec :: [EqSpec], -- Equalities derived from the result type,
-- _as written by the programmer_.
-- Only non-dependent GADT equalities (dependent
-- GADT equalities are in the covars of
-- dcExTyCoVars).
-- This field allows us to move conveniently between the two ways
-- of representing a GADT constructor's type:
-- MkT :: forall a b. (a ~ [b]) => b -> T a
-- MkT :: forall b. b -> T [b]
-- Each equality is of the form (a ~ ty), where 'a' is one of
-- the universally quantified type variables
-- The next two fields give the type context of the data constructor
-- (aside from the GADT constraints,
-- which are given by the dcExpSpec)
-- In GADT form, this is *exactly* what the programmer writes, even if
-- the context constrains only universally quantified variables
-- MkT :: forall a b. (a ~ b, Ord b) => a -> T a b
dcOtherTheta :: ThetaType, -- The other constraints in the data con's type
-- other than those in the dcEqSpec
dcStupidTheta :: ThetaType, -- The context of the data type declaration
-- data Eq a => T a = ...
-- or, rather, a "thinned" version thereof
-- "Thinned", because the Report says
-- to eliminate any constraints that don't mention
-- tyvars free in the arg types for this constructor
--
-- INVARIANT: the free tyvars of dcStupidTheta are a subset of dcUnivTyVars
-- Reason: dcStupidTeta is gotten by thinning the stupid theta from the tycon
--
-- "Stupid", because the dictionaries aren't used for anything.
-- Indeed, [as of March 02] they are no longer in the type of
-- the wrapper Id, because that makes it harder to use the wrap-id
-- to rebuild values after record selection or in generics.
dcOrigArgTys :: [Type], -- Original argument types
-- (before unboxing and flattening of strict fields)
dcOrigResTy :: Type, -- Original result type, as seen by the user
-- NB: for a data instance, the original user result type may
-- differ from the DataCon's representation TyCon. Example
-- data instance T [a] where MkT :: a -> T [a]
-- The OrigResTy is T [a], but the dcRepTyCon might be :T123
-- Now the strictness annotations and field labels of the constructor
dcSrcBangs :: [HsSrcBang],
-- See Note [Bangs on data constructor arguments]
--
-- The [HsSrcBang] as written by the programmer.
--
-- Matches 1-1 with dcOrigArgTys
-- Hence length = dataConSourceArity dataCon
dcFields :: [FieldLabel],
-- Field labels for this constructor, in the
-- same order as the dcOrigArgTys;
-- length = 0 (if not a record) or dataConSourceArity.
-- The curried worker function that corresponds to the constructor:
-- It doesn't have an unfolding; the code generator saturates these Ids
-- and allocates a real constructor when it finds one.
dcWorkId :: Id,
-- Constructor representation
dcRep :: DataConRep,
-- Cached; see Note [DataCon arities]
-- INVARIANT: dcRepArity == length dataConRepArgTys + count isCoVar (dcExTyCoVars)
-- INVARIANT: dcSourceArity == length dcOrigArgTys
dcRepArity :: Arity,
dcSourceArity :: Arity,
-- Result type of constructor is T t1..tn
dcRepTyCon :: TyCon, -- Result tycon, T
dcRepType :: Type, -- Type of the constructor
-- forall a x y. (a~(x,y), x~y, Ord x) =>
-- x -> y -> T a
-- (this is *not* of the constructor wrapper Id:
-- see Note [Data con representation] below)
-- Notice that the existential type parameters come *second*.
-- Reason: in a case expression we may find:
-- case (e :: T t) of
-- MkT x y co1 co2 (d:Ord x) (v:r) (w:F s) -> ...
-- It's convenient to apply the rep-type of MkT to 't', to get
-- forall x y. (t~(x,y), x~y, Ord x) => x -> y -> T t
-- and use that to check the pattern. Mind you, this is really only
-- used in CoreLint.
dcInfix :: Bool, -- True <=> declared infix
-- Used for Template Haskell and 'deriving' only
-- The actual fixity is stored elsewhere
dcPromoted :: TyCon -- The promoted TyCon
-- See Note [Promoted data constructors] in TyCon
}
{- Note [TyVarBinders in DataCons]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For the TyVarBinders in a DataCon and PatSyn:
* Each argument flag is Inferred or Specified.
None are Required. (A DataCon is a term-level function; see
Note [No Required TyCoBinder in terms] in TyCoRep.)
Why do we need the TyVarBinders, rather than just the TyVars? So that
we can construct the right type for the DataCon with its foralls
attributed the correct visibility. That in turn governs whether you
can use visible type application at a call of the data constructor.
See also [DataCon user type variable binders] for an extended discussion on the
order in which TyVarBinders appear in a DataCon.
Note [Existential coercion variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For now (Aug 2018) we can't write coercion quantifications in source Haskell, but
we can in Core. Consider having:
data T :: forall k. k -> k -> Constraint where
MkT :: forall k (a::k) (b::k). forall k' (c::k') (co::k'~k). (b~(c|>co))
=> T k a b
dcUnivTyVars = [k,a,b]
dcExTyCoVars = [k',c,co]
dcUserTyVarBinders = [k,a,k',c]
dcEqSpec = [b~(c|>co)]
dcOtherTheta = []
dcOrigArgTys = []
dcRepTyCon = T
Function call 'dataConKindEqSpec' returns [k'~k]
Note [DataCon arities]
~~~~~~~~~~~~~~~~~~~~~~
dcSourceArity does not take constraints into account,
but dcRepArity does. For example:
MkT :: Ord a => a -> T a
dcSourceArity = 1
dcRepArity = 2
Note [DataCon user type variable binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In System FC, data constructor type signatures always quantify over all of
their universal type variables, followed by their existential type variables.
Normally, this isn't a problem, as most datatypes naturally quantify their type
variables in this order anyway. For example:
data T a b = forall c. MkT b c
Here, we have `MkT :: forall {k} (a :: k) (b :: *) (c :: *). b -> c -> T a b`,
where k, a, and b are universal and c is existential. (The inferred variable k
isn't available for TypeApplications, hence why it's in braces.) This is a
perfectly reasonable order to use, as the syntax of H98-style datatypes
(+ ExistentialQuantification) suggests it.
Things become more complicated when GADT syntax enters the picture. Consider
this example:
data X a where
MkX :: forall b a. b -> Proxy a -> X a
If we adopt the earlier approach of quantifying all the universal variables
followed by all the existential ones, GHC would come up with this type
signature for MkX:
MkX :: forall {k} (a :: k) (b :: *). b -> Proxy a -> X a
But this is not what we want at all! After all, if a user were to use
TypeApplications on MkX, they would expect to instantiate `b` before `a`,
as that's the order in which they were written in the `forall`. (See #11721.)
Instead, we'd like GHC to come up with this type signature:
MkX :: forall {k} (b :: *) (a :: k). b -> Proxy a -> X a
In fact, even if we left off the explicit forall:
data X a where
MkX :: b -> Proxy a -> X a
Then a user should still expect `b` to be quantified before `a`, since
according to the rules of TypeApplications, in the absence of `forall` GHC
performs a stable topological sort on the type variables in the user-written
type signature, which would place `b` before `a`.
But as noted above, enacting this behavior is not entirely trivial, as System
FC demands the variables go in universal-then-existential order under the hood.
Our solution is thus to equip DataCon with two different sets of type
variables:
* dcUnivTyVars and dcExTyCoVars, for the universal type variable and existential
type/coercion variables, respectively. Their order is irrelevant for the
purposes of TypeApplications, and as a consequence, they do not come equipped
with visibilities (that is, they are TyVars/TyCoVars instead of
TyCoVarBinders).
* dcUserTyVarBinders, for the type variables binders in the order in which they
originally arose in the user-written type signature. Their order *does* matter
for TypeApplications, so they are full TyVarBinders, complete with
visibilities.
This encoding has some redundancy. The set of tyvars in dcUserTyVarBinders
consists precisely of:
* The set of tyvars in dcUnivTyVars whose type variables do not appear in
dcEqSpec, unioned with:
* The set of tyvars (*not* covars) in dcExTyCoVars
No covars here because because they're not user-written
The word "set" is used above because the order in which the tyvars appear in
dcUserTyVarBinders can be completely different from the order in dcUnivTyVars or
dcExTyCoVars. That is, the tyvars in dcUserTyVarBinders are a permutation of
(tyvars of dcExTyCoVars + a subset of dcUnivTyVars). But aside from the
ordering, they in fact share the same type variables (with the same Uniques). We
sometimes refer to this as "the dcUserTyVarBinders invariant".
dcUserTyVarBinders, as the name suggests, is the one that users will see most of
the time. It's used when computing the type signature of a data constructor (see
dataConUserType), and as a result, it's what matters from a TypeApplications
perspective.
-}
-- | Data Constructor Representation
-- See Note [Data constructor workers and wrappers]
data DataConRep
= -- NoDataConRep means that the data con has no wrapper
NoDataConRep
-- DCR means that the data con has a wrapper
| DCR { dcr_wrap_id :: Id -- Takes src args, unboxes/flattens,
-- and constructs the representation
, dcr_boxer :: DataConBoxer
, dcr_arg_tys :: [Type] -- Final, representation argument types,
-- after unboxing and flattening,
-- and *including* all evidence args
, dcr_stricts :: [StrictnessMark] -- 1-1 with dcr_arg_tys
-- See also Note [Data-con worker strictness] in MkId.hs
, dcr_bangs :: [HsImplBang] -- The actual decisions made (including failures)
-- about the original arguments; 1-1 with orig_arg_tys
-- See Note [Bangs on data constructor arguments]
}
-------------------------
-- | Haskell Source Bang
--
-- Bangs on data constructor arguments as the user wrote them in the
-- source code.
--
-- @(HsSrcBang _ SrcUnpack SrcLazy)@ and
-- @(HsSrcBang _ SrcUnpack NoSrcStrict)@ (without StrictData) makes no sense, we
-- emit a warning (in checkValidDataCon) and treat it like
-- @(HsSrcBang _ NoSrcUnpack SrcLazy)@
data HsSrcBang =
HsSrcBang SourceText -- Note [Pragma source text] in BasicTypes
SrcUnpackedness
SrcStrictness
deriving Data.Data
-- | Haskell Implementation Bang
--
-- Bangs of data constructor arguments as generated by the compiler
-- after consulting HsSrcBang, flags, etc.
data HsImplBang
= HsLazy -- ^ Lazy field, or one with an unlifted type
| HsStrict -- ^ Strict but not unpacked field
| HsUnpack (Maybe Coercion)
-- ^ Strict and unpacked field
-- co :: arg-ty ~ product-ty HsBang
deriving Data.Data
-- | Source Strictness
--
-- What strictness annotation the user wrote
data SrcStrictness = SrcLazy -- ^ Lazy, ie '~'
| SrcStrict -- ^ Strict, ie '!'
| NoSrcStrict -- ^ no strictness annotation
deriving (Eq, Data.Data)
-- | Source Unpackedness
--
-- What unpackedness the user requested
data SrcUnpackedness = SrcUnpack -- ^ {-# UNPACK #-} specified
| SrcNoUnpack -- ^ {-# NOUNPACK #-} specified
| NoSrcUnpack -- ^ no unpack pragma
deriving (Eq, Data.Data)
-------------------------
-- StrictnessMark is internal only, used to indicate strictness
-- of the DataCon *worker* fields
data StrictnessMark = MarkedStrict | NotMarkedStrict
-- | An 'EqSpec' is a tyvar/type pair representing an equality made in
-- rejigging a GADT constructor
data EqSpec = EqSpec TyVar
Type
-- | Make a non-dependent 'EqSpec'
mkEqSpec :: TyVar -> Type -> EqSpec
mkEqSpec tv ty = EqSpec tv ty
eqSpecTyVar :: EqSpec -> TyVar
eqSpecTyVar (EqSpec tv _) = tv
eqSpecType :: EqSpec -> Type
eqSpecType (EqSpec _ ty) = ty
eqSpecPair :: EqSpec -> (TyVar, Type)
eqSpecPair (EqSpec tv ty) = (tv, ty)
eqSpecPreds :: [EqSpec] -> ThetaType
eqSpecPreds spec = [ mkPrimEqPred (mkTyVarTy tv) ty
| EqSpec tv ty <- spec ]
-- | Substitute in an 'EqSpec'. Precondition: if the LHS of the EqSpec
-- is mapped in the substitution, it is mapped to a type variable, not
-- a full type.
substEqSpec :: TCvSubst -> EqSpec -> EqSpec
substEqSpec subst (EqSpec tv ty)
= EqSpec tv' (substTy subst ty)
where
tv' = getTyVar "substEqSpec" (substTyVar subst tv)
-- | Filter out any 'TyVar's mentioned in an 'EqSpec'.
filterEqSpec :: [EqSpec] -> [TyVar] -> [TyVar]
filterEqSpec eq_spec
= filter not_in_eq_spec
where
not_in_eq_spec var = all (not . (== var) . eqSpecTyVar) eq_spec
instance Outputable EqSpec where
ppr (EqSpec tv ty) = ppr (tv, ty)
{- Note [Bangs on data constructor arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data T = MkT !Int {-# UNPACK #-} !Int Bool
When compiling the module, GHC will decide how to represent
MkT, depending on the optimisation level, and settings of
flags like -funbox-small-strict-fields.
Terminology:
* HsSrcBang: What the user wrote
Constructors: HsSrcBang
* HsImplBang: What GHC decided
Constructors: HsLazy, HsStrict, HsUnpack
* If T was defined in this module, MkT's dcSrcBangs field
records the [HsSrcBang] of what the user wrote; in the example
[ HsSrcBang _ NoSrcUnpack SrcStrict
, HsSrcBang _ SrcUnpack SrcStrict
, HsSrcBang _ NoSrcUnpack NoSrcStrictness]
* However, if T was defined in an imported module, the importing module
must follow the decisions made in the original module, regardless of
the flag settings in the importing module.
Also see Note [Bangs on imported data constructors] in MkId
* The dcr_bangs field of the dcRep field records the [HsImplBang]
If T was defined in this module, Without -O the dcr_bangs might be
[HsStrict, HsStrict, HsLazy]
With -O it might be
[HsStrict, HsUnpack _, HsLazy]
With -funbox-small-strict-fields it might be
[HsUnpack, HsUnpack _, HsLazy]
With -XStrictData it might be
[HsStrict, HsUnpack _, HsStrict]
Note [Data con representation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The dcRepType field contains the type of the representation of a constructor
This may differ from the type of the constructor *Id* (built
by MkId.mkDataConId) for two reasons:
a) the constructor Id may be overloaded, but the dictionary isn't stored
e.g. data Eq a => T a = MkT a a
b) the constructor may store an unboxed version of a strict field.
Here's an example illustrating both:
data Ord a => T a = MkT Int! a
Here
T :: Ord a => Int -> a -> T a
but the rep type is
Trep :: Int# -> a -> T a
Actually, the unboxed part isn't implemented yet!
************************************************************************
* *
\subsection{Instances}
* *
************************************************************************
-}
instance Eq DataCon where
a == b = getUnique a == getUnique b
a /= b = getUnique a /= getUnique b
instance Uniquable DataCon where
getUnique = dcUnique
instance NamedThing DataCon where
getName = dcName
instance Outputable DataCon where
ppr con = ppr (dataConName con)
instance OutputableBndr DataCon where
pprInfixOcc con = pprInfixName (dataConName con)
pprPrefixOcc con = pprPrefixName (dataConName con)
instance Data.Data DataCon where
-- don't traverse?
toConstr _ = abstractConstr "DataCon"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "DataCon"
instance Outputable HsSrcBang where
ppr (HsSrcBang _ prag mark) = ppr prag <+> ppr mark
instance Outputable HsImplBang where
ppr HsLazy = text "Lazy"
ppr (HsUnpack Nothing) = text "Unpacked"
ppr (HsUnpack (Just co)) = text "Unpacked" <> parens (ppr co)
ppr HsStrict = text "StrictNotUnpacked"
instance Outputable SrcStrictness where
ppr SrcLazy = char '~'
ppr SrcStrict = char '!'
ppr NoSrcStrict = empty
instance Outputable SrcUnpackedness where
ppr SrcUnpack = text "{-# UNPACK #-}"
ppr SrcNoUnpack = text "{-# NOUNPACK #-}"
ppr NoSrcUnpack = empty
instance Outputable StrictnessMark where
ppr MarkedStrict = text "!"
ppr NotMarkedStrict = empty
instance Binary SrcStrictness where
put_ bh SrcLazy = putByte bh 0
put_ bh SrcStrict = putByte bh 1
put_ bh NoSrcStrict = putByte bh 2
get bh =
do h <- getByte bh
case h of
0 -> return SrcLazy
1 -> return SrcStrict
_ -> return NoSrcStrict
instance Binary SrcUnpackedness where
put_ bh SrcNoUnpack = putByte bh 0
put_ bh SrcUnpack = putByte bh 1
put_ bh NoSrcUnpack = putByte bh 2
get bh =
do h <- getByte bh
case h of
0 -> return SrcNoUnpack
1 -> return SrcUnpack
_ -> return NoSrcUnpack
-- | Compare strictness annotations
eqHsBang :: HsImplBang -> HsImplBang -> Bool
eqHsBang HsLazy HsLazy = True
eqHsBang HsStrict HsStrict = True
eqHsBang (HsUnpack Nothing) (HsUnpack Nothing) = True
eqHsBang (HsUnpack (Just c1)) (HsUnpack (Just c2))
= eqType (coercionType c1) (coercionType c2)
eqHsBang _ _ = False
isBanged :: HsImplBang -> Bool
isBanged (HsUnpack {}) = True
isBanged (HsStrict {}) = True
isBanged HsLazy = False
isSrcStrict :: SrcStrictness -> Bool
isSrcStrict SrcStrict = True
isSrcStrict _ = False
isSrcUnpacked :: SrcUnpackedness -> Bool
isSrcUnpacked SrcUnpack = True
isSrcUnpacked _ = False
isMarkedStrict :: StrictnessMark -> Bool
isMarkedStrict NotMarkedStrict = False
isMarkedStrict _ = True -- All others are strict
{- *********************************************************************
* *
\subsection{Construction}
* *
********************************************************************* -}
-- | Build a new data constructor
mkDataCon :: Name
-> Bool -- ^ Is the constructor declared infix?
-> TyConRepName -- ^ TyConRepName for the promoted TyCon
-> [HsSrcBang] -- ^ Strictness/unpack annotations, from user
-> [FieldLabel] -- ^ Field labels for the constructor,
-- if it is a record, otherwise empty
-> [TyVar] -- ^ Universals.
-> [TyCoVar] -- ^ Existentials.
-> [TyVarBinder] -- ^ User-written 'TyVarBinder's.
-- These must be Inferred/Specified.
-- See @Note [TyVarBinders in DataCons]@
-> [EqSpec] -- ^ GADT equalities
-> KnotTied ThetaType -- ^ Theta-type occurring before the arguments proper
-> [KnotTied Type] -- ^ Original argument types
-> KnotTied Type -- ^ Original result type
-> RuntimeRepInfo -- ^ See comments on 'TyCon.RuntimeRepInfo'
-> KnotTied TyCon -- ^ Representation type constructor
-> ConTag -- ^ Constructor tag
-> ThetaType -- ^ The "stupid theta", context of the data
-- declaration e.g. @data Eq a => T a ...@
-> Id -- ^ Worker Id
-> DataConRep -- ^ Representation
-> DataCon
-- Can get the tag from the TyCon
mkDataCon name declared_infix prom_info
arg_stricts -- Must match orig_arg_tys 1-1
fields
univ_tvs ex_tvs user_tvbs
eq_spec theta
orig_arg_tys orig_res_ty rep_info rep_tycon tag
stupid_theta work_id rep
-- Warning: mkDataCon is not a good place to check certain invariants.
-- If the programmer writes the wrong result type in the decl, thus:
-- data T a where { MkT :: S }
-- then it's possible that the univ_tvs may hit an assertion failure
-- if you pull on univ_tvs. This case is checked by checkValidDataCon,
-- so the error is detected properly... it's just that assertions here
-- are a little dodgy.
= con
where
is_vanilla = null ex_tvs && null eq_spec && null theta
con = MkData {dcName = name, dcUnique = nameUnique name,
dcVanilla = is_vanilla, dcInfix = declared_infix,
dcUnivTyVars = univ_tvs,
dcExTyCoVars = ex_tvs,
dcUserTyVarBinders = user_tvbs,
dcEqSpec = eq_spec,
dcOtherTheta = theta,
dcStupidTheta = stupid_theta,
dcOrigArgTys = orig_arg_tys, dcOrigResTy = orig_res_ty,
dcRepTyCon = rep_tycon,
dcSrcBangs = arg_stricts,
dcFields = fields, dcTag = tag, dcRepType = rep_ty,
dcWorkId = work_id,
dcRep = rep,
dcSourceArity = length orig_arg_tys,
dcRepArity = length rep_arg_tys + count isCoVar ex_tvs,
dcPromoted = promoted }
-- The 'arg_stricts' passed to mkDataCon are simply those for the
-- source-language arguments. We add extra ones for the
-- dictionary arguments right here.
rep_arg_tys = dataConRepArgTys con
rep_ty =
case rep of
-- If the DataCon has no wrapper, then the worker's type *is* the
-- user-facing type, so we can simply use dataConUserType.
NoDataConRep -> dataConUserType con
-- If the DataCon has a wrapper, then the worker's type is never seen
-- by the user. The visibilities we pick do not matter here.
DCR{} -> mkInvForAllTys univ_tvs $ mkTyCoInvForAllTys ex_tvs $
mkVisFunTys rep_arg_tys $
mkTyConApp rep_tycon (mkTyVarTys univ_tvs)
-- See Note [Promoted data constructors] in TyCon
prom_tv_bndrs = [ mkNamedTyConBinder vis tv
| Bndr tv vis <- user_tvbs ]
fresh_names = freshNames (map getName user_tvbs)
-- fresh_names: make sure that the "anonymous" tyvars don't
-- clash in name or unique with the universal/existential ones.
-- Tiresome! And unnecessary because these tyvars are never looked at
prom_theta_bndrs = [ mkAnonTyConBinder InvisArg (mkTyVar n t)
{- Invisible -} | (n,t) <- fresh_names `zip` theta ]
prom_arg_bndrs = [ mkAnonTyConBinder VisArg (mkTyVar n t)
{- Visible -} | (n,t) <- dropList theta fresh_names `zip` orig_arg_tys ]
prom_bndrs = prom_tv_bndrs ++ prom_theta_bndrs ++ prom_arg_bndrs
prom_res_kind = orig_res_ty
promoted = mkPromotedDataCon con name prom_info prom_bndrs
prom_res_kind roles rep_info
roles = map (\tv -> if isTyVar tv then Nominal else Phantom)
(univ_tvs ++ ex_tvs)
++ map (const Representational) (theta ++ orig_arg_tys)
freshNames :: [Name] -> [Name]
-- Make an infinite list of Names whose Uniques and OccNames
-- differ from those in the 'avoid' list
freshNames avoids
= [ mkSystemName uniq occ
| n <- [0..]
, let uniq = mkAlphaTyVarUnique n
occ = mkTyVarOccFS (mkFastString ('x' : show n))
, not (uniq `elementOfUniqSet` avoid_uniqs)
, not (occ `elemOccSet` avoid_occs) ]
where
avoid_uniqs :: UniqSet Unique
avoid_uniqs = mkUniqSet (map getUnique avoids)
avoid_occs :: OccSet
avoid_occs = mkOccSet (map getOccName avoids)
-- | The 'Name' of the 'DataCon', giving it a unique, rooted identification
dataConName :: DataCon -> Name
dataConName = dcName
-- | The tag used for ordering 'DataCon's
dataConTag :: DataCon -> ConTag
dataConTag = dcTag
dataConTagZ :: DataCon -> ConTagZ
dataConTagZ con = dataConTag con - fIRST_TAG
-- | The type constructor that we are building via this data constructor
dataConTyCon :: DataCon -> TyCon
dataConTyCon = dcRepTyCon
-- | The original type constructor used in the definition of this data
-- constructor. In case of a data family instance, that will be the family
-- type constructor.
dataConOrigTyCon :: DataCon -> TyCon
dataConOrigTyCon dc
| Just (tc, _) <- tyConFamInst_maybe (dcRepTyCon dc) = tc
| otherwise = dcRepTyCon dc
-- | The representation type of the data constructor, i.e. the sort
-- type that will represent values of this type at runtime
dataConRepType :: DataCon -> Type
dataConRepType = dcRepType
-- | Should the 'DataCon' be presented infix?
dataConIsInfix :: DataCon -> Bool
dataConIsInfix = dcInfix
-- | The universally-quantified type variables of the constructor
dataConUnivTyVars :: DataCon -> [TyVar]
dataConUnivTyVars (MkData { dcUnivTyVars = tvbs }) = tvbs
-- | The existentially-quantified type/coercion variables of the constructor
-- including dependent (kind-) GADT equalities
dataConExTyCoVars :: DataCon -> [TyCoVar]
dataConExTyCoVars (MkData { dcExTyCoVars = tvbs }) = tvbs
-- | Both the universal and existential type/coercion variables of the constructor
dataConUnivAndExTyCoVars :: DataCon -> [TyCoVar]
dataConUnivAndExTyCoVars (MkData { dcUnivTyVars = univ_tvs, dcExTyCoVars = ex_tvs })
= univ_tvs ++ ex_tvs
-- See Note [DataCon user type variable binders]
-- | The type variables of the constructor, in the order the user wrote them
dataConUserTyVars :: DataCon -> [TyVar]
dataConUserTyVars (MkData { dcUserTyVarBinders = tvbs }) = binderVars tvbs
-- See Note [DataCon user type variable binders]
-- | 'TyCoVarBinder's for the type variables of the constructor, in the order the
-- user wrote them
dataConUserTyVarBinders :: DataCon -> [TyVarBinder]
dataConUserTyVarBinders = dcUserTyVarBinders
-- | Equalities derived from the result type of the data constructor, as written
-- by the programmer in any GADT declaration. This includes *all* GADT-like
-- equalities, including those written in by hand by the programmer.
dataConEqSpec :: DataCon -> [EqSpec]
dataConEqSpec con@(MkData { dcEqSpec = eq_spec, dcOtherTheta = theta })
= dataConKindEqSpec con
++ eq_spec ++
[ spec -- heterogeneous equality
| Just (tc, [_k1, _k2, ty1, ty2]) <- map splitTyConApp_maybe theta
, tc `hasKey` heqTyConKey
, spec <- case (getTyVar_maybe ty1, getTyVar_maybe ty2) of
(Just tv1, _) -> [mkEqSpec tv1 ty2]
(_, Just tv2) -> [mkEqSpec tv2 ty1]
_ -> []
] ++
[ spec -- homogeneous equality
| Just (tc, [_k, ty1, ty2]) <- map splitTyConApp_maybe theta
, tc `hasKey` eqTyConKey
, spec <- case (getTyVar_maybe ty1, getTyVar_maybe ty2) of
(Just tv1, _) -> [mkEqSpec tv1 ty2]
(_, Just tv2) -> [mkEqSpec tv2 ty1]
_ -> []
]
-- | Dependent (kind-level) equalities in a constructor.
-- There are extracted from the existential variables.
-- See Note [Existential coercion variables]
dataConKindEqSpec :: DataCon -> [EqSpec]
dataConKindEqSpec (MkData {dcExTyCoVars = ex_tcvs})
-- It is used in 'dataConEqSpec' (maybe also 'dataConFullSig' in the future),
-- which are frequently used functions.
-- For now (Aug 2018) this function always return empty set as we don't really
-- have coercion variables.
-- In the future when we do, we might want to cache this information in DataCon
-- so it won't be computed every time when aforementioned functions are called.
= [ EqSpec tv ty
| cv <- ex_tcvs
, isCoVar cv
, let (_, _, ty1, ty, _) = coVarKindsTypesRole cv
tv = getTyVar "dataConKindEqSpec" ty1
]
-- | The *full* constraints on the constructor type, including dependent GADT
-- equalities.
dataConTheta :: DataCon -> ThetaType
dataConTheta con@(MkData { dcEqSpec = eq_spec, dcOtherTheta = theta })
= eqSpecPreds (dataConKindEqSpec con ++ eq_spec) ++ theta
-- | Get the Id of the 'DataCon' worker: a function that is the "actual"
-- constructor and has no top level binding in the program. The type may
-- be different from the obvious one written in the source program. Panics
-- if there is no such 'Id' for this 'DataCon'
dataConWorkId :: DataCon -> Id
dataConWorkId dc = dcWorkId dc
-- | Get the Id of the 'DataCon' wrapper: a function that wraps the "actual"
-- constructor so it has the type visible in the source program: c.f.
-- 'dataConWorkId'.
-- Returns Nothing if there is no wrapper, which occurs for an algebraic data
-- constructor and also for a newtype (whose constructor is inlined
-- compulsorily)
dataConWrapId_maybe :: DataCon -> Maybe Id
dataConWrapId_maybe dc = case dcRep dc of
NoDataConRep -> Nothing
DCR { dcr_wrap_id = wrap_id } -> Just wrap_id
-- | Returns an Id which looks like the Haskell-source constructor by using
-- the wrapper if it exists (see 'dataConWrapId_maybe') and failing over to
-- the worker (see 'dataConWorkId')
dataConWrapId :: DataCon -> Id
dataConWrapId dc = case dcRep dc of
NoDataConRep-> dcWorkId dc -- worker=wrapper
DCR { dcr_wrap_id = wrap_id } -> wrap_id
-- | Find all the 'Id's implicitly brought into scope by the data constructor. Currently,
-- the union of the 'dataConWorkId' and the 'dataConWrapId'
dataConImplicitTyThings :: DataCon -> [TyThing]
dataConImplicitTyThings (MkData { dcWorkId = work, dcRep = rep })
= [AnId work] ++ wrap_ids
where
wrap_ids = case rep of
NoDataConRep -> []
DCR { dcr_wrap_id = wrap } -> [AnId wrap]
-- | The labels for the fields of this particular 'DataCon'
dataConFieldLabels :: DataCon -> [FieldLabel]
dataConFieldLabels = dcFields
-- | Extract the type for any given labelled field of the 'DataCon'
dataConFieldType :: DataCon -> FieldLabelString -> Type
dataConFieldType con label = case dataConFieldType_maybe con label of
Just (_, ty) -> ty
Nothing -> pprPanic "dataConFieldType" (ppr con <+> ppr label)
-- | Extract the label and type for any given labelled field of the
-- 'DataCon', or return 'Nothing' if the field does not belong to it
dataConFieldType_maybe :: DataCon -> FieldLabelString
-> Maybe (FieldLabel, Type)
dataConFieldType_maybe con label
= find ((== label) . flLabel . fst) (dcFields con `zip` dcOrigArgTys con)
-- | Strictness/unpack annotations, from user; or, for imported
-- DataCons, from the interface file
-- The list is in one-to-one correspondence with the arity of the 'DataCon'
dataConSrcBangs :: DataCon -> [HsSrcBang]
dataConSrcBangs = dcSrcBangs
-- | Source-level arity of the data constructor
dataConSourceArity :: DataCon -> Arity
dataConSourceArity (MkData { dcSourceArity = arity }) = arity
-- | Gives the number of actual fields in the /representation/ of the
-- data constructor. This may be more than appear in the source code;
-- the extra ones are the existentially quantified dictionaries
dataConRepArity :: DataCon -> Arity
dataConRepArity (MkData { dcRepArity = arity }) = arity
-- | Return whether there are any argument types for this 'DataCon's original source type
-- See Note [DataCon arities]
isNullarySrcDataCon :: DataCon -> Bool
isNullarySrcDataCon dc = dataConSourceArity dc == 0
-- | Return whether there are any argument types for this 'DataCon's runtime representation type
-- See Note [DataCon arities]
isNullaryRepDataCon :: DataCon -> Bool
isNullaryRepDataCon dc = dataConRepArity dc == 0
dataConRepStrictness :: DataCon -> [StrictnessMark]
-- ^ Give the demands on the arguments of a
-- Core constructor application (Con dc args)
dataConRepStrictness dc = case dcRep dc of
NoDataConRep -> [NotMarkedStrict | _ <- dataConRepArgTys dc]
DCR { dcr_stricts = strs } -> strs
dataConImplBangs :: DataCon -> [HsImplBang]
-- The implementation decisions about the strictness/unpack of each
-- source program argument to the data constructor
dataConImplBangs dc
= case dcRep dc of
NoDataConRep -> replicate (dcSourceArity dc) HsLazy
DCR { dcr_bangs = bangs } -> bangs
dataConBoxer :: DataCon -> Maybe DataConBoxer
dataConBoxer (MkData { dcRep = DCR { dcr_boxer = boxer } }) = Just boxer
dataConBoxer _ = Nothing
dataConInstSig
:: DataCon
-> [Type] -- Instantiate the *universal* tyvars with these types
-> ([TyCoVar], ThetaType, [Type]) -- Return instantiated existentials
-- theta and arg tys
-- ^ Instantiate the universal tyvars of a data con,
-- returning
-- ( instantiated existentials
-- , instantiated constraints including dependent GADT equalities
-- which are *also* listed in the instantiated existentials
-- , instantiated args)
dataConInstSig con@(MkData { dcUnivTyVars = univ_tvs, dcExTyCoVars = ex_tvs
, dcOrigArgTys = arg_tys })
univ_tys
= ( ex_tvs'
, substTheta subst (dataConTheta con)
, substTys subst arg_tys)
where
univ_subst = zipTvSubst univ_tvs univ_tys
(subst, ex_tvs') = Type.substVarBndrs univ_subst ex_tvs
-- | The \"full signature\" of the 'DataCon' returns, in order:
--
-- 1) The result of 'dataConUnivTyVars'
--
-- 2) The result of 'dataConExTyCoVars'
--
-- 3) The non-dependent GADT equalities.
-- Dependent GADT equalities are implied by coercion variables in
-- return value (2).
--
-- 4) The other constraints of the data constructor type, excluding GADT
-- equalities
--
-- 5) The original argument types to the 'DataCon' (i.e. before
-- any change of the representation of the type)
--
-- 6) The original result type of the 'DataCon'
dataConFullSig :: DataCon
-> ([TyVar], [TyCoVar], [EqSpec], ThetaType, [Type], Type)
dataConFullSig (MkData {dcUnivTyVars = univ_tvs, dcExTyCoVars = ex_tvs,
dcEqSpec = eq_spec, dcOtherTheta = theta,
dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
= (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, res_ty)
dataConOrigResTy :: DataCon -> Type
dataConOrigResTy dc = dcOrigResTy dc
-- | The \"stupid theta\" of the 'DataCon', such as @data Eq a@ in:
--
-- > data Eq a => T a = ...
dataConStupidTheta :: DataCon -> ThetaType
dataConStupidTheta dc = dcStupidTheta dc
dataConUserType :: DataCon -> Type
-- ^ The user-declared type of the data constructor
-- in the nice-to-read form:
--
-- > T :: forall a b. a -> b -> T [a]
--
-- rather than:
--
-- > T :: forall a c. forall b. (c~[a]) => a -> b -> T c
--
-- The type variables are quantified in the order that the user wrote them.
-- See @Note [DataCon user type variable binders]@.
--
-- NB: If the constructor is part of a data instance, the result type
-- mentions the family tycon, not the internal one.
dataConUserType (MkData { dcUserTyVarBinders = user_tvbs,
dcOtherTheta = theta, dcOrigArgTys = arg_tys,
dcOrigResTy = res_ty })
= mkForAllTys user_tvbs $
mkInvisFunTys theta $
mkVisFunTys arg_tys $
res_ty
-- | Finds the instantiated types of the arguments required to construct a
-- 'DataCon' representation
-- NB: these INCLUDE any dictionary args
-- but EXCLUDE the data-declaration context, which is discarded
-- It's all post-flattening etc; this is a representation type
dataConInstArgTys :: DataCon -- ^ A datacon with no existentials or equality constraints
-- However, it can have a dcTheta (notably it can be a
-- class dictionary, with superclasses)
-> [Type] -- ^ Instantiated at these types
-> [Type]
dataConInstArgTys dc@(MkData {dcUnivTyVars = univ_tvs,
dcExTyCoVars = ex_tvs}) inst_tys
= ASSERT2( univ_tvs `equalLength` inst_tys
, text "dataConInstArgTys" <+> ppr dc $$ ppr univ_tvs $$ ppr inst_tys)
ASSERT2( null ex_tvs, ppr dc )
map (substTyWith univ_tvs inst_tys) (dataConRepArgTys dc)
-- | Returns just the instantiated /value/ argument types of a 'DataCon',
-- (excluding dictionary args)
dataConInstOrigArgTys
:: DataCon -- Works for any DataCon
-> [Type] -- Includes existential tyvar args, but NOT
-- equality constraints or dicts
-> [Type]
-- For vanilla datacons, it's all quite straightforward
-- But for the call in MatchCon, we really do want just the value args
dataConInstOrigArgTys dc@(MkData {dcOrigArgTys = arg_tys,
dcUnivTyVars = univ_tvs,
dcExTyCoVars = ex_tvs}) inst_tys
= ASSERT2( tyvars `equalLength` inst_tys
, text "dataConInstOrigArgTys" <+> ppr dc $$ ppr tyvars $$ ppr inst_tys )
map (substTy subst) arg_tys
where
tyvars = univ_tvs ++ ex_tvs
subst = zipTCvSubst tyvars inst_tys
-- | Returns the argument types of the wrapper, excluding all dictionary arguments
-- and without substituting for any type variables
dataConOrigArgTys :: DataCon -> [Type]
dataConOrigArgTys dc = dcOrigArgTys dc
-- | Returns the arg types of the worker, including *all* non-dependent
-- evidence, after any flattening has been done and without substituting for
-- any type variables
dataConRepArgTys :: DataCon -> [Type]
dataConRepArgTys (MkData { dcRep = rep
, dcEqSpec = eq_spec
, dcOtherTheta = theta
, dcOrigArgTys = orig_arg_tys })
= case rep of
NoDataConRep -> ASSERT( null eq_spec ) theta ++ orig_arg_tys
DCR { dcr_arg_tys = arg_tys } -> arg_tys
-- | The string @package:module.name@ identifying a constructor, which is attached
-- to its info table and used by the GHCi debugger and the heap profiler
dataConIdentity :: DataCon -> ByteString
-- We want this string to be UTF-8, so we get the bytes directly from the FastStrings.
dataConIdentity dc = LBS.toStrict $ BSB.toLazyByteString $ mconcat
[ BSB.byteString $ bytesFS (unitIdFS (moduleUnitId mod))
, BSB.int8 $ fromIntegral (ord ':')
, BSB.byteString $ bytesFS (moduleNameFS (moduleName mod))
, BSB.int8 $ fromIntegral (ord '.')
, BSB.byteString $ bytesFS (occNameFS (nameOccName name))
]
where name = dataConName dc
mod = ASSERT( isExternalName name ) nameModule name
isTupleDataCon :: DataCon -> Bool
isTupleDataCon (MkData {dcRepTyCon = tc}) = isTupleTyCon tc
isUnboxedTupleCon :: DataCon -> Bool
isUnboxedTupleCon (MkData {dcRepTyCon = tc}) = isUnboxedTupleTyCon tc
isUnboxedSumCon :: DataCon -> Bool
isUnboxedSumCon (MkData {dcRepTyCon = tc}) = isUnboxedSumTyCon tc
-- | Vanilla 'DataCon's are those that are nice boring Haskell 98 constructors
isVanillaDataCon :: DataCon -> Bool
isVanillaDataCon dc = dcVanilla dc
-- | Should this DataCon be allowed in a type even without -XDataKinds?
-- Currently, only Lifted & Unlifted
specialPromotedDc :: DataCon -> Bool
specialPromotedDc = isKindTyCon . dataConTyCon
classDataCon :: Class -> DataCon
classDataCon clas = case tyConDataCons (classTyCon clas) of
(dict_constr:no_more) -> ASSERT( null no_more ) dict_constr
[] -> panic "classDataCon"
dataConCannotMatch :: [Type] -> DataCon -> Bool
-- Returns True iff the data con *definitely cannot* match a
-- scrutinee of type (T tys)
-- where T is the dcRepTyCon for the data con
dataConCannotMatch tys con
| null inst_theta = False -- Common
| all isTyVarTy tys = False -- Also common
| otherwise = typesCantMatch (concatMap predEqs inst_theta)
where
(_, inst_theta, _) = dataConInstSig con tys
-- TODO: could gather equalities from superclasses too
predEqs pred = case classifyPredType pred of
EqPred NomEq ty1 ty2 -> [(ty1, ty2)]
ClassPred eq args
| eq `hasKey` eqTyConKey
, [_, ty1, ty2] <- args -> [(ty1, ty2)]
| eq `hasKey` heqTyConKey
, [_, _, ty1, ty2] <- args -> [(ty1, ty2)]
_ -> []
-- | Were the type variables of the data con written in a different order
-- than the regular order (universal tyvars followed by existential tyvars)?
--
-- This is not a cheap test, so we minimize its use in GHC as much as possible.
-- Currently, its only call site in the GHC codebase is in 'mkDataConRep' in
-- "MkId", and so 'dataConUserTyVarsArePermuted' is only called at most once
-- during a data constructor's lifetime.
-- See Note [DataCon user type variable binders], as well as
-- Note [Data con wrappers and GADT syntax] for an explanation of what
-- mkDataConRep is doing with this function.
dataConUserTyVarsArePermuted :: DataCon -> Bool
dataConUserTyVarsArePermuted (MkData { dcUnivTyVars = univ_tvs
, dcExTyCoVars = ex_tvs, dcEqSpec = eq_spec
, dcUserTyVarBinders = user_tvbs }) =
(filterEqSpec eq_spec univ_tvs ++ ex_tvs) /= binderVars user_tvbs
{-
%************************************************************************
%* *
Promoting of data types to the kind level
* *
************************************************************************
-}
promoteDataCon :: DataCon -> TyCon
promoteDataCon (MkData { dcPromoted = tc }) = tc
{-
************************************************************************
* *
\subsection{Splitting products}
* *
************************************************************************
-}
-- | Extract the type constructor, type argument, data constructor and it's
-- /representation/ argument types from a type if it is a product type.
--
-- Precisely, we return @Just@ for any type that is all of:
--
-- * Concrete (i.e. constructors visible)
--
-- * Single-constructor
--
-- * Not existentially quantified
--
-- Whether the type is a @data@ type or a @newtype@
splitDataProductType_maybe
:: Type -- ^ A product type, perhaps
-> Maybe (TyCon, -- The type constructor
[Type], -- Type args of the tycon
DataCon, -- The data constructor
[Type]) -- Its /representation/ arg types
-- Rejecting existentials is conservative. Maybe some things
-- could be made to work with them, but I'm not going to sweat
-- it through till someone finds it's important.
splitDataProductType_maybe ty
| Just (tycon, ty_args) <- splitTyConApp_maybe ty
, Just con <- isDataProductTyCon_maybe tycon
= Just (tycon, ty_args, con, dataConInstArgTys con ty_args)
| otherwise
= Nothing
{-
************************************************************************
* *
Building an algebraic data type
* *
************************************************************************
buildAlgTyCon is here because it is called from TysWiredIn, which can
depend on this module, but not on BuildTyCl.
-}
buildAlgTyCon :: Name
-> [TyVar] -- ^ Kind variables and type variables
-> [Role]
-> Maybe CType
-> ThetaType -- ^ Stupid theta
-> AlgTyConRhs
-> Bool -- ^ True <=> was declared in GADT syntax
-> AlgTyConFlav
-> TyCon
buildAlgTyCon tc_name ktvs roles cType stupid_theta rhs
gadt_syn parent
= mkAlgTyCon tc_name binders liftedTypeKind roles cType stupid_theta
rhs parent gadt_syn
where
binders = mkTyConBindersPreferAnon ktvs emptyVarSet
buildSynTyCon :: Name -> [KnotTied TyConBinder] -> Kind -- ^ /result/ kind
-> [Role] -> KnotTied Type -> TyCon
buildSynTyCon name binders res_kind roles rhs
= mkSynonymTyCon name binders res_kind roles rhs is_tau is_fam_free
where
is_tau = isTauTy rhs
is_fam_free = isFamFreeTy rhs
| sdiehl/ghc | compiler/basicTypes/DataCon.hs | bsd-3-clause | 60,117 | 0 | 22 | 16,888 | 6,242 | 3,575 | 2,667 | 531 | 5 |
------------------------------------------------------------------------------
-- | Project Euler No. 7
--
-- 10001st prime number.
--
import Data.List (find)
import Data.Maybe (isNothing)
isqrt = ceiling . sqrt . fromIntegral
is_prime :: Int -> Bool
is_prime 2 = True
is_prime 3 = True
is_prime n = isNothing result
where
test_vals = [2,3] ++ [x | x <- [3,5..isqrt n], x `mod` 3 /= 0]
result = find (\x -> n `mod` x == 0) test_vals
primes = take 10001 [x | x <- [2..], is_prime x]
main :: IO ()
main = do
putStrLn (show (last primes))
| mazelife/project_euler | seven.hs | bsd-3-clause | 568 | 0 | 12 | 125 | 220 | 120 | 100 | 13 | 1 |
--
-- Circuit compiler for the Faerieplay hardware-assisted secure
-- computation project at Dartmouth College.
--
-- Copyright (C) 2003-2007, Alexander Iliev <sasho@cs.dartmouth.edu> and
-- Sean W. Smith <sws@cs.dartmouth.edu>
--
-- All rights reserved.
--
-- This code is released under a BSD license.
-- Please see LICENSE.txt for the full license and disclaimers.
--
module Faerieplay.GenHelper_SFDL where
import qualified Faerieplay.Intermediate as Im
-- do not need a helper for SFDL
genHelper :: String -> Im.Prog -> String
genHelper s p = ""
| ailiev/faerieplay-compiler | Faerieplay/GenHelper_SFDL.hs | bsd-3-clause | 561 | 0 | 7 | 94 | 52 | 36 | 16 | 4 | 1 |
{-|
Module : CSVdb.Base
Description : Implements basic CSV data types and core processing functionality
Copyright : (c) Nikos Karagiannidis, 2017
License : GPL-3
Maintainer : nkarag@gmail.com
Stability : experimental
Portability : POSIX
This offers functions for decoding a CSV file into an RTable and encoding an RTable into a CSV file.
After a CSV is decoded to an RTable, then all operations implemented on an RTable are applicable.
**** NOTE ****
Needs the following ghc option to compile from Cygwin (default is 100) :
stack build --ghc-options -fsimpl-tick-factor=200
-}
{-# LANGUAGE OverloadedStrings #-}
-- :set -XOverloadedStrings
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
module CSVdb.Base
(
CSV
,Row
,Column
,readCSV
,readCSVwithOptions
,readCSVFile
,writeCSV
,writeCSVFile
,printCSV
,printCSVFile
,copyCSV
,selectNrows
,csvToRTable
,rtableToCSV
-- export the following only for debugging purposes via GHCI
--,csv2rtable
--,rtable2csv
,csvHeaderFromRtable
,projectByIndex
,headCSV
,tailCSV
,CSVOptions(..)
,YesNo (..)
) where
{-- ,addColumn
,dropColumn
,updateColumn
,filterRows
,appendRow
,deleteRow
,joinCSV --}
--------------
--
-- NOTE:
-- issue command: stack list-dependencies
-- in order to see the exact versions of the packages the CSVdb depends on
--------------
import Debug.Trace
import Data.RTable
-- CSV-conduit
--import qualified Data.CSV.Conduit as CC -- http://hackage.haskell.org/package/csv-conduit , https://www.stackage.org/haddock/lts-6.27/csv-conduit-0.6.6/Data-CSV-Conduit.html
-- Cassava (CSV parsing Library)
-- https://github.com/hvr/cassava
-- https://www.stackbuilders.com/tutorials/haskell/csv-encoding-decoding/
-- https://www.stackage.org/lts-7.15/package/cassava-0.4.5.1
-- https://hackage.haskell.org/package/cassava-0.4.5.1/docs/Data-Csv.html
import qualified Data.Csv as CV
-- HashMap -- https://hackage.haskell.org/package/unordered-containers-0.2.7.2/docs/Data-HashMap-Strict.html
import qualified Data.HashMap.Strict as HM
-- Data.List
import Data.List (map)
-- ByteString
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString as BS
import Data.ByteString.Char8 (pack,unpack) -- as BSW --(pack)
import Prelude hiding (putStr)
import Data.ByteString.Lazy.Char8 (putStr)--as BLW
-- Text
import Data.Text as T
import Data.Text.Encoding (decodeUtf8, encodeUtf8, decodeUtf8', decodeUtf16LE)
-- Vector
import qualified Data.Vector as V
-- Data.Maybe
import Data.Maybe (fromJust)
-- Data.Serialize (Cereal package)
-- https://hackage.haskell.org/package/cereal
-- https://hackage.haskell.org/package/cereal-0.5.4.0/docs/Data-Serialize.html
-- http://stackoverflow.com/questions/2283119/how-to-convert-a-integer-to-a-bytestring-in-haskell
import Data.Serialize (decode, encode)
-- Typepable -- https://hackage.haskell.org/package/base-4.9.1.0/docs/Data-Typeable.html
-- http://stackoverflow.com/questions/6600380/what-is-haskells-data-typeable
-- http://alvinalexander.com/source-code/haskell/how-determine-type-object-haskell-program
import qualified Data.Typeable as TB --(typeOf, Typeable)
import Data.Either.Combinators (fromRight')
import Data.Char (ord)
import Text.Printf (printf)
{--
-- Example code from: https://github.com/hvr/cassava
{--
Sample CSV:
name,salary
John Doe,50000
Jane Doe,60000
--}
data Person = Person
{ name :: !String
, salary :: !Int
}
instance FromNamedRecord Person where
parseNamedRecord r = Person <$> r .: "name" <*> r .: "salary"
main :: IO ()
main = do
csvData <- BL.readFile "salaries.csv"
case decodeByName csvData of
Left err -> putStrLn err
Right (_, v) -> V.forM_ v $ \ p ->
putStrLn $ name p ++ " earns " ++ show (salary p) ++ " dollars"
--}
-- ##################################################
-- * Data Types
-- ##################################################
-- | Definition of a CSV file
-- Treating CSV data as opaque byte strings
-- (type Csv = Vector Record)
type CSV = V.Vector Row -- i.e., CV.Csv
-- | Definition of a CSV Row
-- Essentially a Row is just a Vector of ByteString
-- (type Record = Vector Field)
type Row = V.Vector Column -- i.e., CV.Record
-- | Definition of a CSV Record column
-- (type Field = ByteString)
type Column = CV.Field
-- This typeclass instance is required by CV.decodeByName
--instance CV.FromNamedRecord (V.Vector BS.ByteString)
-- ##################################################
-- * IO operations
-- ##################################################
-- | readCSVFile: reads a CSV file and returns a lazy bytestring
readCSVFile ::
FilePath -- ^ the CSV file
-> IO BL.ByteString -- ^ the output CSV
readCSVFile f = BL.readFile f
-- | readCSV: reads a CSV file and returns a CSV data type (Treating CSV data as opaque byte strings)
readCSV ::
FilePath -- ^ the CSV file
-> IO CSV -- ^ the output CSV type
readCSV f = do
csvData <- BL.readFile f
{- csvDataBS <- BL.readFile f
let
--decodeUtf8' :: ByteString -> Either UnicodeException Text
utf8text = case decodeUtf8' (BL.toStrict csvDataBS) of
Left exc -> error $ "Error in decodeUtf8' the whole ByteString from Data.ByteString.Lazy.readFile: " ++ (show exc)
Right t -> t
-- Note that I had to make sure to use encodeUtf8 on a literal of type Text rather than just using a ByteString literal directly to Cassava
-- because The IsString instance for ByteStrings, which is what's used to convert the literal to a ByteString, truncates each Unicode code point
-- see : https://stackoverflow.com/questions/26499831/parse-csv-tsv-file-in-haskell-unicode-characters
csvData = encodeUtf8 utf8text -- encodeUtf8 :: Text -> ByteString
-}
let
csvResult = -- fromRight' $ CV.decode CV.HasHeader csvData
case CV.decode CV.HasHeader csvData of
Left str -> error $ "Error in decoding CSV file " ++ f ++ ": " ++ str
Right res -> res
{--
case CV.decode CV.HasHeader csvData of --CV.decodeByName csvData of
Left err -> let errbs = encode (err::String) -- BL.pack err -- convert String to ByteString
record = V.singleton (errbs)
csv = V.singleton (record)
in csv
Right csv -> csv --Right (hdr, csv) -> csv
--}
return csvResult
data YesNo = Yes | No
data CSVOptions = CSVOptions {
delimiter :: Char
,hasHeader :: YesNo
}
-- | readCSVwithOptions: reads a CSV file based on input options (delimiter and header option) and returns a CSV data type (Treating CSV data as opaque byte strings)
readCSVwithOptions ::
CSVOptions
-> FilePath -- ^ the CSV file
-> IO CSV -- ^ the output CSV type
readCSVwithOptions opt f = do
csvData <- BL.readFile f
let csvoptions = CV.defaultDecodeOptions {
CV.decDelimiter = fromIntegral $ ord (delimiter opt)
}
csvResult = case CV.decodeWith csvoptions
(case (hasHeader opt) of
Yes -> CV.HasHeader
No -> CV.NoHeader)
csvData of
Left str -> error $ "Error in decoding CSV file " ++ f ++ ": " ++ str
Right res -> res
{- csvResult = fromRight' $
CV.decodeWith csvoptions
(case (hasHeader opt) of
Yes -> CV.HasHeader
No -> CV.NoHeader)
csvData
-}
return csvResult
-- | writeCSVFile: write a CSV (bytestring) to a newly created csv file
writeCSVFile ::
FilePath -- ^ the csv file to be created
-> BL.ByteString -- ^ input CSV
-> IO()
writeCSVFile f csv = BL.writeFile f csv
-- | writeCSV: write a CSV to a newly created csv file
writeCSV ::
FilePath -- ^ the csv file to be created
-> CSV -- ^ input CSV
-> IO()
writeCSV f csv = do
let csvBS = CV.encode (V.toList csv)
BL.writeFile f csvBS
-- | printCSVFile: print input CSV on screen
printCSVFile ::
BL.ByteString -- ^ input CSV to be printed on screen
-> IO()
printCSVFile csv = putStr csv
-- | printCSV: print input CSV on screen
printCSV ::
CSV -- ^ input CSV to be printed on screen
-> IO()
printCSV csv = do
-- convert each ByteString field to Text
{--let csvText = V.map (\r -> V.map (decodeUtf32LE) r) csv
let csvBS = CV.encode (V.toList csvText)--}
let csvBS = CV.encode (V.toList csv)
putStr csvBS
-- | copyCSV: copy input csv file to specified output csv file
copyCSV ::
FilePath -- ^ input csv file
->FilePath -- ^ output csv file
-> IO()
copyCSV fi fo = do
csv <- readCSV fi
writeCSV fo csv
-- ##################################################
-- * CSV to RTable integration
-- ##################################################
-- | csvToRTable: Creates an RTable from a CSV and a set of RTable Metadata.
-- The RTable metadata essentially defines the data type of each column so as to
-- call the appropriate data constructor of RDataType and turn the ByteString values of CSV to RDataTypes values of RTable
-- We assume that the order of the columns in the CSV is identical with the order of the columns in the RTable metadata
csvToRTable ::
RTableMData
-> CSV
-> RTable
csvToRTable m c =
V.map (row2RTuple m) c
where
row2RTuple :: RTableMData -> Row -> RTuple
row2RTuple md row =
let
-- create a list of ColumnInfo. The order of the list correpsonds to the fixed column order and it is identical to the CSV column order
listOfColInfo = toListColumnInfo (rtuplemdata md) --Prelude.map (snd) $ (rtuplemdata md) -- HM.toList (rtuplemdata md)
-- create a list of the form [(ColumnInfo, Column)]
listOfColInfoColumn = Prelude.zip listOfColInfo (V.toList row)
-- create a list of ColumnNames
listOfColNames = toListColumnName (rtuplemdata md) --Prelude.map (fst) $ (rtuplemdata md) --HM.toList (rtuplemdata md)
-- create a list of RDataTypes
listOfRDataTypes = Prelude.map (\(ci,co) -> column2RDataType ci co) $ listOfColInfoColumn
where
column2RDataType :: ColumnInfo -> Column -> RDataType
column2RDataType ci col =
if col == BS.empty
then -- this is an empty ByteString
Null
else
-- Data.ByteString.Char8.unpack :: ByteString -> [Char]
case (dtype ci) of
Integer -> RInt (val::Integer) -- (read (Data.ByteString.Char8.unpack col) :: Int) --((read $ show val) :: Int)
Varchar -> RText $ if False then trace ("Creating RText for column " ++ (name ci)) $ (val::T.Text) else (val::T.Text)
-- $ decodeUtf8 col else decodeUtf8 col -- decodeUtf8 :: ByteString -> Text
-- $ decodeUtf16LE col else decodeUtf16LE col -- decodeUtf16LE :: ByteString -> Text
Date fmt -> RDate { rdate = (val::T.Text) {-decodeUtf8 col-} , dtformat = fmt } -- (val::T.Text)
--getDateFormat (val::String)}
Timestamp fmt -> RTime $ createRTimeStamp fmt (Data.ByteString.Char8.unpack col) -- Data.ByteString.Char8.unpack :: ByteString -> [Char]
Double -> RDouble (val::Double) --(read (Data.ByteString.Char8.unpack col) :: Double) -- ((read $ show val) :: Double)
where
-- Use Data.Serialize for the decoding from ByteString to a known data type
-- decode :: Serialize a => ByteString -> Either String a
-- val = fromRight' (decode col)
{--
val = case decode col of
Left e -> e -- you should throw an exception here!
Right v -> v
--}
-- use Data.Csv parsing capabilities in order to turn a Column (i.e. a Field, i.e., a ByteString)
-- into a known data type.
-- For this reason we are going to use : CV.parseField :: Field -> Parser a
--val = fromRight' $ CV.runParser $ CV.parseField col
val = case CV.runParser $ CV.parseField col of
Left str -> error $ "Error in parsing column " ++ (name ci) ++ ":" ++ str
Right v -> v
{--
val = case CV.runParser $ CV.parseField col of
Left e -> e -- you should throw an exception here!
Right v -> v
--}
{--
getDateFormat :: String -> String
getDateFormat _ = "DD/MM/YYYY"-- parse and return date format
--}
in HM.fromList $ Prelude.zip listOfColNames listOfRDataTypes
-- | rtableToCSV : Retunrs a CSV from an RTable
-- The first line of the CSV will be the header line, taken from the RTable metadata.
-- Note that the driver for creating the output CSV file is the input RTableMData descrbing the columns and RDataTypes of each RTuple.
-- This means, that if the RTableMData include a subset of the actual columns of the input RTable, then no eror will occure and the
-- output CSV will include only this subset.
-- In the same token, if in the RTableMData there is a column name that is not present in the input RTable, then an error will occur.
rtableToCSV ::
RTableMData -- ^ input RTable metadata describing the RTable
-> RTable -- ^ input RTable
-> CSV -- ^ output CSV
rtableToCSV m t =
(createCSVHeader m) V.++ (V.map (rtuple2row m) t)
where
rtuple2row :: RTableMData -> RTuple -> Row
rtuple2row md rt =
-- check that the RTuple is not empty. Otherwise the HM.! operator will cause an exception
if not $ isRTupEmpty rt
then
let listOfColInfo = toListColumnInfo (rtuplemdata md) --Prelude.map (snd) $ (rtuplemdata md) --HM.toList (rtuplemdata md)
-- create a list of the form [(ColumnInfo, RDataType)]
-- Prelude.zip listOfColInfo (Prelude.map (snd) $ HM.toList rt) -- this code does NOT guarantee that HM.toList will return the same column order as [ColumnInfo]
listOfColInfoRDataType :: [ColumnInfo] -> RTuple -> [(ColumnInfo, RDataType)] -- this code does guarantees that RDataTypes will be in the same column order as [ColumnInfo], i.e., the correct RDataType for the correct column
listOfColInfoRDataType (ci:[]) rtup = [(ci, rtup HM.!(name ci))] -- rt HM.!(name ci) -> this returns the RDataType by column name
listOfColInfoRDataType (ci:colInfos) rtup = (ci, rtup HM.!(name ci)):listOfColInfoRDataType colInfos rtup
listOfColumns = Prelude.map (\(ci,rdt) -> rDataType2Column ci rdt) $ listOfColInfoRDataType listOfColInfo rt
where
rDataType2Column :: ColumnInfo -> RDataType -> Column
rDataType2Column _ rdt =
{--
-- encode :: Serialize a => a -> ByteString
case rdt of
RInt i -> encode i
RText t -> encodeUtf8 t -- encodeUtf8 :: Text -> ByteString
RDate {rdate = d, dtformat = f} -> encode d
RDouble db -> encode db
--}
-- toField :: a -> Field (from Data.Csv)
case rdt of
RInt i -> CV.toField i
RText t -> CV.toField t
RDate {rdate = d, dtformat = f} -> CV.toField d
RDouble db -> CV.toField ((printf "%.2f" db)::String)
RTime { rtime = RTimestampVal {year = y, month = m, day = d, hours24 = h, minutes = mi, seconds = s} } -> let timeText = (digitToText d) `mappend` T.pack "/" `mappend` (digitToText m) `mappend` T.pack "/" `mappend` (digitToText y) `mappend` T.pack " " `mappend` (digitToText h) `mappend` T.pack ":" `mappend` (digitToText mi) `mappend` T.pack ":" `mappend` (digitToText s)
-- T.pack . removeQuotes . T.unpack $ (showText d) `mappend` T.pack "/" `mappend` (showText m) `mappend` T.pack "/" `mappend` (showText y) `mappend` T.pack " " `mappend` (showText h) `mappend` T.pack ":" `mappend` (showText mi) `mappend` T.pack ":" `mappend` (showText s)
-- removeQuotes $ (show d) ++ "/" ++ (show m) ++ "/" ++ (show y) ++ " " ++ (show h) ++ ":" ++ (show mi) ++ ":" ++ (show s)
where digitToText :: Int -> T.Text
digitToText d =
if d > 9 then showText d
else "0" `mappend` (showText d)
showText :: Show a => a -> Text
showText = T.pack . show
-- removeQuotes ('"' : [] ) = ""
-- removeQuotes ('"' : xs ) = removeQuotes xs
-- removeQuotes ( x : xs ) = x:removeQuotes xs
-- removeQuotes _ = ""
--noQuotesText = fromJust $ T.stripSuffix "\"" (fromJust $ T.stripPrefix "\"" timeText)
in CV.toField timeText --noQuotesText
-- CV.toField $ (show d) ++ "/" ++ (show m) ++ "/" ++ (show y) ++ " " ++ (show h) ++ ":" ++ (show mi) ++ ":" ++ (show s)
Null -> CV.toField (""::T.Text)
in V.fromList $ listOfColumns
else V.empty::Row
createCSVHeader :: RTableMData -> CSV
createCSVHeader md =
let listOfColNames = toListColumnName (rtuplemdata md) --Prelude.map (fst) $ (rtuplemdata md) --HM.toList (rtuplemdata md)
listOfByteStrings = Prelude.map (\n -> CV.toField n) listOfColNames
headerRow = V.fromList listOfByteStrings
in V.singleton headerRow
-- In order to be able to decode a CSV bytestring into an RTuple,
-- we need to make Rtuple an instance of the FromNamedRecord typeclass and
-- implement the parseNamesRecord function. But this is not necessary, since there is already an instance for CV.FromNamedRecord (HM.HashMap a b), which is the same,
-- since an RTuple is a HashMap.
--
-- type RTuple = HM.HashMap ColumnName RDataType
-- type ColumnName = String
-- data RDataType =
-- RInt { rint :: Int }
-- | RChar { rchar :: Char }
-- | RText { rtext :: T.Text }
-- | RString {rstring :: [Char]}
-- | RDate {
-- rdate :: String
-- ,dtformat :: String -- ^ e.g., "DD/MM/YYYY"
-- }
-- | RDouble { rdouble :: Double }
-- | RFloat { rfloat :: Float }
-- | Null
-- deriving (Show, Eq)
--
--
-- parseNamedRecord :: NamedRecord -> Parser a
-- type NamedRecord = HashMap ByteString ByteString
--
-- Instance of class FromNamedRecord:
-- (Eq a, FromField a, FromField b, Hashable a) => FromNamedRecord (HashMap a b)
--
-- From this we understand that we need to make RDataType (which is "b" in HashMap a b) an instance of FormField ((CV.FromField RDataType)) by implementing parseField
-- where:
-- @
-- parseField :: Field -> Parser a
-- type Field = ByteString
-- @
{--instance CV.FromNamedRecord RTuple where
parseNamedRecord r = do
let listOfcolNames = map (fst) $ HM.toList r -- get the first element of each pair which is the name of the column (list of ByteStrings)
listOfParserValues = map (\c -> r CV..: c) listOfcolNames -- this retuns a list of the form [Parser RDataType]
listOfValues = map (\v -> right (CV.runParser v)) listOfParserValues -- this returns a list of the form [RDataType]
rtup = createRtuple $ zip listOfcolNames listOfValues
return rtup
--}
instance CV.FromField RDataType where
parseField dt = do
-- dt is a ByteString (i.e., a Field) representing some value that we have read from the CSV file (we dont know its type)
-- we need to construct an RDataType from this value and then wrap it into a Parser Monad and return it
--
-- ### Note: the following line does not work ###
-- 1. parse the input ByteString using Cassavas' parsing capabilities for known data types
-- val <- CV.parseField dt
-- 1. We dont know the type of dt. OK lets wrap it into a generic type, that of Data.Typeable.TypeRep
let valTypeRep = TB.typeOf dt
-- 2. wrap this value into a RDataType
let rdata = createRDataType valTypeRep --val
-- wrap the RDataType into a Parser Monad and return it
pure rdata
{--
-- #### NOTE ###
--
-- if the following does not work (val is always a String, then try to use Data.Serialize.decode instead in order to get the original value from a bytestring)
-- get the value inside the Parser Monad (FromField has instances from all common haskell data types)
let val = case CV.runParser (CV.parseField dt) of -- runParser :: Parser a -> Either String a
Left e -> e
Right v -> v
--}
-- Lets try to use Data.Serialize.decode to get the vlaue from the bytestring (decode :: Serialize a => ByteString -> Either String a)
{-- let val = case decode dt of
Left e -> e
Right v -> v
-- wrap this value into a RDataType
let rdata = createRDataType val
-- wrap the RDataType into a Parser Monad
pure rdata
--}
-- In order to encode an input RTable into a CSV bytestring
-- we need to make Rtuple an instance of the ToNamedRecord typeclass and
-- implement the toNamedRecord function.
-- Where:
-- @
-- toNamedRecord :: a -> NamedRecord
-- type NamedRecord = HashMap ByteString ByteString
--
-- namedRecord :: [(ByteString, ByteString)] -> NamedRecord
-- Construct a named record from a list of name-value ByteString pairs. Use .= to construct such a pair from a name and a value.
--
-- (.=) :: ToField a => ByteString -> a -> (ByteString, ByteString)
-- @
-- In our case, we dont need to do this because an RTuple is just a synonym for HM.HashMap ColumnName RDataType and the data type HashMap a b is
-- already an instance of ToNamedRecord.
--
-- Also we need to make RDataType an instance of ToField ((CV.ToField RDataType)) by implementing toField, so as to be able
-- to convert an RDataType into a ByteString
-- where:
-- @
-- toField :: a -> Field
-- type Field = ByteString
-- @
instance CV.ToField RDataType where
toField rdata = case rdata of
RInt i -> encode (i::Integer)
--RChar c -> encode (c::Char)
-- RText t -> encode (t::String)
RText t -> encodeUtf8 t -- encodeUtf8 :: Text -> ByteString
--RString s -> encode (s::String)
--RFloat f -> encode (f::Float)
RDouble d -> encode (d::Double)
Null -> encode (""::String)
RDate d f -> encodeUtf8 d -- encode (d::String)
{--instance CV.ToField RDataType where
toField rdata = case rdata of
(i::Int) -> encode (i::Int)
-- RText t -> encode (t::String)
(t::T.Text) -> encodeUtf8 t -- encodeUtf8 :: Text -> ByteString
(d::Double) -> encode (d::Double)
Null -> encode (""::String)
--}
-- | csv2rtable : turn a input CSV to an RTable.
-- The input CSV will be a ByteString. We assume that the first line is the CSV header,
-- including the Column Names. The RTable that will be created will have as column names the headers appearing
-- in the first line of the CSV.
-- Internally we use CV.decodeByName to achieve this decoding
-- where:
-- @
-- decodeByName
-- :: FromNamedRecord a
-- => ByteString
-- -> Either String (Header, Vector a)
-- @
-- Essentially, decodeByName will return a @Vector RTuples@
--
-- In order to be able to decode a CSV bytestring into an RTuple,
-- we need to make Rtuple an instance of the FromNamesRecrd typeclass and
-- implement the parseNamesRecord function. But this is not necessary, since there is already an instance for CV.FromNamedRecord (HM.HashMap a b), which is the same,
-- since an RTuple is a HashMap.
-- Also we need to make RDataType an instance of FormField ((CV.FromField RDataType)) by implementing parseField
-- where:
-- @
-- parseField :: Field -> Parser a
-- type Field = ByteString
-- @
-- See RTable module for these instance
csv2rtable ::
BL.ByteString -- ^ input CSV (we asume that this CSV has a header in the 1st line)
-> RTable -- ^ output RTable
csv2rtable csv =
case CV.decodeByName csv of
Left e -> emptyRTable
Right (h, v) -> v
-- | rtable2csv: encode an RTable into a CSV bytestring
-- The first line of the CSV will be the header, which compirses of the column names.
--
-- Internally we use CV.encodeByName to achieve this decoding
-- where:
-- @
-- encodeByName :: ToNamedRecord a => Header -> [a] -> ByteString
-- Efficiently serialize CSV records as a lazy ByteString. The header is written before any records and dictates the field order.
--
-- type Header = Vector Name
-- type Name = ByteString
-- @
--
-- In order to encode an input RTable into a CSV bytestring
-- we need to make Rtuple an instance of the ToNamedRecord typeclass and
-- implement the toNamedRecord function.
-- Where:
-- @
-- toNamedRecord :: a -> NamedRecord
-- type NamedRecord = HashMap ByteString ByteString
--
-- namedRecord :: [(ByteString, ByteString)] -> NamedRecord
-- Construct a named record from a list of name-value ByteString pairs. Use .= to construct such a pair from a name and a value.
--
-- (.=) :: ToField a => ByteString -> a -> (ByteString, ByteString)
-- @
-- In our case, we dont need to do this because an RTuple is just a synonym for HM.HashMap ColumnName RDataType and the data type HashMap a b is
-- already an instance of ToNamedRecord.
--
-- Also we need to make RDataType an instance of ToField ((CV.ToField RDataType)) by implementing toField, so as to be able
-- to convert an RDataType into a ByteString
-- where:
-- @
-- toField :: a -> Field
-- type Field = ByteString
-- @
-- See 'RTable' module for these instance
rtable2csv ::
RTable -- ^ input RTable
-> BL.ByteString -- ^ Output ByteString
rtable2csv rtab =
CV.encodeByName (csvHeaderFromRtable rtab) (V.toList rtab)
-- | csvHeaderFromRtable: creates a Header (as defined in Data.Csv) from an RTable
-- type Header = Vector Name
-- type Name = ByteString
csvHeaderFromRtable ::
RTable
-> CV.Header
csvHeaderFromRtable rtab =
let fstRTuple = V.head rtab -- just get any tuple, e.g., the 1st one
colList = HM.keys fstRTuple -- get a list of the columnNames ([ColumnName])
colListPacked = Prelude.map (encode) colList -- turn it into a list of ByteStrings ([ByteString])
header = V.fromList colListPacked
in header
-- ##################################################
-- * Vector oprtations on CSV
-- ##################################################
-- | O(1) First row
headCSV :: CSV -> Row
headCSV = V.head
-- | O(1) Yield all but the first row without copying. The CSV may not be empty.
tailCSV :: CSV -> CSV
tailCSV = V.tail
-- ##################################################
-- * DDL on CSV
-- ##################################################
-- ##################################################
-- * DML on CSV
-- ##################################################
-- ##################################################
-- * Filter, Join, Projection
-- ##################################################
-- | selectNrows: Returns the first N rows from a CSV file
selectNrows::
Int -- ^ Number of rows to select
-> BL.ByteString -- ^ Input csv
-> BL.ByteString -- ^ Output csv
selectNrows n csvi =
let rtabi = csv2rtable csvi
rtabo = restrictNrows n rtabi
in rtable2csv rtabo
-- | Column projection on an input CSV file where
-- desired columns are defined by position (index)
-- in the CSV.
projectByIndex ::
[Int] -- ^ input list of column indexes
-> CSV -- ^ input csv
-> CSV -- ^ output CSV
projectByIndex inds icsv =
V.foldr (prj) V.empty icsv
where
prj :: Row -> CSV -> CSV
prj row acc =
let
-- construct new row including only projected columns
newrow = V.fromList $ Data.List.map (\i -> row V.! i) inds
in -- add new row in result vector
V.snoc acc newrow
| nkarag/haskell-CSVDB | src/CSVdb/Base.hs | bsd-3-clause | 35,490 | 0 | 32 | 14,351 | 2,811 | 1,630 | 1,181 | 234 | 9 |
-- | This is the filesystem module.
module Util.FileSystem (
-- * Data and Type
FDInfo(..),
Order, Predicate,
-- * Functions
toFDInfo,
lookover,
lookoverP,
traverse,
traverseP,
isDirectory,
) where
import Control.Monad (forM)
import Control.Applicative ((<$>),(<*>))
import Control.Exception (SomeException, handle)
import System.Directory (searchable, getDirectoryContents, Permissions, getPermissions, getModificationTime)
import System.FilePath ((</>))
import System.IO (withFile, IOMode(..), hFileSize)
import Data.Time.Clock (UTCTime)
import Prelude hiding (traverse)
-- | Information of file or directory.
data FDInfo = FDInfo {
fdPath :: FilePath -- ^ Path of directory or file.
, fdPerms :: Maybe Permissions -- ^ Nothing if the file not existed.
, fdSize :: Maybe Integer -- ^ Nothing if the file not existed.
, fdModTime :: Maybe UTCTime -- ^ Nothing if the file not existed.
} deriving (Eq, Show)
type Order = [FDInfo] -> [FDInfo]
type Predicate = FDInfo -> Bool
instance Ord FDInfo where
compare x y
| isDirectory x && isDirectory y = compare (fdPath x) (fdPath y)
| not (isDirectory x) && isDirectory y = GT
| isDirectory x && not (isDirectory y) = LT
| otherwise = compare (fdPath x) (fdPath y)
-----------------------------------------------------------------------------------------------
-- Traversal functions
-----------------------------------------------------------------------------------------------
lookover :: Order -> FilePath -> IO [FDInfo]
lookover order path = do
xs <- items path
let paths = (path </>) <$> xs
fdInfos <- mapM toFDInfo paths
return $ order fdInfos
lookoverP :: Predicate -> Order -> FilePath -> IO [FDInfo]
lookoverP pred order fp = filter pred <$> lookover order fp
traverse :: Order -> FilePath -> IO [FDInfo]
traverse order path = do
xs <- items path
let paths = path : ((path </>) <$> xs)
fdInfos <- mapM toFDInfo paths
concat <$> forM (order fdInfos) (\info -> do
if isDirectory info && fdPath info /= path
then traverse order (fdPath info)
else return [info])
traverseP :: Predicate -> Order -> FilePath -> IO [FDInfo]
traverseP pred order fp = filter pred <$> traverse order fp
-----------------------------------------------------------------------------------------------
-- Utility
-----------------------------------------------------------------------------------------------
-- | returns all subitems of a directory except self (.) and parent (..)
items :: FilePath -> IO [String]
items path = filter (`notElem` [".", ".."]) <$> getDirectoryContents path
isDirectory :: Predicate
isDirectory = (maybe False searchable) . fdPerms
toFDInfo :: FilePath -> IO FDInfo
toFDInfo path = FDInfo path <$> maybeIO perms <*> maybeIO size <*> maybeIO modified
where
perms = getPermissions path
size = withFile path ReadMode hFileSize
modified = getModificationTime path
maybeIO :: IO a -> IO (Maybe a)
maybeIO act = handle handler (Just <$> act)
where
handler :: SomeException -> IO (Maybe a)
handler _ = return Nothing
| ocean0yohsuke/Scheme | src/Util/FileSystem.hs | bsd-3-clause | 3,245 | 0 | 16 | 704 | 903 | 479 | 424 | 63 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
module Text.HTML.KURE
( -- * Reading HTML
parseHTML,
-- * HTML Builders
element,
text,
attr,
zero,
-- * Primitive Traversal Combinators
htmlT, htmlC,
elementT, elementC,
textT, textC,
attrsT, attrsC,
attrT, attrC,
-- * Other Combinators and Observers
getAttr,
isTag,
getTag,
getAttrs,
getInner,
anyElementHTML,
unconcatHTML,
-- * Types and Classes
HTML,
Element,
Text,
Attrs,
Attr,
Syntax,
Context(..),
Node,
Html(..),
-- * KURE combinators synonyms specialized to our universe type 'Node'
injectT',
projectT',
extractT',
promoteT',
extractR',
promoteR'
)where
import Text.XML.HXT.Parser.HtmlParsec
import Text.XML.HXT.DOM.ShowXml
import Text.XML.HXT.DOM.TypeDefs
import Text.XML.HXT.DOM.XmlNode
-- import Data.Tree.NTree.TypeDefs
-- import Text.XML.HXT.Parser.XmlParsec hiding (element)
-- import Text.XML.HXT.Parser.XhtmlEntities
import Control.Arrow
import Data.Char
import Data.Monoid (Monoid(..))
import Control.Monad
#if __GLASGOW_HASKELL__ >= 800
import Data.Semigroup (Semigroup(..))
#endif
--import Language.KURE.Walker
import qualified Language.KURE as KURE
import Language.KURE hiding ()
-- | The Principal type in DSL. Use 'show' to get the String rendition of this type.
-- 'HTML' is concatenated using '<>', the 'Monoid' mappend.
newtype HTML = HTML XmlTrees
-- | HTML element with tag and attrs
newtype Element = Element XmlTree
-- | Text (may include escaped text internally)
newtype Text = Text XmlTrees -- precondition: XmlTrees is never []
-- | Attributes for a element
newtype Attrs = Attrs XmlTrees
-- | Single attribute
newtype Attr = Attr XmlTree
-- | XML/HTML syntax, like <? or <!, or our zero-width space 'zero'.
newtype Syntax = Syntax XmlTree
-- | Context contains all the containing elements
-- in an inside to outside order
newtype Context = Context [Element]
-- | Our universal node type. Only used during
-- generic tree walking and traversals.
data Node
= HTMLNode HTML
| ElementNode Element
| TextNode Text
| AttrsNode Attrs
| AttrNode Attr
| SyntaxNode Syntax
deriving Show
-----------------------------------------------------------------------------
instance Show HTML where
show (HTML html) = xshow html
instance Show Element where
show (Element html) = xshow [html]
instance Show Text where
show (Text html) = xshow html
instance Show Attrs where
show (Attrs html) = xshow html
instance Show Attr where
show (Attr html) = xshow [html]
instance Show Syntax where
show (Syntax syntax) = xshow [syntax]
#if __GLASGOW_HASKELL__ >= 800
instance Semigroup HTML where
(<>) = mappend
instance Semigroup Context where
(<>) = mappend
#endif
instance Monoid HTML where
mempty = HTML []
mappend (HTML xs) (HTML ys) = HTML $ xs ++ ys
instance Monoid Context where
mempty = Context []
mappend (Context xs) (Context ys) = Context $ xs ++ ys
-----------------------------------------------------------------------------
-- KURE specific instances
instance Injection HTML Node where
inject = HTMLNode
project u = do HTMLNode t <- return u
return t
instance Injection Element Node where
inject = ElementNode
project u = do ElementNode t <- return u
return t
instance Injection Text Node where
inject = TextNode
project u = do TextNode t <- return u
return t
instance Injection Attrs Node where
inject = AttrsNode
project u = do AttrsNode t <- return u
return t
instance Injection Attr Node where
inject = AttrNode
project u = do AttrNode t <- return u
return t
instance Injection Syntax Node where
inject = SyntaxNode
project u = do SyntaxNode t <- return u
return t
instance Walker Context Node where
allR :: forall m . MonadCatch m => Rewrite Context m Node -> Rewrite Context m Node
allR rr = prefixFailMsg "allR failed: " $
rewrite $ \ c -> \ case
HTMLNode o -> liftM HTMLNode $ KURE.applyT (htmlT (extractR rr >>> arr html)
(extractR rr >>> arr html)
(extractR rr >>> arr html) $ htmlC) c o
ElementNode o -> liftM ElementNode $ KURE.applyT (elementT (extractR rr) (extractR rr) $ elementC) c o
TextNode o -> liftM TextNode $ return o
AttrsNode o -> liftM AttrsNode $ KURE.applyT (attrsT (extractR rr) $ attrsC) c o
AttrNode o -> liftM AttrNode $ return o
SyntaxNode o -> liftM SyntaxNode $ return o -- never processed
class Html a where
html :: a -> HTML
instance Html Element where
html (Element b) = HTML [b]
instance Html Text where
html (Text b) = HTML b
instance Html Syntax where
html (Syntax b) = HTML [b]
-----------------------------------------------------------------------------
-- | 'htmlT' take arrows that operate over elements, texts, and syntax,
-- and returns a transformation over HTML.
htmlT :: (Monad m)
=> Transform Context m Element a -- used many times
-> Transform Context m Text a -- used many times
-> Transform Context m Syntax a -- used many times
-> ([a] -> x)
-> Transform Context m HTML x
htmlT tr1 tr2 tr3 k = transform $ \ c (HTML ts) -> liftM k $ flip mapM ts $ \ case
t@(NTree (XTag {}) _) -> applyT tr1 c (Element t)
t@(NTree (XText {}) _) -> applyT tr2 c (Text [t])
t@(NTree (XCharRef {}) _) -> applyT tr2 c (Text [t])
t@(NTree (XPi {}) _) -> applyT tr3 c (Syntax t)
t@(NTree (XDTD {}) _) -> applyT tr3 c (Syntax t)
t@(NTree (XCmt {}) _) -> applyT tr3 c (Syntax t)
t@(NTree (XError {}) _) -> applyT tr3 c (Syntax t)
t -> error $ "not XTag or XText: " ++ take 100 (show t)
-- | 'mconcat' over 'HTML'
htmlC :: [HTML] -> HTML
htmlC = mconcat
-- | 'elementT' take arrows that operate over attributes and (the inner) HTML,
-- and returns a transformation over a single element.
elementT :: (Monad m)
=> Transform Context m Attrs a
-> Transform Context m HTML b
-> (String -> a -> b -> x)
-> Transform Context m Element x
elementT tr1 tr2 k = transform $ \ (Context cs) (Element t) ->
case t of
NTree (XTag tag attrs) rest
| namePrefix tag == ""
&& namespaceUri tag == "" -> do
let nm = localPart tag
let c = Context (Element t : cs)
attrs' <- applyT tr1 c (Attrs attrs)
rest' <- applyT tr2 c (HTML rest)
return $ k nm attrs' rest'
_ -> fail "elementT runtime type error"
-- | 'elementC' builds a element from its components.
elementC :: String -> Attrs -> HTML -> Element
elementC nm (Attrs attrs) (HTML rest) = Element (NTree (XTag (mkName nm) attrs) rest)
-- | 'textT' takes a Text to bits. The string is fully unescaped (a regular Haskell string)
textT :: (Monad m)
=> (String -> x)
-> Transform Context m Text x
textT k = transform $ \ _ (Text txt) ->
return $ k $ unescapeText $ [ fn t | (NTree t _) <- txt ]
where
fn (XText xs) = Left xs
fn (XCharRef c) = Right c
fn _ = error "found non XText / XCharRef in Text"
-- | 'textC' constructs a Text from a fully unescaped string.
textC :: String -> Text
textC "" = Text [ NTree (XText "") [] ]
textC str = Text [ NTree t [] | t <- map (either XText XCharRef) $ escapeText str ]
-- | 'attrsT' promotes a transformation over 'Attr' into a transformation over 'Attrs'.
attrsT :: (Monad m)
=> Transform Context m Attr a
-> ([a] -> x)
-> Transform Context m Attrs x
attrsT tr k = transform $ \ c (Attrs ts) -> liftM k $ flip mapM ts $ \ case
t@(NTree (XAttr {}) _) -> applyT tr c (Attr t)
_ -> fail "not XTag or XText"
-- | join attributes together.
attrsC :: [Attr] -> Attrs
attrsC xs = Attrs [ x | Attr x <- xs ]
-- | promote a function over an attributes components into a transformation over 'Attr'.
attrT :: (Monad m)
=> (String -> String -> x)
-> Transform Context m Attr x
attrT k = transform $ \ c -> \ case
Attr (NTree (XAttr nm) ts)
| namePrefix nm == ""
&& namespaceUri nm == "" -> applyT (textT $ k (localPart nm)) c (Text ts)
_ -> fail "textT runtime error"
-- | Create a single attribute.
attrC :: String -> String -> Attr
attrC nm val = Attr $ mkAttr (mkName nm) ts
where Text ts = textC val
--------------------------------------------------
-- HTML Builders.
-- | 'element' is the main way of generates a element in HTML.
element :: String -> [Attr] -> HTML -> HTML
element nm xs inner = HTML [t]
where Element t = elementC nm (attrsC xs) inner
-- | 'text' creates a HTML node with text inside it.
text :: String -> HTML
text txt = HTML ts
where Text ts = textC txt
-- | 'zero' is an empty piece of HTML, which can be used to avoid
-- the use of the \<tag/\> form; for example "element \"br\" [] zero" will generate both an opener and closer.
-- 'zero' is the same as "text \"\"".
zero :: HTML
zero = text ""
----------------------------------------------------
-- Attr builder
-- | build a single Attr. Short version of 'attrC'.
attr :: String -> String -> Attr
attr = attrC
--------------------------------------------------
-- Element observers
-- | 'getAttr' gets the attributes of a specific attribute of a element.
getAttr :: (MonadCatch m) => String -> Transform Context m Element String
getAttr nm = getAttrs >>> attrsT find catchesM >>> joinT
where
find :: (MonadCatch m) => Transform Context m Attr (m String)
find = attrT $ \ nm' val -> if nm' == nm
then return val
else fail $ "getAttr: not" ++ show nm
-- | 'isTag' checks the element for a specific element name.
isTag :: (Monad m) => String -> Transform Context m Element ()
isTag nm = elementT idR idR (\ nm' _ _ -> nm == nm') >>> guardT
-- | 'getTag' gets the element name.
getTag :: (Monad m) => Transform Context m Element String
getTag = elementT idR idR (\ nm _ _ -> nm)
-- | 'getAttrs' gets the attributes inside a element.
getAttrs :: (Monad m) => Transform Context m Element Attrs
getAttrs = elementT idR idR (\ _ as _ -> as)
-- | 'getInner' gets the HTML inside a element.
getInner :: (Monad m) => Transform Context m Element HTML
getInner = elementT idR idR (\ _ _ h -> h)
--------------------------------------------------
-- common pattern; promote a transformation over a element to over
injectT' :: (Monad m, Injection a Node) => Transform c m a Node
injectT' = injectT
projectT' :: (Monad m, Injection a Node) => Transform c m Node a
projectT' = projectT
extractT' :: (Monad m, Injection a Node) => Transform c m Node b -> Transform c m a b
extractT' = extractT
promoteT' :: (Monad m, Injection a Node) => Transform c m a b -> Transform c m Node b
promoteT' = promoteT
extractR' :: (Monad m, Injection a Node) => Rewrite c m Node -> Rewrite c m a
extractR' = extractR
promoteR' :: (Monad m, Injection a Node) => Rewrite c m a -> Rewrite c m Node
promoteR' = promoteR
---------------------------------------
-- | Flatten into singleton HTMLs. The opposite of mconcat.
unconcatHTML :: HTML -> [HTML]
unconcatHTML (HTML ts) = map (\ t -> HTML [t]) ts
-- | lifts mapping of 'Element' to 'HTML' over a single level of 'HTML' sub-nodes.
-- 'anyElementHTML' has the property ''anyElementHTML (arr html) = idR''.
--
-- This is successful only if any of the sub-transformations are successful.
anyElementHTML :: (MonadCatch m) => Transform Context m Element HTML -> Rewrite Context m HTML
anyElementHTML tr = arr unconcatHTML >>> unwrapAnyR (mapT (wrapAnyR $ extractT' $ oneT $ promoteT' tr)) >>> arr mconcat
-- | parsing HTML files. If you want to unparse, use 'show'.
parseHTML :: FilePath -> String -> HTML
parseHTML fileName input = HTML $ parseHtmlDocument fileName input
---------------------------------------
escapeText :: String -> [Either String Int]
escapeText = foldr join [] . map f
where f n | n == '<' = Right (ord n)
| n == '"' = Right (ord n)
| n == '&' = Right (ord n)
| n == '\n' = Left n
| n == '\t' = Left n
| n == '\r' = Left n
| n > '~' = Right (ord n)
| n < ' ' = Right (ord n)
| otherwise = Left n
join (Left x) (Left xs :rest) = Left (x : xs) : rest
join (Left x) rest = Left [x] : rest
join (Right x) rest = Right x : rest
unescapeText :: [Either String Int] -> String
unescapeText = concatMap (either id ((: []) . chr))
| ku-fpg/html-kure | Text/HTML/KURE.hs | bsd-3-clause | 13,948 | 26 | 23 | 4,252 | 3,825 | 1,993 | 1,832 | 253 | 8 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Prelude hiding (map)
import qualified Data.Vector.Storable as V
import Language.C.Quote.CUDA
import qualified Language.C.Syntax as C
#if !MIN_VERSION_template_haskell(2,7,0)
import qualified Data.Loc
import qualified Data.Symbol
import qualified Language.C.Syntax
#endif /* !MIN_VERSION_template_haskell(2,7,0) */
import Data.Array.Nikola.Backend.CUDA
import Data.Array.Nikola.Backend.CUDA.CodeGen
main :: IO ()
main = withNewContext $ \_ -> do
test
test :: IO ()
test = do
print (g v)
where
g :: V.Vector Float -> V.Vector Float
g = compile f2
v :: V.Vector Float
v = V.fromList [0..31]
f :: Exp (V.Vector Float) -> Exp (V.Vector Float)
f = map inc
inc :: Exp Float -> Exp Float
inc = vapply $ \x -> x + 1
f2 :: CFun (Exp (V.Vector Float) -> Exp (V.Vector Float))
f2 = CFun { cfunName = "f2"
, cfunDefs = defs
, cfunAllocs = [vectorArgT FloatT (ParamIdx 0)]
, cfunExecConfig = ExecConfig { gridDimX = fromIntegral 240
, gridDimY = 1
, blockDimX = fromIntegral 128
, blockDimY = 1
, blockDimZ = 1
}
}
where
defs :: [C.Definition]
defs = [cunit|
__device__ float f0(float x2)
{
float v4;
v4 = x2 + 1.0F;
return v4;
}
extern "C" __global__ void f2(float* x0, int x0n, float* temp, int* tempn)
{
for (int i = (blockIdx.x + blockIdx.y * gridDim.x) * 128 + threadIdx.x; i <
x0n; i += 128 * 240) {
if (i < x0n) {
{
float temp0;
temp0 = f0(x0[i]);
temp[i] = temp0;
}
if (i == 0)
*tempn = x0n;
}
}
__syncthreads();
}
|]
| mainland/nikola | tests/Main.hs | bsd-3-clause | 2,001 | 0 | 11 | 712 | 401 | 232 | 169 | 39 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.