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
-- import System.Random -- -- data Coin = Heads | Tails deriving (Show, Enum, Bounded) -- -- instance Random Coin where -- randomR (a, b) g = -- case randomR (fromEnum a, fromEnum b) g of -- (x, g') -> (toEnum x, g') -- random g = randomR (minBound, maxBound) g -- -- main = do -- g <- newStdGen -- print . take 1 $ (randoms g :: [Coin]) import System.IO.Unsafe -- be careful! import System.Random data Dist = Dist Float Float mean :: Dist -> Float mean (Dist m sd) = m std :: Dist -> Float std (Dist m sd) = sd -- c :: Float -- c = unsafePerformIO (getStdRandom (randomR (90, 110))) / 100 -- x :: [IO Float] -- -- x = 10 : map (* (unsafePerformIO (getStdRandom (randomR (90, 110))) / 100)) x -- x = (getStdRandom (randomR (90, 110))) : x -- randList :: Int -> [[Float]] -- randList 0 = [] -- randList n = (randList (n-1)) : y -- where -- y = map (/ 100) (map unsafePerformIO x) -- where x = (getStdRandom (randomR (90, 110))) : x -- y1 :: [Float] -- y1 = map (/ 100) (map unsafePerformIO x1) -- where x1 = (getStdRandom (randomR (90, 110))) : x1 -- -- y2 :: [Float] -- y2 = map (/ 100) (map unsafePerformIO x2) -- where x2 = (getStdRandom (randomR (90, 110))) : x2 -- -- y3 :: [Float] -- y3 = map (/ 100) (map unsafePerformIO x3) -- where x3 = (getStdRandom (randomR (90, 110))) : x3 -- -- y4 :: [Float] -- y4 = map (/ 100) (map unsafePerformIO x4) -- where x4 = (getStdRandom (randomR (90, 110))) : x4 -- z :: [Float] -- z = map interestWalk :: Float -> [Float] -> [Float] interestWalk = walk where walk currentIr (x:xs) = (currentIr * x) : (walk (currentIr * x) xs) -- z1 = interestWalk 0.01 y1 -- -- z2 = interestWalk 0.01 y2 -- -- z3 = interestWalk 0.01 y3 -- -- z4 = interestWalk 0.01 y4 interestWalkAll :: Float -> Int -> [[Float]] interestWalkAll a = walkMore where walkMore 0 = [] walkMore n = (walkMore (n-1)) ++ [(interestWalk a (map (/ 100) (map unsafePerformIO x)))] where x = (getStdRandom (randomR (90, 110))) : x m = interestWalkAll 0.01 50 d = Dist 3.4 2.4 -- distMean :: [Float] -> [Float] -> [Float] -> [Float] -> Int -> Float -- distMean z1 z2 z3 z4 t = (sum l) / (fromIntegral (length l) :: Float) -- where l = (z1 !! t) : (z2 !! t) : (z3 !! t) : (z4 !! t) : [] -- x = distMean z1 z2 z3 z4 5 disc :: [[Float]] -> Float -> Int -> Int -> Float disc intr p k = discin where discin 0 = p discin n = (discin (n-1))*(1 + (intr!!k!!(n-1))) discSum :: [[Float]] -> Float -> Int -> Int -> Float discSum intr p 0 n = disc intr p 0 n discSum intr p k n = (discSum intr p (k-1) n) + (disc intr p k n) discMean :: [[Float]] -> Float -> Int -> Float discMean intr p n = (discSum intr p ((length intr)-1) n)/(fromIntegral (length intr)) discVarSum :: [[Float]] -> Float -> Int -> Int -> Float discVarSum intr p 0 n = 0 discVarSum intr p k n = (((disc intr p k n) - dmean) * ((disc intr p k n) - dmean)) + (discVarSum intr p (k-1) n) where dmean = discMean intr p n discVar :: [[Float]] -> Float -> Int -> Float discVar intr p n = (discVarSum intr p ((length intr)-1) n) / (fromIntegral ((length intr)-1)) discAll :: [[Float]] -> Float -> Int -> Dist discAll intr p n = Dist (discMean intr p n) (discVar intr p n) v = discAll m 100 4
vbalalla/financial_contract_language
Test.hs
mit
3,316
0
14
824
905
504
401
35
2
module Main where import Control.Applicative import Control.Monad import System.Environment import System.IO import Data.List import Language.BrainFuck.Compile import Language.BrainFuck.Parse import Language.BrainFuck.Interpret main = do (inHdl, outHdl) <- getHandles cProgram <- liftM (compile . parse) (hGetContents inHdl) hPutStr outHdl cProgram getHandles :: IO (Handle, Handle) getHandles = do args <- filter (isSuffixOf ".b") <$> getArgs case args of [] -> return (stdin, stdout) (x:xs) -> do inHdl <- openFile x ReadMode outHdl <- openFile (take (length x - 2) x ++ ".c") WriteMode return (inHdl, outHdl)
mgaut72/cbf
compiler/Main.hs
mit
658
0
19
129
232
121
111
22
2
import Control.Monad import Data.ByteString as BS (ByteString, pack, unpack) import Data.ByteString.Base16 as BS16 (encode) import Data.ByteString.Char8 as BSC8 (pack, unpack) import Data.ByteString.Lazy as BSL (pack, unpack, hPut) import Data.ByteString.Lazy.Char8 as BSLC8 (pack, unpack) import Data.ByteString.Base16.Lazy as BSL16 (encode) import Data.Digest.SHA256 as Digest (hash) import Data.Text.Lazy as T (pack) import Data.Text.Lazy.Encoding (encodeUtf8) import Data.Word (Word8) import System.Directory import System.Environment import System.FilePath import System.IO import System.Posix.Files import Text.Printf import Cabinet -- |Add an object whose content is the specified String to the store. The -- contents are encoded as UTF8. createStringObject :: Cabinet -> ObjectType -> String -> IO Object createStringObject c typ cnts = createObject c typ octets where octets = BSL.unpack $ encodeUtf8 $ T.pack cnts -- |Write an object header to a file handle writeHeader :: ObjectType -> Int -> Handle -> IO () writeHeader t s file = hPutStr file $ printf "%s %d" (describeType t) s -- |Add an object whose content is the specified list of octets to the store. createObject :: Cabinet -> ObjectType -> [Word8] -> IO Object createObject c typ cnts = do -- ensure that the directory containing the object files exists ensureObjectPaths object -- write the header withFile (header paths) WriteMode $ writeHeader typ len -- write the contents withFile (contents paths) WriteMode $ \h -> BSL.hPut h (BSL.pack cnts) -- return the object return object where digest = Digest.hash cnts -- digest octets name = BSC8.unpack $ BS16.encode $ BS.pack digest -- digest hex string len = length cnts -- length of contents object = Object c name paths = objectPaths object data Object = Object Cabinet String deriving (Show) data ObjectType = ObjectType String describeType :: ObjectType -> String describeType (ObjectType t) = t data ObjectPaths = ObjectPaths String String deriving (Show) header :: ObjectPaths -> String header (ObjectPaths _ p) = p contents :: ObjectPaths -> String contents (ObjectPaths p _) = p -- |Return the paths containing the contents and header for the specified object name objectPaths :: Object -> ObjectPaths objectPaths o = ObjectPaths (addExtension base "contents") (addExtension base "header") where (dir, file) = objectBase o base = joinPath [dir, file] -- |The directory containing the object's files and the remainder of the name objectBase :: Object -> (FilePath, String) objectBase (Object c n) = (joinPath [objectStore c, take 2 n], drop 2 n) -- Ensure the directory containing the object files exists ensureObjectDir :: Object -> IO () ensureObjectDir o = do exists <- doesDirectoryExist dir unless exists $ createDirectory dir where (dir, _) = objectBase o -- Like objectPaths but ensures that the directory containing the header and -- contents files exists. ensureObjectPaths :: Object -> IO ObjectPaths ensureObjectPaths o = ensureObjectDir o >> return (objectPaths o) main :: IO() main = do c <- ensureCabinetDir "hello" print c obj <- createStringObject c (ObjectType "blob") "ngsjngr" print $ objectPaths obj -- vim:sw=4:sts=4:et
rjw57/cloudsync
mksnapshot/mksnapshot.hs
mit
3,624
0
12
933
890
479
411
67
1
{- | Module : $Header$ Description : Maude Comorphisms Copyright : (c) Adrian Riesco, Facultad de Informatica UCM 2009 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : experimental Portability : portable Comorphism from Maude to CASL. -} module Maude.PreComorphism where import Data.Maybe import qualified Data.List as List import qualified Data.Set as Set import qualified Data.Map as Map import qualified Maude.Sign as MSign import qualified Maude.Sentence as MSentence import qualified Maude.Morphism as MMorphism import qualified Maude.AS_Maude as MAS import qualified Maude.Symbol as MSym import Maude.Meta.HasName import qualified CASL.Sign as CSign import qualified CASL.Morphism as CMorphism import qualified CASL.AS_Basic_CASL as CAS import CASL.StaticAna import Common.Id import Common.Result import Common.AS_Annotation import Common.ProofUtils (charMap) import qualified Common.Lib.Rel as Rel import qualified Common.Lib.MapSet as MapSet type IdMap = Map.Map Id Id type OpTransTuple = (CSign.OpMap, CSign.OpMap, Set.Set Component) -- | generates a CASL morphism from a Maude morphism mapMorphism :: MMorphism.Morphism -> Result CMorphism.CASLMor mapMorphism morph = let src = MMorphism.source morph tgt = MMorphism.target morph mk = kindMapId $ MSign.kindRel src mk' = kindMapId $ MSign.kindRel tgt smap = MMorphism.sortMap morph omap = MMorphism.opMap morph smap' = applySortMap2CASLSorts smap mk mk' omap' = maudeOpMap2CASLOpMap mk omap pmap = createPredMap mk smap (src', _) = maude2casl src [] (tgt', _) = maude2casl tgt [] in return $ CMorphism.Morphism src' tgt' smap' omap' pmap () {- | translates the Maude morphism between operators into a CASL morpshim between operators -} maudeOpMap2CASLOpMap :: IdMap -> MMorphism.OpMap -> CMorphism.Op_map maudeOpMap2CASLOpMap im = Map.foldWithKey (translateOpMapEntry im) Map.empty {- | translates the mapping between two symbols representing operators into a CASL operators map -} translateOpMapEntry :: IdMap -> MSym.Symbol -> MSym.Symbol -> CMorphism.Op_map -> CMorphism.Op_map translateOpMapEntry im (MSym.Operator from ar co) (MSym.Operator to _ _) copm = copm' where f = token2id . getName g x = Map.findWithDefault (errorId "translate op map entry") (f x) im ot = CSign.OpType CAS.Total (map g ar) (g co) cop = (token2id from, ot) to' = (token2id to, CAS.Total) copm' = Map.insert cop to' copm translateOpMapEntry _ _ _ _ = Map.empty -- | generates a set of CASL symbol from a Maude Symbol mapSymbol :: MSign.Sign -> MSym.Symbol -> Set.Set CSign.Symbol mapSymbol sg (MSym.Sort q) = Set.singleton csym where mk = kindMapId $ MSign.kindRel sg sym_id = token2id q kind = Map.findWithDefault (errorId "map symbol") sym_id mk pred_data = CSign.PredType [kind] csym = CSign.Symbol sym_id $ CSign.PredAsItemType pred_data mapSymbol sg (MSym.Operator q ar co) = Set.singleton csym where mk = kindMapId $ MSign.kindRel sg q' = token2id q ar' = map (maudeSort2caslId mk) ar co' = token2id $ getName co op_data = CSign.OpType CAS.Total ar' co' csym = CSign.Symbol q' $ CSign.OpAsItemType op_data mapSymbol _ _ = Set.empty -- | returns the sort in CASL of the Maude sort symbol maudeSort2caslId :: IdMap -> MSym.Symbol -> Id maudeSort2caslId im sym = Map.findWithDefault (errorId "sort to id") (token2id $ getName sym) im {- | creates the predicate map for the CASL morphism from the Maude sort map and the map between sorts and kinds -} createPredMap :: IdMap -> MMorphism.SortMap -> CMorphism.Pred_map createPredMap im = Map.foldWithKey (createPredMap4sort im) Map.empty -- | creates an entry of the predicate map for a single sort createPredMap4sort :: IdMap -> MSym.Symbol -> MSym.Symbol -> CMorphism.Pred_map -> CMorphism.Pred_map createPredMap4sort im from to = Map.insert key id_to where id_from = token2id $ getName from id_to = token2id $ getName to kind = Map.findWithDefault (errorId "predicate for sort") id_from im key = (id_from, CSign.PredType [kind]) {- | computes the sort morphism of CASL from the sort morphism in Maude and the set of kinds -} applySortMap2CASLSorts :: MMorphism.SortMap -> IdMap -> IdMap -> CMorphism.Sort_map applySortMap2CASLSorts sm im im' = Map.fromList sml' where sml = Map.toList sm sml' = foldr (applySortMap2CASLSort im im') [] sml -- | computes the morphism for a single sort pair applySortMap2CASLSort :: IdMap -> IdMap -> (MSym.Symbol, MSym.Symbol) -> [(Id, Id)] -> [(Id, Id)] applySortMap2CASLSort im im' (s1, s2) l = l' where p1 = (mSym2caslId s1, mSym2caslId s2) f x = Map.findWithDefault (errorId $ "err" ++ show (mSym2caslId x)) (mSym2caslId x) p2 = (f s1 im, f s2 im') l' = p1 : if s1 == s2 then l else p2 : l -- | renames the sorts in a given kind rename :: MMorphism.SortMap -> Token -> Token rename sm tok = new_tok where sym = MSym.Sort tok sym' = if Map.member sym sm then fromJust $ Map.lookup sym sm else sym new_tok = getName sym' -- | translates a Maude sentence into a CASL formula mapSentence :: MSign.Sign -> MSentence.Sentence -> Result CAS.CASLFORMULA mapSentence sg sen = let mk = kindMapId $ MSign.kindRel sg named = makeNamed "" sen form = mb_rl2formula mk named in return $ sentence $ case sen of MSentence.Equation (MAS.Eq _ _ _ ats) -> if any MAS.owise ats then let sg_sens = map (makeNamed "") $ Set.toList $ MSign.sentences sg (no_owise_sens, _, _) = splitOwiseEqs sg_sens no_owise_forms = map (noOwiseSen2Formula mk) no_owise_sens in owiseSen2Formula mk no_owise_forms named else noOwiseSen2Formula mk named MSentence.Membership (MAS.Mb {}) -> form MSentence.Rule (MAS.Rl {}) -> form {- | applies maude2casl to compute the CASL signature and sentences from the Maude ones, and wraps them into a Result datatype -} mapTheory :: (MSign.Sign, [Named MSentence.Sentence]) -> Result (CSign.CASLSign, [Named CAS.CASLFORMULA]) mapTheory (sg, nsens) = return $ maude2casl sg nsens {- | computes new signature and sentences of CASL associated to the given Maude signature and sentences -} maude2casl :: MSign.Sign -> [Named MSentence.Sentence] -> (CSign.CASLSign, [Named CAS.CASLFORMULA]) maude2casl msign nsens = (csign { CSign.sortRel = Rel.union (Rel.fromKeysSet cs) sbs', CSign.opMap = cops', CSign.assocOps = assoc_ops, CSign.predMap = preds, CSign.declaredSymbols = syms }, new_sens) where csign = CSign.emptySign () ss = MSign.sorts msign ss' = Set.map sym2id ss mk = kindMapId $ MSign.kindRel msign sbs = MSign.subsorts msign sbs' = maudeSbs2caslSbs sbs mk cs = Set.union ss' $ kindsFromMap mk preds = rewPredicates cs rs = rewPredicatesSens cs ops = deleteUniversal $ MSign.ops msign ksyms = kinds2syms cs (cops, assoc_ops, _) = translateOps mk ops -- (cops, assoc_ops, comps) axSens = axiomsSens mk ops ctor_sen = [] -- [ctorSen False (cs, Rel.empty, comps)] cops' = universalOps cs cops $ booleanImported ops rs' = rewPredicatesCongSens cops' pred_forms = loadLibraries (MSign.sorts msign) ops ops_syms = ops2symbols cops' (no_owise_sens, owise_sens, mbs_rls_sens) = splitOwiseEqs nsens no_owise_forms = map (noOwiseSen2Formula mk) no_owise_sens owise_forms = map (owiseSen2Formula mk no_owise_forms) owise_sens mb_rl_forms = map (mb_rl2formula mk) mbs_rls_sens preds_syms = preds2syms preds syms = Set.union ksyms $ Set.union ops_syms preds_syms new_sens = concat [rs, rs', no_owise_forms, owise_forms, mb_rl_forms, ctor_sen, pred_forms, axSens] {- | translates the Maude subsorts into CASL subsorts, and adds the subsorts for the kinds -} maudeSbs2caslSbs :: MSign.SubsortRel -> IdMap -> Rel.Rel CAS.SORT maudeSbs2caslSbs sbs im = Rel.fromMap m4 where l = Map.toList $ Rel.toMap sbs l1 = [] -- map maudeSb2caslSb l l2 = idList2Subsorts $ Map.toList im l3 = map subsorts2Ids l m1 = Map.fromList l1 m2 = Map.fromList l2 m3 = Map.fromList l3 m4 = Map.unionWith Set.union m1 $ Map.unionWith Set.union m2 m3 idList2Subsorts :: [(Id, Id)] -> [(Id, Set.Set Id)] idList2Subsorts [] = [] idList2Subsorts ((id1, id2) : il) = t1 : idList2Subsorts il where t1 = (id1, Set.singleton id2) maudeSb2caslSb :: (MSym.Symbol, Set.Set MSym.Symbol) -> (Id, Set.Set Id) maudeSb2caslSb (sym, st) = (sortSym2id sym, Set.map (kindId . sortSym2id) st) subsorts2Ids :: (MSym.Symbol, Set.Set MSym.Symbol) -> (Id, Set.Set Id) subsorts2Ids (sym, st) = (sortSym2id sym, Set.map sortSym2id st) sortSym2id :: MSym.Symbol -> Id sortSym2id (MSym.Sort q) = token2id q sortSym2id _ = token2id $ mkSimpleId "error_translation" -- | generates the sentences to state that the rew predicates are a congruence rewPredicatesCongSens :: CSign.OpMap -> [Named CAS.CASLFORMULA] rewPredicatesCongSens = MapSet.foldWithKey rewPredCong [] {- | generates the sentences to state that the rew predicates are a congruence for a single operator -} rewPredCong :: Id -> CSign.OpType -> [Named CAS.CASLFORMULA] -> [Named CAS.CASLFORMULA] rewPredCong op ot fs = case args of [] -> fs _ -> nq_form : fs where args = CSign.opArgs ot vars1 = rewPredCongPremise 0 args vars2 = rewPredCongPremise (length args) args res = CSign.opRes ot res_pred_type = CAS.Pred_type [res, res] nullRange pn = CAS.Qual_pred_name rewID res_pred_type nullRange name = "rew_cong_" ++ show op prems = rewPredsCong args vars1 vars2 prems_conj = createConjForm prems os = CAS.Qual_op_name op (CSign.toOP_TYPE ot) nullRange conc_term1 = CAS.Application os vars1 nullRange conc_term2 = CAS.Application os vars2 nullRange conc_form = CAS.Predication pn [conc_term1, conc_term2] nullRange form = createImpForm prems_conj conc_form nq_form = makeNamed name $ quantifyUniversally form -- | generates a list of variables of the given sorts rewPredCongPremise :: Int -> [CAS.SORT] -> [CAS.CASLTERM] rewPredCongPremise n (s : ss) = newVarIndex n s : rewPredCongPremise (n + 1) ss rewPredCongPremise _ [] = [] -- | generates a list of rew predicates with the given variables rewPredsCong :: [CAS.SORT] -> [CAS.CASLTERM] -> [CAS.CASLTERM] -> [CAS.CASLFORMULA] rewPredsCong (s : ss) (t : ts) (t' : ts') = form : forms where pred_type = CAS.Pred_type [s, s] nullRange pn = CAS.Qual_pred_name rewID pred_type nullRange form = CAS.Predication pn [t, t'] nullRange forms = rewPredsCong ss ts ts' rewPredsCong _ _ _ = [] -- | load the CASL libraries for the Maude built-in operators loadLibraries :: MSign.SortSet -> MSign.OpMap -> [Named CAS.CASLFORMULA] loadLibraries ss om = if natImported ss om then loadNaturalNatSens else [] -- | loads the sentences associated to the natural numbers loadNaturalNatSens :: [Named CAS.CASLFORMULA] loadNaturalNatSens = [] -- retrieve code from Rev 17944 if needed again! -- | checks if a sentence is an constructor sentence ctorCons :: Named CAS.CASLFORMULA -> Bool ctorCons f = case sentence f of CAS.Sort_gen_ax _ _ -> True _ -> False -- | checks if the boolean values are imported booleanImported :: MSign.OpMap -> Bool booleanImported = Map.member (mkSimpleId "if_then_else_fi") -- | checks if the natural numbers are imported natImported :: MSign.SortSet -> MSign.OpMap -> Bool natImported ss om = b1 && b2 && b3 where b1 = Set.member (MSym.Sort $ mkSimpleId "Nat") ss b2 = Map.member (mkSimpleId "s_") om b3 = not b2 || specialZeroSet (om Map.! mkSimpleId "s_") specialZeroSet :: MSign.OpDeclSet -> Bool specialZeroSet = Set.fold specialZero False specialZero :: MSign.OpDecl -> Bool -> Bool specialZero (_, ats) b = b' || b where b' = isSpecial ats isSpecial :: [MAS.Attr] -> Bool isSpecial [] = False isSpecial (MAS.Special _ : _) = True isSpecial (_ : ats) = isSpecial ats {- | delete the universal operators from Maude specifications, that will be substituted for one operator for each sort in the specification -} deleteUniversal :: MSign.OpMap -> MSign.OpMap deleteUniversal om = om5 where om1 = Map.delete (mkSimpleId "if_then_else_fi") om om2 = Map.delete (mkSimpleId "_==_") om1 om3 = Map.delete (mkSimpleId "_=/=_") om2 om4 = Map.delete (mkSimpleId "upTerm") om3 om5 = Map.delete (mkSimpleId "downTerm") om4 -- | generates the universal operators for all the sorts in the module universalOps :: Set.Set Id -> CSign.OpMap -> Bool -> CSign.OpMap universalOps kinds om True = Set.fold universalOpKind om kinds universalOps _ om False = om -- | generates the universal operators for a concrete module universalOpKind :: Id -> CSign.OpMap -> CSign.OpMap universalOpKind kind = MapSet.union $ MapSet.fromList [ (if_id, [if_opt]), (double_eq_id, [eq_opt]), (neg_double_eq_id, [eq_opt]) ] where if_id = str2id "if_then_else_fi" double_eq_id = str2id "_==_" neg_double_eq_id = str2id "_=/=_" bool_id = str2id "Bool" if_opt = CSign.OpType CAS.Total [bool_id, kind, kind] kind eq_opt = CSign.OpType CAS.Total [kind, kind] bool_id -- | generates the formulas for the universal operators universalSens :: Set.Set Id -> [Named CAS.CASLFORMULA] universalSens = Set.fold universalSensKind [] -- | generates the formulas for the universal operators for the given sort universalSensKind :: Id -> [Named CAS.CASLFORMULA] -> [Named CAS.CASLFORMULA] universalSensKind kind acc = concat [iss, eqs, neqs, acc] where iss = ifSens kind eqs = equalitySens kind neqs = nonEqualitySens kind -- | generates the formulas for the if statement ifSens :: Id -> [Named CAS.CASLFORMULA] ifSens kind = [form'', neg_form''] where v1 = newVarIndex 1 kind v2 = newVarIndex 2 kind bk = str2id "Bool" bv = newVarIndex 2 bk true_type = CAS.Op_type CAS.Total [] bk nullRange true_id = CAS.Qual_op_name (str2id "true") true_type nullRange true_term = CAS.Application true_id [] nullRange if_type = CAS.Op_type CAS.Total [bk, kind, kind] kind nullRange if_name = str2id "if_then_else_fi" if_id = CAS.Qual_op_name if_name if_type nullRange if_term = CAS.Application if_id [bv, v1, v2] nullRange prem = CAS.mkStEq bv true_term concl = CAS.mkStEq if_term v1 form = CAS.mkImpl prem concl form' = quantifyUniversally form neg_prem = CAS.Negation prem nullRange neg_concl = CAS.mkStEq if_term v2 neg_form = CAS.mkImpl neg_prem neg_concl neg_form' = quantifyUniversally neg_form name1 = show kind ++ "_if_true" name2 = show kind ++ "_if_false" form'' = makeNamed name1 form' neg_form'' = makeNamed name2 neg_form' -- | generates the formulas for the equality equalitySens :: Id -> [Named CAS.CASLFORMULA] equalitySens kind = [form'', comp_form''] where v1 = newVarIndex 1 kind v2 = newVarIndex 2 kind bk = str2id "Bool" b_type = CAS.Op_type CAS.Total [] bk nullRange true_id = CAS.Qual_op_name (str2id "true") b_type nullRange true_term = CAS.Application true_id [] nullRange false_id = CAS.Qual_op_name (str2id "false") b_type nullRange false_term = CAS.Application false_id [] nullRange prem = CAS.mkStEq v1 v2 double_eq_type = CAS.Op_type CAS.Total [kind, kind] kind nullRange double_eq_name = str2id "_==_" double_eq_id = CAS.mkQualOp double_eq_name double_eq_type double_eq_term = CAS.Application double_eq_id [v1, v2] nullRange concl = CAS.mkStEq double_eq_term true_term form = CAS.mkImpl prem concl form' = quantifyUniversally form neg_prem = CAS.Negation prem nullRange new_concl = CAS.mkStEq double_eq_term false_term comp_form = CAS.mkImpl neg_prem new_concl comp_form' = quantifyUniversally comp_form name1 = show kind ++ "_==_true" name2 = show kind ++ "_==_false" form'' = makeNamed name1 form' comp_form'' = makeNamed name2 comp_form' -- | generates the formulas for the inequality nonEqualitySens :: Id -> [Named CAS.CASLFORMULA] nonEqualitySens kind = [form'', comp_form''] where v1 = newVarIndex 1 kind v2 = newVarIndex 2 kind bk = str2id "Bool" b_type = CAS.Op_type CAS.Total [] bk nullRange true_id = CAS.Qual_op_name (str2id "true") b_type nullRange true_term = CAS.Application true_id [] nullRange false_id = CAS.Qual_op_name (str2id "false") b_type nullRange false_term = CAS.Application false_id [] nullRange prem = CAS.mkStEq v1 v2 double_eq_type = CAS.Op_type CAS.Total [kind, kind] kind nullRange double_eq_name = str2id "_==_" double_eq_id = CAS.mkQualOp double_eq_name double_eq_type double_eq_term = CAS.Application double_eq_id [v1, v2] nullRange concl = CAS.mkStEq double_eq_term false_term form = CAS.mkImpl prem concl form' = quantifyUniversally form neg_prem = CAS.Negation prem nullRange new_concl = CAS.mkStEq double_eq_term true_term comp_form = CAS.mkImpl neg_prem new_concl comp_form' = quantifyUniversally comp_form name1 = show kind ++ "_=/=_false" name2 = show kind ++ "_=/=_true" form'' = makeNamed name1 form' comp_form'' = makeNamed name2 comp_form' -- | generates the sentences for the operator attributes axiomsSens :: IdMap -> MSign.OpMap -> [Named CAS.CASLFORMULA] axiomsSens im = Map.fold (axiomsSensODS im) [] axiomsSensODS :: IdMap -> MSign.OpDeclSet -> [Named CAS.CASLFORMULA] -> [Named CAS.CASLFORMULA] axiomsSensODS im ods l = Set.fold (axiomsSensOD im) l ods axiomsSensOD :: IdMap -> MSign.OpDecl -> [Named CAS.CASLFORMULA] -> [Named CAS.CASLFORMULA] axiomsSensOD im (ss, ats) l = Set.fold (axiomsSensSS im ats) l ss axiomsSensSS :: IdMap -> [MAS.Attr] -> MSym.Symbol -> [Named CAS.CASLFORMULA] -> [Named CAS.CASLFORMULA] axiomsSensSS im ats (MSym.Operator q ar co) l = l ++ l1 where l1 = if elem MAS.Comm ats then commSen im q ar co else [] axiomsSensSS _ _ _ l = l commSen :: IdMap -> MAS.Qid -> MSym.Symbols -> MSym.Symbol -> [Named CAS.CASLFORMULA] commSen im q ar@[ar1, ar2] co = [form'] where q' = token2id q f = (`maudeSymbol2caslSort` im) ar1' = f ar1 ar2' = f ar2 ot = CAS.Op_type CAS.Total (map f ar) (f co) nullRange os = CAS.Qual_op_name q' ot nullRange v1 = newVarIndex 1 ar1' v2 = newVarIndex 2 ar2' t1 = CAS.Application os [v1, v2] nullRange t2 = CAS.Application os [v2, v1] nullRange form = CAS.mkStEq t1 t2 name = "comm_" ++ ms2vcs (show q') ++ "_" ++ show ar1' form' = makeNamed name $ quantifyUniversally form commSen _ _ _ _ = [] -- (newVarIndex 1 (hd ar)) -- maudeSymbol2caslSort x im {- | translates the Maude operator map into a tuple of CASL operators, CASL associative operators, membership induced from each Maude operator, and the set of sorts with the ctor attribute -} translateOps :: IdMap -> MSign.OpMap -> OpTransTuple translateOps im = Map.fold (translateOpDeclSet im) (MapSet.empty, MapSet.empty, Set.empty) -- | translates an operator declaration set into a tern as described above translateOpDeclSet :: IdMap -> MSign.OpDeclSet -> OpTransTuple -> OpTransTuple translateOpDeclSet im ods tpl = Set.fold (translateOpDecl im) tpl ods {- | given an operator declaration updates the accumulator with the translation to CASL operator, checking if the operator has the assoc attribute to insert it in the map of associative operators, generating the membership predicate induced by the operator declaration, and checking if it has the ctor attribute to introduce the operator in the generators sentence -} translateOpDecl :: IdMap -> MSign.OpDecl -> OpTransTuple -> OpTransTuple translateOpDecl im (syms, ats) (ops, assoc_ops, cs) = case tl of [] -> (ops', assoc_ops', cs') _ -> translateOpDecl im (syms', ats) (ops', assoc_ops', cs') where sym : tl = Set.toList syms syms' = Set.fromList tl (cop_id, ot, _) = fromJust $ maudeSym2CASLOp im sym ops' = MapSet.insert cop_id ot ops assoc_ops' = if any MAS.assoc ats then MapSet.insert cop_id ot assoc_ops else assoc_ops cs' = if any MAS.ctor ats then Set.insert (Component cop_id ot) cs else cs {- | translates a Maude operator symbol into a pair with the id of the operator and its CASL type -} maudeSym2CASLOp :: IdMap -> MSym.Symbol -> Maybe (Id, CSign.OpType, CSign.OpType) maudeSym2CASLOp im (MSym.Operator op ar co) = Just (token2id op, ot, ot') where f = token2id . getName g = (`maudeSymbol2caslSort` im) ot = CSign.OpType CAS.Total (map g ar) (g co) ot' = CSign.OpType CAS.Total (map f ar) (f co) maudeSym2CASLOp _ _ = Nothing -- | creates a conjuctive formula distinguishing the size of the list createConjForm :: [CAS.CASLFORMULA] -> CAS.CASLFORMULA createConjForm = CAS.conjunct -- | creates a implication formula distinguishing the size of the premises createImpForm :: CAS.CASLFORMULA -> CAS.CASLFORMULA -> CAS.CASLFORMULA createImpForm (CAS.Atom True _) form = form createImpForm form1 form2 = CAS.mkImpl form1 form2 {- | generates the predicates asserting the "true" sort of the operator if all the arguments have the correct sort -} ops2predPremises :: IdMap -> [MSym.Symbol] -> Int -> ([CAS.CASLTERM], [CAS.CASLFORMULA]) ops2predPremises im (MSym.Sort s : ss) i = (var : terms, form : forms) where s' = token2id s kind = Map.findWithDefault (errorId "mb of op as predicate") s' im pred_type = CAS.Pred_type [kind] nullRange pred_name = CAS.Qual_pred_name s' pred_type nullRange var = newVarIndex i kind form = CAS.Predication pred_name [var] nullRange (terms, forms) = ops2predPremises im ss (i + 1) ops2predPremises im (MSym.Kind k : ss) i = (var : terms, forms) where k' = token2id k kind = Map.findWithDefault (errorId "mb of op as predicate") k' im var = newVarIndex i kind (terms, forms) = ops2predPremises im ss (i + 1) ops2predPremises _ _ _ = ([], []) {- | traverses the Maude sentences, returning a pair of list of sentences. The first list in the pair are the equations without the attribute "owise", while the second one are the equations with this attribute -} splitOwiseEqs :: [Named MSentence.Sentence] -> ([Named MSentence.Sentence] , [Named MSentence.Sentence], [Named MSentence.Sentence]) splitOwiseEqs [] = ([], [], []) splitOwiseEqs (s : ss) = res where (no_owise_sens, owise_sens, mbs_rls) = splitOwiseEqs ss sen = sentence s res = case sen of MSentence.Equation (MAS.Eq _ _ _ ats) -> if any MAS.owise ats then (no_owise_sens, s : owise_sens, mbs_rls) else (s : no_owise_sens, owise_sens, mbs_rls) _ -> (no_owise_sens, owise_sens, s : mbs_rls) {- | translates a Maude equation defined without the "owise" attribute into a CASL formula -} noOwiseSen2Formula :: IdMap -> Named MSentence.Sentence -> Named CAS.CASLFORMULA noOwiseSen2Formula im s = s' where MSentence.Equation eq = sentence s sen' = noOwiseEq2Formula im eq s' = s { sentence = sen' } {- | translates a Maude equation defined with the "owise" attribute into a CASL formula -} owiseSen2Formula :: IdMap -> [Named CAS.CASLFORMULA] -> Named MSentence.Sentence -> Named CAS.CASLFORMULA owiseSen2Formula im owise_forms s = s' where MSentence.Equation eq = sentence s sen' = owiseEq2Formula im owise_forms eq s' = s { sentence = sen' } -- | translates a Maude membership or rule into a CASL formula mb_rl2formula :: IdMap -> Named MSentence.Sentence -> Named CAS.CASLFORMULA mb_rl2formula im s = case sen of MSentence.Membership mb -> let mb' = mb2formula im mb in s { sentence = mb' } MSentence.Rule rl -> let rl' = rl2formula im rl in s { sentence = rl' } _ -> makeNamed "" CAS.falseForm where sen = sentence s -- | generates a new variable qualified with the given number newVarIndex :: Int -> Id -> CAS.CASLTERM newVarIndex i sort = CAS.Qual_var var sort nullRange where var = mkSimpleId $ 'V' : show i -- | generates a new variable newVar :: Id -> CAS.CASLTERM newVar sort = CAS.Qual_var var sort nullRange where var = mkSimpleId "V" -- | Id for the rew predicate rewID :: Id rewID = token2id $ mkSimpleId "rew" {- | translates a Maude equation without the "owise" attribute into a CASL formula -} noOwiseEq2Formula :: IdMap -> MAS.Equation -> CAS.CASLFORMULA noOwiseEq2Formula im (MAS.Eq t t' [] _) = quantifyUniversally form where ct = maudeTerm2caslTerm im t ct' = maudeTerm2caslTerm im t' form = CAS.mkStEq ct ct' noOwiseEq2Formula im (MAS.Eq t t' conds@(_ : _) _) = quantifyUniversally form where ct = maudeTerm2caslTerm im t ct' = maudeTerm2caslTerm im t' conds_form = conds2formula im conds concl_form = CAS.mkStEq ct ct' form = createImpForm conds_form concl_form {- | transforms a Maude equation defined with the otherwise attribute into a CASL formula -} owiseEq2Formula :: IdMap -> [Named CAS.CASLFORMULA] -> MAS.Equation -> CAS.CASLFORMULA owiseEq2Formula im no_owise_form eq = form where (eq_form, vars) = noQuantification $ noOwiseEq2Formula im eq (op, ts, _) = fromJust $ getLeftApp eq_form ex_form = existencialNegationOtherEqs op ts no_owise_form imp_form = createImpForm ex_form eq_form form = CAS.mkForall vars imp_form -- | generates a conjunction of negation of existencial quantifiers existencialNegationOtherEqs :: CAS.OP_SYMB -> [CAS.CASLTERM] -> [Named CAS.CASLFORMULA] -> CAS.CASLFORMULA existencialNegationOtherEqs op ts forms = form where ex_forms = concatMap (existencialNegationOtherEq op ts) forms form = CAS.conjunct ex_forms {- | given a formula, if it refers to the same operator indicated by the parameters the predicate creates a list with the negation of the existence of variables that match the pattern described in the formula. In other case it returns an empty list -} existencialNegationOtherEq :: CAS.OP_SYMB -> [CAS.CASLTERM] -> Named CAS.CASLFORMULA -> [CAS.CASLFORMULA] existencialNegationOtherEq req_op terms form = if ok then let (_, ts, conds) = fromJust tpl ts' = qualifyExVarsTerms ts conds' = qualifyExVarsForms conds prems = createEqs ts' terms ++ conds' conj_form = CAS.conjunct prems ex_form = if null vars' then conj_form else CAS.mkExist vars' conj_form neg_form = CAS.mkNeg ex_form in [neg_form] else [] where (inner_form, vars) = noQuantification $ sentence form vars' = qualifyExVars vars tpl = getLeftApp inner_form ok = case tpl of Nothing -> False Just _ -> let (op, ts, _) = fromJust tpl in req_op == op && length terms == length ts {- | qualifies the variables in a list of formulas with the suffix "_ex" to distinguish them from the variables already bound -} qualifyExVarsForms :: [CAS.CASLFORMULA] -> [CAS.CASLFORMULA] qualifyExVarsForms = map qualifyExVarsForm {- | qualifies the variables in a formula with the suffix "_ex" to distinguish them from the variables already bound -} qualifyExVarsForm :: CAS.CASLFORMULA -> CAS.CASLFORMULA qualifyExVarsForm (CAS.Equation t CAS.Strong t' r) = CAS.Equation qt CAS.Strong qt' r where qt = qualifyExVarsTerm t qt' = qualifyExVarsTerm t' qualifyExVarsForm (CAS.Predication op ts r) = CAS.Predication op ts' r where ts' = qualifyExVarsTerms ts qualifyExVarsForm f = f {- | qualifies the variables in a list of terms with the suffix "_ex" to distinguish them from the variables already bound -} qualifyExVarsTerms :: [CAS.CASLTERM] -> [CAS.CASLTERM] qualifyExVarsTerms = map qualifyExVarsTerm {- | qualifies the variables in a term with the suffix "_ex" to distinguish them from the variables already bound -} qualifyExVarsTerm :: CAS.CASLTERM -> CAS.CASLTERM qualifyExVarsTerm (CAS.Qual_var var sort r) = CAS.Qual_var (qualifyExVarAux var) sort r qualifyExVarsTerm (CAS.Application op ts r) = CAS.Application op ts' r where ts' = map qualifyExVarsTerm ts qualifyExVarsTerm (CAS.Sorted_term t s r) = CAS.Sorted_term (qualifyExVarsTerm t) s r qualifyExVarsTerm (CAS.Cast t s r) = CAS.Cast (qualifyExVarsTerm t) s r qualifyExVarsTerm (CAS.Conditional t1 f t2 r) = CAS.Conditional t1' f t2' r where t1' = qualifyExVarsTerm t1 t2' = qualifyExVarsTerm t2 qualifyExVarsTerm (CAS.Mixfix_term ts) = CAS.Mixfix_term ts' where ts' = map qualifyExVarsTerm ts qualifyExVarsTerm (CAS.Mixfix_parenthesized ts r) = CAS.Mixfix_parenthesized ts' r where ts' = map qualifyExVarsTerm ts qualifyExVarsTerm (CAS.Mixfix_bracketed ts r) = CAS.Mixfix_bracketed ts' r where ts' = map qualifyExVarsTerm ts qualifyExVarsTerm (CAS.Mixfix_braced ts r) = CAS.Mixfix_braced ts' r where ts' = map qualifyExVarsTerm ts qualifyExVarsTerm t = t {- | qualifies a list of variables with the suffix "_ex" to distinguish them from the variables already bound -} qualifyExVars :: [CAS.VAR_DECL] -> [CAS.VAR_DECL] qualifyExVars = map qualifyExVar {- | qualifies a variable with the suffix "_ex" to distinguish it from the variables already bound -} qualifyExVar :: CAS.VAR_DECL -> CAS.VAR_DECL qualifyExVar (CAS.Var_decl vars s r) = CAS.Var_decl vars' s r where vars' = map qualifyExVarAux vars -- | qualifies a token with the suffix "_ex" qualifyExVarAux :: Token -> Token qualifyExVarAux var = mkSimpleId $ show var ++ "_ex" -- | creates a list of strong equalities from two lists of terms createEqs :: [CAS.CASLTERM] -> [CAS.CASLTERM] -> [CAS.CASLFORMULA] createEqs (t1 : ts1) (t2 : ts2) = CAS.mkStEq t1 t2 : ls where ls = createEqs ts1 ts2 createEqs _ _ = [] {- | extracts the operator at the top and the arguments of the lefthand side in a strong equation -} getLeftApp :: CAS.CASLFORMULA -> Maybe (CAS.OP_SYMB, [CAS.CASLTERM], [CAS.CASLFORMULA]) getLeftApp (CAS.Equation term CAS.Strong _ _) = case getLeftAppTerm term of Nothing -> Nothing Just (op, ts) -> Just (op, ts, []) getLeftApp (CAS.Relation prem c concl _) = case getLeftApp concl of Just (op, ts, _) | c /= CAS.Equivalence -> Just (op, ts, conds) where conds = getPremisesImplication prem _ -> Nothing getLeftApp _ = Nothing {- | extracts the operator at the top and the arguments of the lefthand side in an application term -} getLeftAppTerm :: CAS.CASLTERM -> Maybe (CAS.OP_SYMB, [CAS.CASLTERM]) getLeftAppTerm (CAS.Application op ts _) = Just (op, ts) getLeftAppTerm _ = Nothing {- | extracts the formulas of the given premise, distinguishing whether it is a conjunction or not -} getPremisesImplication :: CAS.CASLFORMULA -> [CAS.CASLFORMULA] getPremisesImplication (CAS.Junction CAS.Con forms _) = concatMap getPremisesImplication forms getPremisesImplication form = [form] -- | translate a Maude membership into a CASL formula mb2formula :: IdMap -> MAS.Membership -> CAS.CASLFORMULA mb2formula im (MAS.Mb t s [] _) = quantifyUniversally form where ct = maudeTerm2caslTerm im t s' = token2id $ getName s form = CAS.Membership ct s' nullRange mb2formula im (MAS.Mb t s conds@(_ : _) _) = quantifyUniversally form where ct = maudeTerm2caslTerm im t s' = token2id $ getName s conds_form = conds2formula im conds concl_form = CAS.Membership ct s' nullRange form = CAS.mkImpl conds_form concl_form -- | translate a Maude rule into a CASL formula rl2formula :: IdMap -> MAS.Rule -> CAS.CASLFORMULA rl2formula im (MAS.Rl t t' [] _) = quantifyUniversally form where ty = token2id $ getName $ MAS.getTermType t kind = Map.findWithDefault (errorId "rl to formula") ty im pred_type = CAS.Pred_type [kind, kind] nullRange pred_name = CAS.Qual_pred_name rewID pred_type nullRange ct = maudeTerm2caslTerm im t ct' = maudeTerm2caslTerm im t' form = CAS.Predication pred_name [ct, ct'] nullRange rl2formula im (MAS.Rl t t' conds@(_ : _) _) = quantifyUniversally form where ty = token2id $ getName $ MAS.getTermType t kind = Map.findWithDefault (errorId "rl to formula") ty im pred_type = CAS.Pred_type [kind, kind] nullRange pred_name = CAS.Qual_pred_name rewID pred_type nullRange ct = maudeTerm2caslTerm im t ct' = maudeTerm2caslTerm im t' conds_form = conds2formula im conds concl_form = CAS.Predication pred_name [ct, ct'] nullRange form = CAS.mkImpl conds_form concl_form -- | translate a conjunction of Maude conditions to a CASL formula conds2formula :: IdMap -> [MAS.Condition] -> CAS.CASLFORMULA conds2formula im conds = CAS.conjunct forms where forms = map (cond2formula im) conds -- | translate a single Maude condition to a CASL formula cond2formula :: IdMap -> MAS.Condition -> CAS.CASLFORMULA cond2formula im (MAS.EqCond t t') = CAS.mkStEq ct ct' where ct = maudeTerm2caslTerm im t ct' = maudeTerm2caslTerm im t' cond2formula im (MAS.MatchCond t t') = CAS.mkStEq ct ct' where ct = maudeTerm2caslTerm im t ct' = maudeTerm2caslTerm im t' cond2formula im (MAS.MbCond t s) = CAS.Membership ct s' nullRange where ct = maudeTerm2caslTerm im t s' = token2id $ getName s cond2formula im (MAS.RwCond t t') = CAS.mkPredication pred_name [ct, ct'] where ct = maudeTerm2caslTerm im t ct' = maudeTerm2caslTerm im t' ty = token2id $ getName $ MAS.getTermType t kind = Map.findWithDefault (errorId "rw cond to formula") ty im pred_type = CAS.Pred_type [kind, kind] nullRange pred_name = CAS.Qual_pred_name rewID pred_type nullRange -- | translates a Maude term into a CASL term maudeTerm2caslTerm :: IdMap -> MAS.Term -> CAS.CASLTERM maudeTerm2caslTerm im (MAS.Var q ty) = CAS.Qual_var q ty' nullRange where ty' = maudeType2caslSort ty im maudeTerm2caslTerm im (MAS.Const q ty) = CAS.Application op [] nullRange where name = token2id q ty' = maudeType2caslSort ty im op_type = CAS.Op_type CAS.Total [] ty' nullRange op = CAS.Qual_op_name name op_type nullRange maudeTerm2caslTerm im (MAS.Apply q ts ty) = CAS.Application op tts nullRange where name = token2id q tts = map (maudeTerm2caslTerm im) ts ty' = maudeType2caslSort ty im types_tts = getTypes tts op_type = CAS.Op_type CAS.Total types_tts ty' nullRange op = CAS.Qual_op_name name op_type nullRange maudeSymbol2caslSort :: MSym.Symbol -> IdMap -> CAS.SORT maudeSymbol2caslSort (MSym.Sort q) _ = token2id q maudeSymbol2caslSort (MSym.Kind q) im = Map.findWithDefault err q' im where q' = token2id q err = errorId "error translate symbol" maudeSymbol2caslSort _ _ = errorId "error translate symbol" maudeType2caslSort :: MAS.Type -> IdMap -> CAS.SORT maudeType2caslSort (MAS.TypeSort q) _ = token2id $ getName q maudeType2caslSort (MAS.TypeKind q) im = Map.findWithDefault err q' im where q' = token2id $ getName q err = errorId "error translate type" -- | obtains the types of the given terms getTypes :: [CAS.CASLTERM] -> [Id] getTypes = mapMaybe getType -- | extracts the type of the temr getType :: CAS.CASLTERM -> Maybe Id getType (CAS.Qual_var _ kind _) = Just kind getType (CAS.Application op _ _) = case op of CAS.Qual_op_name _ (CAS.Op_type _ _ kind _) _ -> Just kind _ -> Nothing getType _ = Nothing -- | generates the formulas for the rewrite predicates rewPredicatesSens :: Set.Set Id -> [Named CAS.CASLFORMULA] rewPredicatesSens = Set.fold rewPredicateSens [] -- | generates the formulas for the rewrite predicate of the given sort rewPredicateSens :: Id -> [Named CAS.CASLFORMULA] -> [Named CAS.CASLFORMULA] rewPredicateSens kind acc = ref : trans : acc where ref = reflSen kind trans = transSen kind -- | creates the reflexivity predicate for the given kind reflSen :: Id -> Named CAS.CASLFORMULA reflSen kind = makeNamed name $ quantifyUniversally form where v = newVar kind pred_type = CAS.Pred_type [kind, kind] nullRange pn = CAS.Qual_pred_name rewID pred_type nullRange form = CAS.Predication pn [v, v] nullRange name = "rew_refl_" ++ show kind -- | creates the transitivity predicate for the given kind transSen :: Id -> Named CAS.CASLFORMULA transSen kind = makeNamed name $ quantifyUniversally form where v1 = newVarIndex 1 kind v2 = newVarIndex 2 kind v3 = newVarIndex 3 kind pred_type = CAS.Pred_type [kind, kind] nullRange pn = CAS.Qual_pred_name rewID pred_type nullRange prem1 = CAS.Predication pn [v1, v2] nullRange prem2 = CAS.Predication pn [v2, v3] nullRange concl = CAS.Predication pn [v1, v3] nullRange conj_form = CAS.conjunct [prem1, prem2] form = CAS.mkImpl conj_form concl name = "rew_trans_" ++ show kind -- | generate the predicates for the rewrites rewPredicates :: Set.Set Id -> CSign.PredMap rewPredicates = Set.fold rewPredicate MapSet.empty -- | generate the predicates for the rewrites of the given sort rewPredicate :: Id -> CSign.PredMap -> CSign.PredMap rewPredicate kind = MapSet.insert rewID $ CSign.PredType [kind, kind] -- | create the predicates that assign sorts to each term kindPredicates :: IdMap -> Map.Map Id (Set.Set CSign.PredType) kindPredicates = Map.foldWithKey kindPredicate Map.empty {- | create the predicates that assign the current sort to the corresponding terms -} kindPredicate :: Id -> Id -> Map.Map Id (Set.Set CSign.PredType) -> Map.Map Id (Set.Set CSign.PredType) kindPredicate sort kind mis = if sort == str2id "Universal" then mis else let ar = Set.singleton $ CSign.PredType [kind] in Map.insertWith Set.union sort ar mis -- | extract the kinds from the map of id's kindsFromMap :: IdMap -> Set.Set Id kindsFromMap = Map.fold Set.insert Set.empty {- | transform the set of Maude sorts in a set of CASL sorts, including only one sort for each kind. -} sortsTranslation :: MSign.SortSet -> MSign.SubsortRel -> Set.Set Id sortsTranslation = sortsTranslationList . Set.toList {- | transform a list representing the Maude sorts in a set of CASL sorts, including only one sort for each kind. -} sortsTranslationList :: [MSym.Symbol] -> MSign.SubsortRel -> Set.Set Id sortsTranslationList [] _ = Set.empty sortsTranslationList (s : ss) r = Set.insert (sort2id tops) res where tops@(top : _) = List.sort $ getTop r s ss' = deleteRelated ss top r res = sortsTranslation ss' r -- | return the maximal elements from the sort relation getTop :: MSign.SubsortRel -> MSym.Symbol -> [MSym.Symbol] getTop r tok = case succs of [] -> [tok] toks@(_ : _) -> concatMap (getTop r) toks where succs = Set.toList $ Rel.succs r tok -- | delete from the list of sorts those in the same kind that the parameter deleteRelated :: [MSym.Symbol] -> MSym.Symbol -> MSign.SubsortRel -> MSign.SortSet deleteRelated ss sym r = foldr (f sym tc) Set.empty ss where tc = Rel.transClosure r f sort trC x y = if MSym.sameKind trC sort x then y else Set.insert x y -- | build an Id from a token with the function mkId token2id :: Token -> Id token2id t = mkId ts where ts = maudeSymbol2validCASLSymbol t -- | build an Id from a Maude symbol sym2id :: MSym.Symbol -> Id sym2id = token2id . getName -- | generates an Id from a string str2id :: String -> Id str2id = token2id . mkSimpleId -- | build an Id from a list of sorts, taking the first from the ordered list sort2id :: [MSym.Symbol] -> Id sort2id syms = mkId sym'' where sym : _ = List.sort syms sym' = getName sym sym'' = maudeSymbol2validCASLSymbol sym' -- | add universal quantification of all variables in the formula quantifyUniversally :: CAS.CASLFORMULA -> CAS.CASLFORMULA quantifyUniversally form = CAS.mkForall var_decl form where vars = getVars form var_decl = listVarDecl vars {- | traverses a map with sorts as keys and sets of variables as value and creates a list of variable declarations -} listVarDecl :: Map.Map Id (Set.Set Token) -> [CAS.VAR_DECL] listVarDecl = Map.foldWithKey f [] where f sort var_set = (CAS.Var_decl (Set.toList var_set) sort nullRange :) -- | removes a quantification from a formula noQuantification :: CAS.CASLFORMULA -> (CAS.CASLFORMULA, [CAS.VAR_DECL]) noQuantification (CAS.Quantification _ vars form _) = (form, vars) noQuantification form = (form, []) -- | translate the CASL sorts to symbols kinds2syms :: Set.Set Id -> Set.Set CSign.Symbol kinds2syms = Set.map kind2sym -- | translate a CASL sort to a CASL symbol kind2sym :: Id -> CSign.Symbol kind2sym k = CSign.Symbol k CSign.SortAsItemType -- | translates the CASL predicates into CASL symbols preds2syms :: CSign.PredMap -> Set.Set CSign.Symbol preds2syms = MapSet.foldWithKey createSym4id Set.empty -- | creates a CASL symbol for a predicate createSym4id :: Id -> CSign.PredType -> Set.Set CSign.Symbol -> Set.Set CSign.Symbol createSym4id pn pt = Set.insert sym where sym = CSign.Symbol pn $ CSign.PredAsItemType pt -- | translates the CASL operators into CASL symbols ops2symbols :: CSign.OpMap -> Set.Set CSign.Symbol ops2symbols = MapSet.foldWithKey createSymOp4id Set.empty -- | creates a CASL symbol for an operator createSymOp4id :: Id -> CSign.OpType -> Set.Set CSign.Symbol -> Set.Set CSign.Symbol createSymOp4id on ot = Set.insert sym where sym = CSign.Symbol on $ CSign.OpAsItemType ot {- | extract the variables from a CASL formula and put them in a map with keys the sort of the variables and value the set of variables in this sort -} getVars :: CAS.CASLFORMULA -> Map.Map Id (Set.Set Token) getVars (CAS.Quantification _ _ f _) = getVars f getVars (CAS.Junction _ fs _) = foldr (Map.unionWith Set.union . getVars) Map.empty fs getVars (CAS.Relation f1 _ f2 _) = Map.unionWith Set.union v1 v2 where v1 = getVars f1 v2 = getVars f2 getVars (CAS.Negation f _) = getVars f getVars (CAS.Predication _ ts _) = foldr (Map.unionWith Set.union . getVarsTerm) Map.empty ts getVars (CAS.Definedness t _) = getVarsTerm t getVars (CAS.Equation t1 _ t2 _) = Map.unionWith Set.union v1 v2 where v1 = getVarsTerm t1 v2 = getVarsTerm t2 getVars (CAS.Membership t _ _) = getVarsTerm t getVars (CAS.Mixfix_formula t) = getVarsTerm t getVars _ = Map.empty -- | extract the variables of a CASL term getVarsTerm :: CAS.CASLTERM -> Map.Map Id (Set.Set Token) getVarsTerm (CAS.Qual_var var sort _) = Map.insert sort (Set.singleton var) Map.empty getVarsTerm (CAS.Application _ ts _) = foldr (Map.unionWith Set.union . getVarsTerm) Map.empty ts getVarsTerm (CAS.Sorted_term t _ _) = getVarsTerm t getVarsTerm (CAS.Cast t _ _) = getVarsTerm t getVarsTerm (CAS.Conditional t1 f t2 _) = Map.unionWith Set.union v3 m where v1 = getVarsTerm t1 v2 = getVarsTerm t2 v3 = getVars f m = Map.unionWith Set.union v1 v2 getVarsTerm (CAS.Mixfix_term ts) = foldr (Map.unionWith Set.union . getVarsTerm) Map.empty ts getVarsTerm (CAS.Mixfix_parenthesized ts _) = foldr (Map.unionWith Set.union . getVarsTerm) Map.empty ts getVarsTerm (CAS.Mixfix_bracketed ts _) = foldr (Map.unionWith Set.union . getVarsTerm) Map.empty ts getVarsTerm (CAS.Mixfix_braced ts _) = foldr (Map.unionWith Set.union . getVarsTerm) Map.empty ts getVarsTerm _ = Map.empty -- | generates the constructor constraint ctorSen :: Bool -> GenAx -> Named CAS.CASLFORMULA ctorSen isFree (sorts, _, ops) = let sortList = Set.toList sorts opSyms = map ( \ c -> let ide = compId c in CAS.Qual_op_name ide (CSign.toOP_TYPE $ compType c) $ posOfId ide) $ Set.toList ops allSyms = opSyms resType _ (CAS.Op_name _) = False resType s (CAS.Qual_op_name _ t _) = CAS.res_OP_TYPE t == s getIndex s = fromMaybe (-1) $ List.elemIndex s sortList addIndices (CAS.Op_name _) = error "CASL/StaticAna: Internal error in function addIndices" addIndices os@(CAS.Qual_op_name _ t _) = (os, map getIndex $ CAS.args_OP_TYPE t) collectOps s = CAS.Constraint s (map addIndices $ filter (resType s) allSyms) s constrs = map collectOps sortList f = CAS.Sort_gen_ax constrs isFree in makeNamed ("ga_generated_" ++ showSepList (showString "_") showId sortList "") f -- | transforms a maude identifier into a valid CASL identifier maudeSymbol2validCASLSymbol :: Token -> [Token] maudeSymbol2validCASLSymbol t = splitDoubleUnderscores str "" where str = ms2vcs $ show t {- | transforms a string coding a Maude identifier into another string representing a CASL identifier -} ms2vcs :: String -> String ms2vcs s@('k' : 'i' : 'n' : 'd' : '_' : _) = s ms2vcs s = if Map.member s stringMap then stringMap Map.! s else let f x y | Map.member x charMap = (charMap Map.! x) ++ "'" ++ y | x == '_' = "__" ++ y | otherwise = x : y in foldr f [] s -- | map of reserved words stringMap :: Map.Map String String stringMap = Map.fromList [("true", "maudeTrue"), ("false", "maudeFalse"), ("not_", "neg__"), ("s_", "suc"), ("_+_", "__+__"), ("_*_", "__*__"), ("_<_", "__<__"), ("_<=_", "__<=__"), ("_>_", "__>__"), ("_>=_", "__>=__"), ("_and_", "__maudeAnd__")] {- | splits the string into a list of tokens, separating the double underscores from the rest of characters -} splitDoubleUnderscores :: String -> String -> [Token] splitDoubleUnderscores [] acc = if null acc then [] else [mkSimpleId acc] splitDoubleUnderscores ('_' : '_' : cs) acc = if null acc then dut : rest else acct : dut : rest where acct = mkSimpleId acc dut = mkSimpleId "__" rest = splitDoubleUnderscores cs [] splitDoubleUnderscores (c : cs) acc = splitDoubleUnderscores cs (acc ++ [c]) -- | error Id errorId :: String -> Id errorId s = token2id $ mkSimpleId $ "ERROR: " ++ s kindId :: Id -> Id kindId i = token2id $ mkSimpleId $ "kind_" ++ show i kindMapId :: MSign.KindRel -> IdMap kindMapId kr = Map.fromList krl' where krl = Map.toList kr krl' = map (\ (x, y) -> (mSym2caslId x, mSym2caslId y)) krl mSym2caslId :: MSym.Symbol -> Id mSym2caslId (MSym.Sort q) = token2id q mSym2caslId (MSym.Kind q) = kindId q' where q' = token2id q mSym2caslId _ = errorId "error translate symbol" -- | checks the profile has at least one sort atLeastOneSort :: MSign.OpMap -> MSign.OpMap atLeastOneSort om = Map.fromList lom' where lom = Map.toList om lom' = filterAtLeastOneSort lom filterAtLeastOneSort :: [(MAS.Qid, MSign.OpDeclSet)] -> [(MAS.Qid, MSign.OpDeclSet)] filterAtLeastOneSort [] = [] filterAtLeastOneSort ((q, ods) : ls) = hd ++ filterAtLeastOneSort ls where ods' = atLeastOneSortODS ods hd = if Set.null ods' then [] else [(q, ods')] atLeastOneSortODS :: MSign.OpDeclSet -> MSign.OpDeclSet atLeastOneSortODS ods = Set.fromList lods' where lods = Set.toList ods lods' = atLeastOneSortLODS lods atLeastOneSortLODS :: [MSign.OpDecl] -> [MSign.OpDecl] atLeastOneSortLODS [] = [] atLeastOneSortLODS ((ss, ats) : ls) = res ++ atLeastOneSortLODS ls where ss' = atLeastOneSortSS ss res = if Set.null ss' then [] else [(ss', ats)] atLeastOneSortSS :: Set.Set MSym.Symbol -> Set.Set MSym.Symbol atLeastOneSortSS = Set.filter hasOneSort hasOneSort :: MSym.Symbol -> Bool hasOneSort (MSym.Operator _ ar co) = any isSymSort (co : ar) hasOneSort _ = False isSymSort :: MSym.Symbol -> Bool isSymSort (MSym.Sort _) = True isSymSort _ = False {- | translates the Maude operator map into a tuple of CASL operators, CASL associative operators, membership induced from each Maude operator, and the set of sorts with the ctor attribute -} translateOps' :: IdMap -> MSign.OpMap -> OpTransTuple translateOps' im = Map.fold (translateOpDeclSet' im) (MapSet.empty, MapSet.empty, Set.empty) -- | translates an operator declaration set into a tern as described above translateOpDeclSet' :: IdMap -> MSign.OpDeclSet -> OpTransTuple -> OpTransTuple translateOpDeclSet' im ods tpl = Set.fold (translateOpDecl' im) tpl ods {- | given an operator declaration updates the accumulator with the translation to CASL operator, checking if the operator has the assoc attribute to insert it in the map of associative operators, generating the membership predicate induced by the operator declaration, and checking if it has the ctor attribute to introduce the operator in the generators sentence -} translateOpDecl' :: IdMap -> MSign.OpDecl -> OpTransTuple -> OpTransTuple translateOpDecl' im (syms, ats) (ops, assoc_ops, cs) = if Set.null syms' then (ops', assoc_ops', cs') else translateOpDecl' im (syms', ats) (ops', assoc_ops', cs') where (sym, syms') = Set.deleteFindMin syms Just (cop_id, ot, _) = maudeSym2CASLOp' im sym ops' = MapSet.insert cop_id ot ops assoc_ops' = if any MAS.assoc ats then MapSet.insert cop_id ot assoc_ops else assoc_ops cs' = if any MAS.ctor ats then Set.insert (Component cop_id ot) cs else cs {- | translates a Maude operator symbol into a pair with the id of the operator and its CASL type -} maudeSym2CASLOp' :: IdMap -> MSym.Symbol -> Maybe (Id, CSign.OpType, CSign.OpType) maudeSym2CASLOp' im (MSym.Operator op ar co) = Just (token2id op, ot, ot') where f = token2id . getName g = (`maudeSymbol2caslSort'` im) ot = CSign.OpType CAS.Total (map g ar) (g co) ot' = CSign.OpType CAS.Total (map f ar) (f co) maudeSym2CASLOp' _ _ = Nothing maudeSymbol2caslSort' :: MSym.Symbol -> IdMap -> CAS.SORT maudeSymbol2caslSort' (MSym.Sort q) _ = token2id $ mkSimpleId $ "kind_" ++ show q maudeSymbol2caslSort' (MSym.Kind q) im = Map.findWithDefault err q' im where q' = token2id q err = errorId "error translate symbol" maudeSymbol2caslSort' _ _ = errorId "error translate symbol"
nevrenato/HetsAlloy
Maude/PreComorphism.hs
gpl-2.0
54,078
0
20
14,277
14,569
7,554
7,015
919
4
{-# LANGUAGE TemplateHaskell, EmptyDataDecls, MultiParamTypeClasses, FlexibleInstances, TypeSynonymInstances, DeriveDataTypeable, Rank2Types #-} -- -- Copyright (c) 2008 Gustav Munkby -- -- | An implementation of NSTextStorage that uses Yi's FBuffer as -- the backing store. module Yi.UI.Cocoa.TextStorage ( TextStorage , initializeClass_TextStorage , newTextStorage , setTextStorageBuffer , visibleRangeChanged ) where import Prelude () import Yi.Editor (currentRegex, emptyEditor, Editor) import Yi.Prelude import Yi.Buffer import Yi.Style import Yi.UI.Cocoa.Utils import Yi.UI.Utils import Yi.Window import Control.Arrow import Data.Char import Data.Maybe import qualified Data.Rope as R import qualified Data.Map as M import qualified Data.List as L import Foreign hiding (new) import Foreign.C -- Specify Cocoa imports explicitly, to avoid name-clashes. -- Since the number of functions recognized by HOC varies -- between revisions, this seems like the safest choice. import HOC import Foundation ( Unichar,NSString,NSStringClass,NSDictionary,NSRange(..),NSRangePointer, NSStringMetaClass,toNSString,NSCharacterSet,_NSCharacterSet,invertedSet, _NSMutableCharacterSet,formUnionWithCharacterSet,newlineCharacterSet, length,attributeAtIndexEffectiveRange,attributesAtIndexEffectiveRange, attributesAtIndexLongestEffectiveRangeInRange,nsMaxRange, rangeOfCharacterFromSetOptionsRange,nsLiteralSearch, beginEditing,endEditing,setAttributesRange,haskellString, NSMutableDictionary,_NSMutableDictionary,dictionaryWithDictionary, objectForKey,setObjectForKey,substringWithRange,copy, attributeAtIndexLongestEffectiveRangeInRange, addAttributeValueRange,addAttributesRange) import AppKit ( NSTextStorage,NSTextStorageClass,string,fixesAttributesLazily, NSTextStorageMetaClass,NSFontClass,NSFont,coveredCharacterSet, _NSCursor,_NSFont,replaceCharactersInRangeWithString, _NSParagraphStyle,defaultParagraphStyle,ibeamCursor,_NSTextStorage, editedRangeChangeInLength,nsTextStorageEditedAttributes, nsTextStorageEditedCharacters,userFixedPitchFontOfSize) -- Unfortunately, my version of hoc does not handle typedefs correctly, -- and thus misses every selector that uses the "unichar" type, even -- though it has introduced a type alias for it... $(declareRenamedSelector "characterAtIndex:" "characterAtIndex" [t| CUInt -> IO Unichar |]) instance Has_characterAtIndex (NSString a) $(declareRenamedSelector "getCharacters:range:" "getCharactersRange" [t| Ptr Unichar -> NSRange -> IO () |]) instance Has_getCharactersRange (NSString a) -- A (hidden) utility method for looking up font substitutions (used by WebKit) $(declareRenamedSelector "findFontLike:forString:withRange:inLanguage:" "findFontLikeForStringWithRangeInLanguage" [t| forall t1 t2 t3. NSFont t1 -> NSString t2 -> NSRange -> NSString t3 -> IO (NSFont ()) |]) instance Has_findFontLikeForStringWithRangeInLanguage (NSFontClass a) _silence :: ImpType_findFontLikeForStringWithRangeInLanguage x y _silence = undefined -- | SplitRope provides means for tracking the position -- of Cocoa reads from the underlying rope... data SplitRope = SplitRope R.Rope -- Cocoa has moved beyond this portion R.Rope -- Cocoa is currently accessing this part Int -- From this offset... [Unichar] -- And in this format... =) [Unichar] -- But we keep the whole as a backup -- | Create a new SplitRope, and initialize the encoded portion appropriately. mkSplitRope :: R.Rope -> R.Rope -> SplitRope mkSplitRope done next = SplitRope done next 0 acs acs where acs = concatMap (encodeUTF16 . fromEnum) (R.toString next) -- | Get the length of the whole SplitRope. sLength :: SplitRope -> Int sLength (SplitRope done next _ _ _) = R.length done + R.length next -- | Ensure that the specified position is in the first chunk of -- the ``next'' rope. sSplitAtChunkBefore :: Int -> SplitRope -> SplitRope sSplitAtChunkBefore n s@(SplitRope done next _ _ _) | n < R.length done = mkSplitRope done' (R.append renext next) | R.null redone = s | otherwise = mkSplitRope (R.append done redone) next' where (done', renext) = R.splitAtChunkBefore n done (redone, next') = R.splitAtChunkBefore (n - R.length done) next sSplitAt :: Int -> SplitRope -> SplitRope sSplitAt n s = SplitRope done next n' (if n' >= off then L.drop (n' - off) cs else L.drop n' acs) acs where n' = n - R.length done SplitRope done next off cs acs = sSplitAtChunkBefore n s encodeUTF16 :: Int -> [Unichar] encodeUTF16 c | c < 0x10000 = [fromIntegral c] | otherwise = let c' = c - 0x10000 in [0xd800 .|. (fromIntegral $ c' `shiftR` 10), 0xdc00 .|. (fromIntegral $ c' .&. 0x3ff)] -- Introduce a NSString subclass that has a Data.Rope internally. -- A NSString subclass needs to implement length and characterAtIndex, -- and for performance reasons getCharactersRange. -- This implementation is a hack just like the old bytestring one, -- but less so as Rope uses character indices instead of byte indices. -- In theory, this should work fine for all characters in the -- unicode BMP. I am unsure as to what happens if any characters -- outside of the BMP are used. $(declareClass "YiRope" "NSString") $(exportClass "YiRope" "yirope_" [ InstanceVariable "str" [t| SplitRope |] [| mkSplitRope R.empty R.empty |] , InstanceMethod 'length -- ' , InstanceMethod 'characterAtIndex -- ' , InstanceMethod 'getCharactersRange -- ' ]) yirope_length :: YiRope () -> IO CUInt yirope_length slf = do -- logPutStrLn $ "Calling yirope_length (gah...)" slf #. _str >>= return . fromIntegral . sLength yirope_characterAtIndex :: CUInt -> YiRope () -> IO Unichar yirope_characterAtIndex i slf = do -- logPutStrLn $ "Calling yirope_characterAtIndex " ++ show i flip (modifyIVar _str) slf $ \s -> do s'@(SplitRope _ _ _ (c:_) _) <- return (sSplitAt (fromIntegral i) s) return (s', c) yirope_getCharactersRange :: Ptr Unichar -> NSRange -> YiRope () -> IO () yirope_getCharactersRange p _r@(NSRange i l) slf = do -- logPutStrLn $ "Calling yirope_getCharactersRange " ++ show r flip (modifyIVar_ _str) slf $ \s -> do s'@(SplitRope _ _ _ cs _) <- return (sSplitAt (fromIntegral i) s) pokeArray p (L.take (fromIntegral l) cs) return s' -- An implementation of NSTextStorage that uses Yi's FBuffer as -- the backing store. An implementation must at least implement -- a O(1) string method and attributesAtIndexEffectiveRange. -- For performance reasons, attributeAtIndexEffectiveRange is -- implemented to deal with specific properties such as font. -- Judging by usage logs, the environment using the text storage -- seem to rely on strings O(1) behavior and thus caching the -- result seems like a good idea. In addition attributes are -- queried for the same location multiple times, and thus caching -- them as well also seems fruitful. type PicStroke = (CUInt, Attributes) type Picture = [PicStroke] instance Show NSRange where show (NSRange i len) = "NSRange " ++ show i ++ " " ++ show len emptyPicture :: (Picture,NSRange) emptyPicture = ([],NSRange 0 0) dropStrokesWhile :: (a -> Bool) -> [a] -> [a] dropStrokesWhile f = helper where helper [] = [] helper [_] = [] helper ~(x:y:zs) = if f y then helper (y:zs) else (x:y:zs) attributeIsCached :: CUInt -> [PicStroke] -> Bool attributeIsCached _ [] = False attributeIsCached i ~((j,_):_) = i >= j -- | Extend the currently cached picture, so that it at least -- covers the desired region. The resulting picture starts -- at the location of the desired region, but might extend -- further... extendPicture :: CUInt -> (CUInt -> IO Picture) -> Picture -> IO Picture extendPicture d f c = if attributeIsCached d c then return c else f d type YiState = (Editor, FBuffer, Window, UIStyle, YiRope ()) $(declareClass "YiTextStorage" "NSTextStorage") $(exportClass "YiTextStorage" "yts_" [ InstanceVariable "yiState" [t| YiState |] [| error "Uninitialized" |] , InstanceVariable "dictionaryCache" [t| M.Map Attributes (NSDictionary ()) |] [| M.empty |] , InstanceVariable "pictureCache" [t| (Picture, NSRange) |] [| emptyPicture |] , InstanceVariable "attributeCache" [t| [PicStroke] |] [| [] |] , InstanceVariable "covered" [t| (NSCharacterSet (), NSCharacterSet ()) |] [| error "Uninitialized" |] , InstanceMethod 'string -- ' , InstanceMethod 'fixesAttributesLazily -- ' , InstanceMethod 'attributeAtIndexEffectiveRange -- ' , InstanceMethod 'attributeAtIndexLongestEffectiveRangeInRange , InstanceMethod 'attributesAtIndexEffectiveRange -- ' , InstanceMethod 'attributesAtIndexLongestEffectiveRangeInRange , InstanceMethod 'replaceCharactersInRangeWithString -- ' , InstanceMethod 'setAttributesRange -- Disallow changing attributes , InstanceMethod 'addAttributesRange -- optimized to avoid needless work , InstanceMethod 'addAttributeValueRange -- ... , InstanceMethod 'length -- ' ]) _editor :: YiTextStorage () -> IO Editor _buffer :: YiTextStorage () -> IO FBuffer _window :: YiTextStorage () -> IO Window _uiStyle :: YiTextStorage () -> IO UIStyle _stringCache :: YiTextStorage () -> IO (YiRope ()) _editor o = (\ (x,_,_,_,_) -> x) <$> o #. _yiState _buffer o = (\ (_,x,_,_,_) -> x) <$> o #. _yiState _window o = (\ (_,_,x,_,_) -> x) <$> o #. _yiState _uiStyle o = (\ (_,_,_,x,_) -> x) <$> o #. _yiState _stringCache o = (\ (_,_,_,_,x) -> x) <$> o #. _yiState yts_length :: YiTextStorage () -> IO CUInt yts_length slf = do -- logPutStrLn "Calling yts_length " slf # _stringCache >>= length yts_string :: YiTextStorage () -> IO (NSString ()) yts_string slf = castObject <$> slf # _stringCache yts_fixesAttributesLazily :: YiTextStorage () -> IO Bool yts_fixesAttributesLazily _ = return True yts_attributesAtIndexEffectiveRange :: CUInt -> NSRangePointer -> YiTextStorage () -> IO (NSDictionary ()) yts_attributesAtIndexEffectiveRange i er slf = do (cache, _) <- slf #. _pictureCache if attributeIsCached i cache then returnEffectiveRange cache i er (NSRange i 12345678) slf else yts_attributesAtIndexLongestEffectiveRangeInRange i er (NSRange i 1) slf yts_attributesAtIndexLongestEffectiveRangeInRange :: CUInt -> NSRangePointer -> NSRange -> YiTextStorage () -> IO (NSDictionary ()) yts_attributesAtIndexLongestEffectiveRangeInRange i er rl@(NSRange il _) slf = do (cache, prev_rl) <- slf #. _pictureCache -- Since we only cache the remaining part of the rl window, we must -- check to ensure that we do not re-read the window all the time... let use_i = if prev_rl == rl then i else il -- logPutStrLn $ "yts_attributesAtIndexLongestEffectiveRangeInRange " ++ show i ++ " " ++ show rl full <- extendPicture use_i (flip storagePicture slf) cache returnEffectiveRange full i er rl slf returnEffectiveRange :: Picture -> CUInt -> NSRangePointer -> NSRange -> YiTextStorage () -> IO (NSDictionary ()) returnEffectiveRange full i er rl@(NSRange il ll) slf = do pic <- return $ dropStrokesWhile ((fromIntegral i >=) . fst) full slf # setIVar _pictureCache (pic, rl) case pic of (before,s):rest@((next,_):_) -> do let begin = max before il let len = min (il + ll - begin) (next - begin) let rng = NSRange begin len -- Keep a cache of seen styles... usually, there should not be to many -- TODO: Have one centralized cache instead of one per text storage... dict <- slf # cachedDictionaryFor s if (nsMaxRange rng == begin) then return dict else do str <- yts_string slf (covered, missing) <- slf #. _covered NSRange b2 _ <- str # rangeOfCharacterFromSetOptionsRange missing nsLiteralSearch rng if begin /= b2 -- First caracter is included in the font then do let corange = NSRange begin $ if b2 == 0x7fffffff then len else b2 - begin -- logPutStrLn $ "Normal " ++ show i ++ show rl ++ show corange when (er /= nullPtr) (poke er corange) when (rng /= corange) $ slf # setIVar _pictureCache ((before,s):(nsMaxRange corange,s):rest, rl) return dict else do NSRange b3 _ <- str # rangeOfCharacterFromSetOptionsRange covered nsLiteralSearch rng let unrange = NSRange begin $ if b3 == 0x7fffffff then len else b3 - begin rep <- str # substringWithRange unrange >>= haskellString -- logPutStrLn $ "Fixing " ++ show unrange ++ ": " ++ show rep font <- castObject <$> dict # objectForKey (toNSString "NSFont") :: IO (NSFont ()) font2 <- _NSFont # findFontLikeForStringWithRangeInLanguage font str unrange nil dict2 <- castObject <$> _NSMutableDictionary # dictionaryWithDictionary dict :: IO (NSMutableDictionary ()) dict2 # setObjectForKey font2 (toNSString "NSFont") dict2 # setObjectForKey font (toNSString "NSOriginalFont") when (er /= nullPtr) (poke er unrange) when (rng /= unrange) $ slf # setIVar _pictureCache ((before,s):(nsMaxRange unrange,s):rest, rl) castObject <$> return dict2 _ -> error "Empty picture?" cachedDictionaryFor :: Attributes -> YiTextStorage () -> IO (NSDictionary ()) cachedDictionaryFor s slf = do slf # modifyIVar _dictionaryCache (\dicts -> case M.lookup s dicts of Just dict -> return (dicts, dict) _ -> do dict <- convertAttributes s return (M.insert s dict dicts, dict)) simpleAttr :: String -> IO (Either String (ID ())) simpleAttr "NSFont" = Right <$> castObject <$> userFixedPitchFontOfSize 0 _NSFont simpleAttr "NSGlyphInfo" = Right <$> return nil simpleAttr "NSAttachment" = Right <$> return nil simpleAttr "NSCursor" = Right <$> castObject <$> ibeamCursor _NSCursor simpleAttr "NSToolTip" = Right <$> return nil simpleAttr "NSLanguage" = Right <$> return nil simpleAttr "NSLink" = Right <$> return nil -- TODO: Adjust line break property... simpleAttr "NSParagraphStyle" = Right <$> castObject <$> defaultParagraphStyle _NSParagraphStyle simpleAttr attr = Left <$> return attr yts_attributeAtIndexLongestEffectiveRangeInRange :: NSString t -> CUInt -> NSRangePointer -> NSRange -> YiTextStorage () -> IO (ID ()) yts_attributeAtIndexLongestEffectiveRangeInRange attr i er rn slf = do sres <- simpleAttr =<< haskellString attr case sres of Right res -> safePoke er rn >> return res Left "NSBackgroundColor" -> do ~((s,a):xs) <- onlyBg <$> L.takeWhile ((<= nsMaxRange rn).fst) <$> slf # storagePicture i safePoke er (NSRange s ((if null xs then nsMaxRange rn else fst (head xs)) - s)) castObject <$> getColor False (background a) Left _attr' -> do -- logPutStrLn $ "Unoptimized yts_attributeAtIndexLongestEffectiveRangeInRange " ++ attr' ++ " at " ++ show i super slf # attributeAtIndexLongestEffectiveRangeInRange attr i er rn yts_attributeAtIndexEffectiveRange :: forall t. NSString t -> CUInt -> NSRangePointer -> YiTextStorage () -> IO (ID ()) yts_attributeAtIndexEffectiveRange attr i er slf = do sres <- simpleAttr =<< haskellString attr case sres of Right res -> slf # length >>= safePoke er . NSRange 0 >> return res Left "NSBackgroundColor" -> do len <- slf # length slf # yts_attributeAtIndexLongestEffectiveRangeInRange attr i er (NSRange i (min 100 (len - i))) Left _attr' -> do -- TODO: Optimize the other queries as well (if needed) -- logPutStrLn $ "Unoptimized yts_attributeAtIndexEffectiveRange " ++ attr' ++ " at " ++ show i super slf # attributeAtIndexEffectiveRange attr i er -- These methods are used to modify the contents of the NSTextStorage. -- We do not allow direct updates of the contents this way, though. yts_replaceCharactersInRangeWithString :: forall t. NSRange -> NSString t -> YiTextStorage () -> IO () yts_replaceCharactersInRangeWithString _ _ _ = return () yts_setAttributesRange :: forall t. NSDictionary t -> NSRange -> YiTextStorage () -> IO () yts_setAttributesRange _ _ _ = return () yts_addAttributesRange :: NSDictionary t -> NSRange -> YiTextStorage () -> IO () yts_addAttributesRange _ _ _ = return () yts_addAttributeValueRange :: NSString t -> ID () -> NSRange -> YiTextStorage () -> IO () yts_addAttributeValueRange _ _ _ _ = return () -- | Remove element x_(i+1) if f(x_i,x_(i+1)) is true filter2 :: (a -> a -> Bool) -> [a] -> [a] filter2 _f [] = [] filter2 _f [x] = [x] filter2 f (x1:x2:xs) = if f x1 x2 then filter2 f (x1:xs) else x1 : filter2 f (x2:xs) -- | Keep only the background information onlyBg :: [PicStroke] -> [PicStroke] onlyBg = filter2 ((==) `on` (background . snd)) -- | A version of poke that does nothing if p is null. safePoke :: (Storable a) => Ptr a -> a -> IO () safePoke p x = when (p /= nullPtr) (poke p x) -- | Execute strokeRangesB on the buffer, and update the buffer -- so that we keep around cached syntax information... -- We assume that the incoming region provide character-indices, -- and we need to find out the corresponding byte-indices storagePicture :: CUInt -> YiTextStorage () -> IO Picture storagePicture i slf = do (ed, buf, win, sty, _) <- slf #. _yiState -- logPutStrLn $ "storagePicture " ++ show i return $ bufferPicture ed sty buf win i bufferPicture :: Editor -> UIStyle -> FBuffer -> Window -> CUInt -> Picture bufferPicture ed sty buf win i = fmap (first fromIntegral) $ fst $ runBuffer win buf $ do e <- sizeB (attributesPictureB sty (currentRegex ed) (mkRegion (fromIntegral i) e) []) type TextStorage = YiTextStorage () initializeClass_TextStorage :: IO () initializeClass_TextStorage = do initializeClass_YiRope initializeClass_YiTextStorage applyUpdate :: YiTextStorage () -> FBuffer -> Update -> IO () applyUpdate buf b (Insert p _ s) = buf # editedRangeChangeInLength nsTextStorageEditedCharacters (NSRange (fromIntegral p) 0) (fromIntegral $ R.length s) applyUpdate buf b (Delete p _ s) = let len = R.length s in buf # editedRangeChangeInLength nsTextStorageEditedCharacters (NSRange (fromIntegral p) (fromIntegral len)) (fromIntegral (negate len)) newTextStorage :: UIStyle -> FBuffer -> Window -> IO TextStorage newTextStorage sty b w = do buf <- new _YiTextStorage s <- new _YiRope s # setIVar _str (mkSplitRope R.empty (runBufferDummyWindow b (streamB Forward 0))) buf # setIVar _yiState (emptyEditor, b, w, sty, s) -- Determine the set of characters in the font. -- Always add newlines, since they are currently not rendered anyhow... allset <- new _NSMutableCharacterSet buf # setMonospaceFont >>= coveredCharacterSet >>= flip formUnionWithCharacterSet allset _NSCharacterSet # newlineCharacterSet >>= flip formUnionWithCharacterSet allset . castObject covset <- castObject <$> copy allset misset <- covset # invertedSet buf # setIVar _covered (covset, misset) return buf setTextStorageBuffer :: Editor -> FBuffer -> TextStorage -> IO () setTextStorageBuffer ed buf storage = do storage # beginEditing flip (modifyIVar_ _yiState) storage $ \ (_,_,w,sty,s) -> do s # setIVar _str (mkSplitRope R.empty (runBufferDummyWindow buf (streamB Forward 0))) return (ed, buf, w, sty, s) when (not $ null $ getVal pendingUpdatesA buf) $ do mapM_ (applyUpdate storage buf) [u | TextUpdate u <- getVal pendingUpdatesA buf] storage # setIVar _pictureCache emptyPicture storage # endEditing visibleRangeChanged :: NSRange -> TextStorage -> IO () visibleRangeChanged range storage = do storage # setIVar _pictureCache emptyPicture storage # editedRangeChangeInLength nsTextStorageEditedAttributes range 0
codemac/yi-editor
src/Yi/UI/Cocoa/TextStorage.hs
gpl-2.0
19,848
0
24
3,810
5,352
2,772
2,580
309
6
-- -- Copyright (c) 2005 Don Stewart - http://www.cse.unsw.edu.au/~dons -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License as -- published by the Free Software Foundation; either version 2 of -- the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -- 02111-1307, USA. -- -- The functions we know how to generate binaries for module Command where data Command = Command Name -- haskell function to use Name -- binary name (for, e.g. !!) Type Mode [String] data Mode = List | Packed name :: Command -> Name name (Command _ f _ _ _) = f type Name = String data Type = Pair Type Type | To Type Type -- -> | S -- String | LS -- [String] | LI -- [Int] | I -- Int | B -- Bool | MaybeT Type deriving (Show, Eq) ------------------------------------------------------------------------ commands :: [Command] commands = [ Command "tail" "tl" (LS `To` LS) Packed ["tail :: [a] -> [a]", "Extract the elements after the head of a list, which must be non-empty."] , Command "init" "init" (LS `To` LS) Packed ["init :: [a] -> [a]" ,"Return all the elements of a list except the last one." ,"The list must be finite and non-empty."] , Command "reverse" "reverse" (LS `To` LS) Packed ["reverse :: [a] -> [a]" ,"reverse returns the elements of the list in reverse order." ,"The list must be finite."] , Command "nub" "nub" (LS `To` LS) Packed ["nub :: (Eq a) => [a] -> [a]" ,"The 'nub' function removes duplicate elements from a list." ,"In particular, it keeps only the first occurrence of each element."] , Command "sort" "srt" (LS `To` LS) Packed ["sort :: (Ord a) => [a] -> [a]" ,"The 'sort' function implements a stable sorting algorithm."] , Command "id" "i" (S `To` S) Packed ["id :: a -> a" ,"Identity function."] , Command "cycle" "cycle" (LS `To` LS) List ["cycle :: [a] -> [a]" ,"'cycle' ties a finite list into a circular one, or equivalently," ,"the infinite repetition of the original list. It is the identity" ,"on infinite lists."] , Command "transpose" "transpose" (LS `To` LS) List ["transpose :: [[a]] -> [[a]]" ,"The 'transpose' function transposes the rows and columns of its argument." ,"For example," ,"" ,"> transpose [[1,2,3],[4,5,6]] == [[1,4],[2,5],[3,6]]"] ------------------------------------------------------------------------ , Command "concat" "concat" (LS `To` S) List ["concat :: [[a]] -> [a]" ,"Concatenate a list of lists."] , Command "unwords" "unwords" (LS `To` S) List ["unwords :: [String] -> String" ,"'unwords' is an inverse operation to 'words'." ,"It joins words with separating spaces."] , Command "head" "hd" (LS `To` S) Packed ["head :: [a] -> a" ,"Extract the first element of a list, which must be non-empty."] , Command "last" "last" (LS `To` S) Packed ["last :: [a] -> a" ,"Extract the last element of a list, which must be finite and non-empty."] , Command "minimum" "min" (LS `To` S) Packed ["minimum :: (Ord a) => [a] -> a" ,"'minimum' returns the minimum value from a list," ,"which must be non-empty, finite, and of an ordered type."] , Command "maximum" "max" (LS `To` S) Packed ["maximum :: (Ord a) => [a] -> a" ,"'maximum' returns the maximum value from a list," ,"which must be non-empty, finite, and of an ordered type."] ------------------------------------------------------------------------ , Command "length" "length" -- count '\n' is faster (LS `To` I) Packed ["length :: [a] -> Int" ,"length returns the length of a finite list as an Int."] ------------------------------------------------------------------------ , Command "(:[])" "show" (S `To` LS) Packed ["show :: (Show a) => a -> String" ,"Convert a value to a readable 'String'."] , Command "repeat" "rpt" (S `To` LS) List ["repeat :: a -> [a]" ,"repeat x is an infinite list, with x the value of every element."] , Command "words" "words" (S `To` LS) List ["words :: String -> [String]" ,"'words' breaks a string up into a list of words, which were delimited" ,"by white space."] , Command "map (concat . intersperse \" \") . group" "group" (LS `To` LS) List ["group :: Eq a => [a] -> [[a]]" ,"The 'group' function takes a list and returns a list of lists such" ,"that the concatenation of the result is equal to the argument. Moreover," ,"each sublist in the result contains only equal elements. For example," ,"" ,"> group \"Mississippi\" = [\"M\",\"i\",\"ss\",\"i\",\"ss\",\"i\",\"pp\",\"i\"]" ,"" ,"It is a special case of 'groupBy', which allows the programmer to supply" ,"their own equality test."] ------------------------------------------------------------------------ , Command "take" "take" (I `To` (LS `To` LS)) List ["take :: Int -> [a] -> [a]" ,"take n, applied to a list xs, returns the prefix of xs" ,"of length n, or xs itself if n > length xs."] , Command "drop" "drop" (I `To` (LS `To` LS)) List ["drop :: Int -> [a] -> [a]" ,"drop n xs returns the suffix of xs" ,"after the first n elements, or [] if n > length xs."] ------------------------------------------------------------------------ , Command "map" "map" ((S `To` S) `To` (LS `To` LS)) List -- list is still faster ["map :: (a -> b) -> [a] -> [b]" ,"map f xs is the list obtained by applying f to each element of xs, i.e.," ,"" ,"> map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn]" ,"> map f [x1, x2, ...] == [f x1, f x2, ...]"] ------------------------------------------------------------------------ , Command "filter" "filter" ((S `To` B) `To` (LS `To` LS)) List -- list version if faster ["filter :: (a -> Bool) -> [a] -> [a]" ,"filter, applied to a predicate and a list, returns the list of" ,"those elements that satisfy the predicate."] , Command "takeWhile" "takew" ((S `To` B) `To` (LS `To` LS)) List ["takeWhile :: (a -> Bool) -> [a] -> [a]" ,"'takeWhile', applied to a predicate p and a list xs, returns the" ,"longest prefix (possibly empty) of xs of elements that satisfy p."] , Command "dropWhile" "dropw" ((S `To` B) `To` (LS `To` LS)) List ["dropWhile :: (a -> Bool) -> [a] -> [a]" ,"'dropWhile' p xs returns the suffix remaining after 'takeWhile' p xs."] ------------------------------------------------------------------------ , Command "intersperse" "intersperse" (S `To` (LS `To` LS)) Packed ["intersperse :: a -> [a] -> [a]" ,"The 'intersperse' function takes an element and a list and" ,"`intersperses\' that element between the elements of the list." ,"For example," ,"" ,"> intersperse ',' \"abcde\" == \"a,b,c,d,e\""] , Command "delete" "delete" (S `To` (LS `To` LS)) Packed ["delete :: (Eq a) => a -> [a] -> [a]" ,"'delete' x removes the first occurrence of x from its list argument." ,"For example," ,"" ,"> delete 'a' \"banana\" == \"bnana\""] , Command "insert" "insert" (S `To` (LS `To` LS)) Packed ["insert :: Ord a => a -> [a] -> [a]" ,"The 'insert' function takes an element and a list and inserts the" ,"element into the list at the last position where it is still less" ,"than or equal to the next element. In particular, if the list" ,"is sorted before the call, the result will also be sorted."] , Command "(:)" "cons" (S `To` (LS `To` LS)) Packed ["(:) :: a -> [a] -> [a]","List constructor"] ------------------------------------------------------------------------ , Command "elemIndices" "indices" (S `To` (LS `To` LI)) List ["elemIndices :: Eq a => a -> [a] -> [Int]" ,"The 'elemIndices' function return the" ,"indices of all elements equal to the query element, in ascending order."] ------------------------------------------------------------------------ , Command "flip (!!)" "index" (I `To` (LS `To` S)) Packed ["flip (!!) :: Int -> [a] -> a" ,"LS index (subscript) operator, starting from 0."] ------------------------------------------------------------------------ -- is this ok for zip? , Command "(zipWith ((. (' ':)) . (++)))" "zp" (LS `To` (LS `To` LS)) List -- the zipWith code has a char in it ["zip :: [a] -> [b] -> [(a,b)]" ,"'zip' takes two lists and returns a list of corresponding pairs." ,"If one input list is short, excess elements of the longer list are" ,"discarded."] , Command "union" "union" (LS `To` (LS `To` LS)) Packed ["union :: (Eq a) => [a] -> [a] -> [a]" ,"The 'union' function returns the list union of the two lists." ,"For example," ,"" ,"> \"dog\" `union` \"cow\" == \"dogcw\"" ,"" ,"Duplicates, and elements of the first list, are removed from the" ,"the second list, but if the first list contains duplicates, so will" ,"the result."] , Command "(\\\\)" "difference" (LS `To` (LS `To` LS)) Packed ["(\\\\) :: (Eq a) => [a] -> [a] -> [a]" ,"The '\\\\' function is list difference ((non-associative)." ,"In the result of xs '\\' ys, the first occurrence of each element of" ,"ys in turn (if any) has been removed from xs. Thus" ,"" ,"> (xs ++ ys) \\ xs == ys."] , Command "intersect" "intersect" (LS `To` (LS `To` LS)) Packed ["intersect :: (Eq a) => [a] -> [a] -> [a]" ,"The 'intersect' function takes the list intersection of two lists." ,"For example," ,"" ,"> [1,2,3,4] `intersect` [2,4,6,8] == [2,4]" ,"" ,"If the first list contains duplicates, so will the result."] , Command "(++)" "append" (LS `To` (LS `To` LS)) Packed ["(++) :: [a] -> [a] -> [a]" ,"Append two lists, i.e.," ,"" ,"[x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn]" ,"[x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]" ,"" ,"the first list is not finite, the result is the first list."] ------------------------------------------------------------------------ , Command "(\\f -> foldl f [])" "foldl" ((S `To` (S `To` S)) `To`(LS `To` S)) List ["foldl :: (a -> b -> a) -> a -> [b] -> a" ,"'foldl', applied to a binary operator, a starting value (typically" ,"the left-identity of the operator), and a list, reduces the list" ,"using the binary operator, from left to right:" ,"" ,"> foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn" ,"" ,"The list must be finite."] , Command "(\\f -> foldr f [])" "foldr" ((S `To` (S `To` S)) `To`(LS `To` S)) List ["foldr :: (a -> b -> b) -> b -> [a] -> b" ,"'foldr', applied to a binary operator, a starting value (typically" ,"the right-identity of the operator), and a list, reduces the list" ,"using the binary operator, from right to left:" ,"" ,"foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)" ] ------------------------------------------------------------------------ , Command "iterate" "iterate" ((S `To` S) `To` (S `To` LS)) List ["iterate :: (a -> a) -> a -> [a]" ,"'iterate' f x returns an infinite list of repeated applications" ,"of f to x:" ,"" ,"> iterate f x == [x, f x, f (f x), ...]"] ------------------------------------------------------------------------ , Command "unfoldr" "unfoldr" ((S `To` (MaybeT (S `Pair` S))) `To` (S `To` LS)) List ["unfoldr :: (b -> Maybe (a, b)) -> b -> [a]" ,"The 'unfoldr' function is a `dual\' to 'foldr': while 'foldr'" ,"reduces a list to a summary value, 'unfoldr' builds a list from" ,"a seed value. The function takes the element and returns 'Nothing'" ,"if it is done producing the list or returns Just (a,b), in which" ,"case, a is a prepended to the list and b is used as the next" ,"element in a recursive call. For example," ,"" ,"> iterate f == unfoldr (\\x -> Just (x, f x))" ,"" ,"In some cases, 'unfoldr' can undo a 'foldr' operation:" ,"" ,"> unfoldr f' (foldr f z xs) == xs" ,"" ,"if the following holds:" ,"" ,"> f' (f x y) = Just (x,y)" ,"> f' z = Nothing"] ------------------------------------------------------------------------ , Command "($)" "ap" ((S `To` S) `To` (S `To` S)) List ["($) :: (a -> b) -> a -> b" ,"Function application."] ------------------------------------------------------------------------ , Command "concatMap" "concatmap" ((S `To` S) `To` (LS `To` S)) List ["concatMap :: (a -> a) -> [a] -> a" ,"Map a function over a list and concatenate the results."] ]
cpennington/h4sh
Command.hs
gpl-2.0
14,760
0
14
4,602
1,996
1,236
760
320
1
module Helium.StaticAnalysis.Heuristics.RepairSystem (repairSystem) where {-| Module : RepairSystem License : GPL Maintainer : [email protected] Stability : experimental Portability : portable The work of Arjen Langebaerd to try out all kinds of repairs up to a particular depth to see whether any repairs fix a type error. This can then be displayed as a hint. -} import Top.Types --import Top.States.BasicState (printMessage) import Top.Implementation.TypeGraph.Basics (EdgeId, VertexId(..)) import Top.Implementation.TypeGraph.Heuristic --import Top.Implementation.TypeGraph.TypeGraphState import Top.Repair.Repair (repair) import Top.Repair.AExpr import Data.Maybe import Helium.StaticAnalysis.Miscellaneous.ConstraintInfo import Helium.StaticAnalysis.Miscellaneous.DoublyLinkedTree import Helium.Syntax.UHA_Syntax --import Helium.Syntax.UHA_Source import Helium.Utils.Utils (internalError) type HeliumRepairInfo = (Maybe Tp, Maybe UHA_Source) instance RepairInfo HeliumRepairInfo where getType = fst makeInfo tp = (Just tp, Nothing) emptyInfo = (Nothing, Nothing) repairSystem :: Heuristic ConstraintInfo repairSystem = Heuristic (Filter "Repair System" handleList) where handleList :: HasTypeGraph m ConstraintInfo => [(EdgeId, ConstraintInfo)] -> m [(EdgeId, ConstraintInfo)] handleList xs = do aexprs <- recList xs printMessage "\n========== Begin of Repair System ===========\n" printMessage $ unlines (map (unlines . repair) aexprs) printMessage "========== End of Repair System ===========\n" return xs recList :: HasTypeGraph m ConstraintInfo => [(EdgeId, ConstraintInfo)] -> m [AExpr HeliumRepairInfo] recList [] = return [] recList (x:xs) = do mPair <- handleOne x case mPair of Just (edges, aexpr) -> do aexprs <- recList (filter ((`notElem` edges) . fst) xs) return (aexpr:aexprs) Nothing -> recList xs handleOne :: HasTypeGraph m ConstraintInfo => (EdgeId, ConstraintInfo) -> m (Maybe ([EdgeId], AExpr HeliumRepairInfo)) handleOne (edgeId, info) | isBlock aexpr = return Nothing | otherwise = do edges <- whichEdges aexpr doWithoutEdges edges $ do mexpr <- substituteLocalType aexpr return (fmap (\expr -> (map fst edges, expr)) mexpr) where aexpr = makeAExpr (rootOfInfoTree (localInfo info)) substituteLocalType :: HasTypeGraph m ConstraintInfo => AExpr LocalInfo -> m (Maybe (AExpr HeliumRepairInfo)) substituteLocalType aexpr = do subExpr <- mapAExprM toRepairInfo aexpr return (change subExpr) where change :: AExpr (Maybe HeliumRepairInfo) -> Maybe (AExpr HeliumRepairInfo) change aexpr | all isJust (getInfos aexpr) = Just (fmap fromJust aexpr) | otherwise = Nothing toRepairInfo :: HasTypeGraph m ConstraintInfo => LocalInfo -> m (Maybe HeliumRepairInfo) toRepairInfo info = case assignedType info of Just tp -> do mtp <- substituteTypeSafe tp return (fmap (\tp -> (Just tp, Just (self info))) mtp) Nothing -> return Nothing rootOfInfoTree :: InfoTree -> InfoTree rootOfInfoTree infoTree | isBlock (makeAExpr infoTree) = infoTree | otherwise = rec_ infoTree where rec_ thisTree = case parent thisTree of Just it | not . isBlock . makeAExpr $ it -> rec_ it _ -> thisTree makeAExpr :: InfoTree -> AExpr LocalInfo makeAExpr infoTree = case self (attribute infoTree) of UHA_Expr e -> make e _ -> Blk info where info = attribute infoTree aexprs = map makeAExpr (children infoTree) make :: Expression -> AExpr LocalInfo make expression = case expression of Expression_If{} -> case aexprs of [ae1, ae2, ae3] -> If info ae1 ae2 ae3 _ -> internalError "RepairSystem.hs" "makeAExpr" "Cannot make conditional" Expression_NormalApplication{} -> case aexprs of fun:a:as -> App info fun (a:as) _ -> internalError "RepairSystem.hs" "makeAExpr" "Cannot make (normal) application" Expression_List _ _ -> Lst info aexprs Expression_Variable _ name -> Var info (show name) Expression_Constructor _ name -> Var info (show name) _ -> Blk info whichEdges :: HasTypeGraph m ConstraintInfo => AExpr LocalInfo -> m [(EdgeId, ConstraintInfo)] whichEdges aexpr | isBlock aexpr = return [] | otherwise = do let vs = mapMaybe infoToVar (aexpr : subexpressions aexpr) allEdges <- mapM edgesFrom vs let edges = filter (fromTheSameLocation aexpr) (concat allEdges) rest <- mapM whichEdges (subexpressions aexpr) return (edges ++ concat rest) where infoToVar :: AExpr LocalInfo -> Maybe VertexId infoToVar = fmap (VertexId . head . ftv) . assignedType . getInfo fromTheSameLocation :: AExpr LocalInfo -> (EdgeId, ConstraintInfo) -> Bool fromTheSameLocation aexpr (_, info) = assignedType (getInfo aexpr) == assignedType (attribute (localInfo info)) ------------------------------------------------------------------ -- This part should be in the Top library {- data AExpr info = App info (AExpr info) [AExpr info] -- ^ application node | If info (AExpr info) (AExpr info) (AExpr info) -- ^ if-then-else node | Lst info [AExpr info] -- ^ list node | Var info String -- ^ variable node | Blk info -- ^ unmutable block node deriving Show getInfo :: AExpr info -> info getInfo (App info _ _) = info getInfo (If info _ _ _) = info getInfo (Lst info _) = info getInfo (Var info _) = info getInfo (Blk info) = info getInfos :: AExpr info -> [info] getInfos aexpr = getInfo aexpr : concatMap getInfos (subexpressions aexpr) instance Functor AExpr where fmap f aexpr = case aexpr of App a fun args -> App (f a) (fmap f fun) (map (fmap f) args) If a e1 e2 e3 -> If (f a) (fmap f e1) (fmap f e2) (fmap f e3) Lst a elts -> Lst (f a) (map (fmap f) elts) Var a s -> Var (f a) s Blk a -> Blk (f a) mapAExprM :: Monad m => (a -> m b) -> AExpr a -> m (AExpr b) mapAExprM f aexpr = case aexpr of App a fun args -> do b <- f a fun' <- mapAExprM f fun args' <- mapM (mapAExprM f) args return (App b fun' args') If a e1 e2 e3 -> do b <- f a e1' <- mapAExprM f e1 e2' <- mapAExprM f e2 e3' <- mapAExprM f e3 return (If b e1' e2' e3') Lst a elts -> do b <- f a elts' <- mapM (mapAExprM f) elts return (Lst b elts') Var a s -> do b <- f a return (Var b s) Blk a -> do b <- f a return (Blk b) subexpressions :: AExpr a -> [AExpr a] subexpressions aexpr = case aexpr of App _ fun args -> fun : args If _ e1 e2 e3 -> [e1, e2, e3] Lst _ elts -> elts Var _ _ -> [] Blk _ -> [] isBlock :: AExpr a -> Bool isBlock (Blk _) = True isBlock _ = False -}
Helium4Haskell/helium
src/Helium/StaticAnalysis/Heuristics/RepairSystem.hs
gpl-3.0
7,508
0
20
2,287
1,503
746
757
-1
-1
{-# LANGUAGE GeneralizedNewtypeDeriving, DisambiguateRecordFields, NamedFieldPuns, StandaloneDeriving, FlexibleContexts, NoMonomorphismRestriction, FlexibleInstances, BangPatterns, MultiParamTypeClasses, TypeSynonymInstances, DeriveGeneric, TemplateHaskell, DeriveDataTypeable, OverlappingInstances #-} module CommonTypes where import Object import BasicTypes import Data.Array.IArray import Data.Array.Unboxed import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import LocationMap --import qualified LocationMap as Loc import Data.Int (Int64) import Data.Accessor ((^:), (^=)) import Data.Accessor.Template import System.Random import Control.Monad.State.Strict (StateT, runStateT, evalStateT) import Control.Monad.State.Class (get, put) import Control.Monad.Reader (ReaderT, runReaderT) import Control.Monad.Reader.Class (ask, asks) import Control.Monad.Random (runRandT, RandT, MonadRandom) import Control.Monad.Random.Class (getRandom, getRandoms, getRandomR, getRandomRs) import Control.Monad.Trans (lift, MonadIO) import Control.Arrow (first) import Data.Typeable import Data.YamlObject (ToYaml, FromYaml, FromYamlM, fromYaml, TranslateField (..)) import qualified Data.Text as Text import Tile import DataUtil (copyArray) import UI.HSCurses.Curses (Key (..)) import CursesWrap (StyledChar, Style, ColorName) import Control.Monad.Identity import Control.Monad.Random import GHC.Generics (Generic) data Facing = N | NE | E | SE | S | SW | W | NW deriving (Eq, Ord, Show, Read, Enum, Bounded) newtype GameT m a = GameT { runGame :: ReaderT GameConfig (StateT GameState (RandT StdGen m)) a } deriving (Monad, Functor, MonadIO) instance Monad m => MonadSplit StdGen (GameT m) where getSplit = GameT (lift . lift $ getSplit) type PureGame a = GameT Identity a gGlobal = GameT get pGlobal = GameT . put askGlobal = GameT ask asksGlobal = GameT . asks runGameT (GameT a) g s c = runRandT (runStateT (runReaderT a c) s) g evalGameT a g s c = fst `fmap` fst `fmap` runGameT a g s c -- evalGameT, taking the game state and game config from the enclosing state, and using a static RNG. Basically, "do this thing, but just get the return value and ignore its changes to the game state" try (GameT a) = do gamestate <- gGlobal gameconfig <- askGlobal evalRandT (evalStateT (runReaderT a gameconfig) gamestate) (mkStdGen 0) instance Monad m => MonadRandom (GameT m) where getRandom = GameT $ lift $ lift getRandom getRandoms = GameT $ lift $ lift getRandoms getRandomR = GameT . lift . lift . getRandomR getRandomRs = GameT . lift . lift . getRandomRs type Levels = Map LevelRef Level type World = Array Coord Tile type References = Map ObjRef Object type Positions = LocationMap ObjRef Location type Remembered = Array Coord Char type Explored = Array Coord Bool type Visible = Set Coord type Initiative = Int -- Dunno why this instance or something like it doesn't exist by default -- todo: put somewhere else instance (Ix i, Read i, Read e, IArray UArray e) => Read (UArray i e) where readsPrec precedence input = map (first copyArray) $ (readsPrec :: (Ix i, Read i, Read e) => Int -> String -> [(Array i e, String)]) precedence input data GameConfig = GameConfig { keyBindings_ :: [(Key, KeyAction)] , furniturePrototypes_ :: Map String FurniturePrototype , rangedWeaponPrototypes_ :: Map String RangedWeaponPrototype } data KeyAction = North | Northwest | West | Southwest | South | Southeast | East | Northeast | StayInPlace | UseFocusSlot Int | MenuPrevious | MenuNext | MenuPrevPage | MenuNextPage | MenuSelect | MenuFinish | QuitGame | SaveGame deriving (Show, Read, Eq) {- One of the annoying downsides of Haskell is that it can be difficult to track down space leaks. The fortunate thing is that at *least* you know everything that's leaked for longer than a turn must have a reference from GameState - all other stuff is either garbage collected or immutable. Therefore, it's enough to just ensure that all parts of GameState are treated in a way that prevents space leaks. Possible future direction: Un-export the GameState constructor and record accessors, force all mutation of GameState to go through an interface that ensures strictness. -} data GameState = GameState { levels_ :: Levels -- only mutated through strictness-ensuring interface defined in LocationMap.hs , positions_ :: Positions -- only mutated through strictness-ensuring interface Game.touch , references_ :: References -- trivial , firstUnusedId_ :: ObjRef -- trivial , currentTurn_ :: Time -- emptied regularly , messages_ :: [String] -- trivial , turnDone_ :: Bool -- trivial , doQuit_ :: Bool } deriving (Show, Typeable, Generic) data Flinged = Flinged { flingedObject_ :: ObjRef , flingedPath_ :: [Coord] -- flingedProgress_ == maxBound is currently special, meaning the fling is "done" , flingedProgress_ :: Int } deriving (Show, Typeable, Generic) data Level = Level { -- currently never mutated world_ :: Array Coord Tile -- currently never mutated , compounds_ :: Compounds -- unboxed array , playerExplored_ :: !Explored -- emptied regularly , playerVisible_ :: !Visible -- unboxed array , playerRemembered_ :: !Remembered -- emptied regularly , flinged_ :: [Flinged] -- todo: this and possibly some other ones are really more generally interface-related data and should be made ephemeral } deriving (Show, Typeable, Generic) type Time = Int data IdlingType = UseWorkstation | GetStuffOnShelf deriving (Show, Read, Eq, Typeable, Generic) data IdlingPoint = IdlingPoint { ipIdlingType_ :: IdlingType , ipLocation_ :: Coord } deriving (Show, Read, Eq, Typeable, Generic) instance TranslateField IdlingPoint where translateField _ = Text.init newtype CompoundRef = CompoundRef Int deriving (Show, Read, Eq, Ord, Enum, Typeable, Generic) data Compounds = Compounds { compoundsCoords_ :: Array Coord CompoundRef , compoundsRefs_ :: Map CompoundRef Compound } deriving (Show, Read, Typeable, Generic) data Compound = Compound { compoundRooms_ :: [BoundsRect] , idlingPoints_ :: [IdlingPoint] } deriving (Show, Read, Typeable, Generic) $( deriveAccessors ''GameState ) $( deriveAccessors ''GameConfig ) $( deriveAccessors ''Level ) $( deriveAccessors ''Flinged ) $( deriveAccessors ''IdlingPoint ) mGlobal f = do s <- gGlobal pGlobal (f s) gsGlobal f = do s <- gGlobal return $ f s gLevel l = (Map.! l) `fmap` levels_ `fmap` gGlobal gsLevel l f = f `fmap` gLevel l mLevel l f = mGlobal (levels ^: Map.adjust f l) pLevel l x = mGlobal (levels ^: Map.insert l x) instance Random Facing where random = (\(a, g) -> (toEnum a, g)) . randomR (fromEnum (minBound :: Facing), fromEnum (maxBound :: Facing)) randomR (s, e) g = (\(a, g) -> (toEnum a, g)) $ randomR (fromEnum s, fromEnum e) g instance FromYaml GameState instance FromYaml Level instance FromYaml Object instance FromYaml Tile instance FromYaml Compounds instance FromYaml Flinged instance FromYaml AIState instance FromYaml RangedWeaponPrototype instance FromYaml FurniturePrototype instance FromYaml RubbleMaterial instance FromYaml Location instance FromYaml StyledChar instance FromYaml Style instance FromYaml ColorName instance FromYaml CompoundRef instance FromYaml Compound instance FromYaml IdlingPoint instance FromYaml IdlingType instance ToYaml GameState instance ToYaml Level instance ToYaml Object instance ToYaml Tile instance ToYaml Compounds instance ToYaml Flinged instance ToYaml AIState instance ToYaml RangedWeaponPrototype instance ToYaml FurniturePrototype instance ToYaml RubbleMaterial instance ToYaml Location instance ToYaml StyledChar instance ToYaml Style instance ToYaml ColorName instance ToYaml CompoundRef instance ToYaml Compound instance ToYaml IdlingPoint instance ToYaml IdlingType instance (Show ml, Show mr, Typeable ml, Typeable mr, Ord ml, Ord mr, ToYaml ml, ToYaml mr) => ToYaml (LocationMap ml mr) instance (Read ml, Read mr, Typeable ml, Typeable mr, Ord ml, Ord mr, FromYaml ml, FromYaml mr) => FromYaml (LocationMap ml mr)
arirahikkala/straylight-divergence
src/CommonTypes.hs
gpl-3.0
8,346
0
14
1,569
2,227
1,219
1,008
179
1
{-# LANGUAGE BangPatterns , FlexibleInstances , MagicHash , MultiParamTypeClasses , RecordWildCards , ViewPatterns #-} {-# LANGUAGE Trustworthy #-} -- | Clause, supporting pointer-based equality module SAT.Mios.Clause ( Clause (..) -- , isLit -- , getLit , newClauseFromStack -- * Vector of Clause , ClauseVector , lenClauseVector ) where import GHC.Prim (tagToEnum#, reallyUnsafePtrEquality#) import qualified Data.Vector as V import qualified Data.Vector.Mutable as MV import SAT.Mios.Types -- | __Fig. 7.(p.11)__ -- normal, null (and binary) clause. -- This matches both of @Clause@ and @GClause@ in MiniSat. data Clause = Clause { learnt :: !Bool -- ^ whether this is a learnt clause -- , rank :: !Int' -- ^ goodness like LBD; computed in 'Ranking' , activity :: !Double' -- ^ activity of this clause , protected :: !Bool' -- ^ protected from reduce , lits :: !Stack -- ^ which this clause consists of } | NullClause -- as null pointer -- | BinaryClause Lit -- binary clause consists of only a propagating literal -- | The equality on 'Clause' is defined with 'reallyUnsafePtrEquality'. instance Eq Clause where {-# SPECIALIZE INLINE (==) :: Clause -> Clause -> Bool #-} (==) x y = x `seq` y `seq` tagToEnum# (reallyUnsafePtrEquality# x y) instance Show Clause where show NullClause = "NullClause" show _ = "a clause" -- | 'Clause' is a 'VecFamily' of 'Lit'. instance VecFamily Clause Lit where {-# SPECIALIZE INLINE getNth :: Clause -> Int -> IO Int #-} getNth Clause{..} n = errorWithoutStackTrace "no getNth for Clause" {-# SPECIALIZE INLINE setNth :: Clause -> Int -> Int -> IO () #-} setNth Clause{..} n x = errorWithoutStackTrace "no setNth for Clause" -- | returns a vector of literals in it. asList NullClause = return [] asList Clause{..} = take <$> get' lits <*> asList lits {- dump mes NullClause = return $ mes ++ "Null" dump mes Clause{..} = do let intercalate p l = if null l then [] else (head l) ++ foldl (\l' x -> l' ++ p ++ x) [] (tail l) a <- show <$> get' activity n <- get' lits l <- asList lits return $ mes ++ "C" ++ show n ++ "{" ++ intercalate "," [show learnt, a, show (map lit2int l)] ++ "}" -} -- | 'Clause' is a 'SingleStorage' on the number of literals in it. instance SingleStorage Clause Int where -- | returns the number of literals in a clause, even if the given clause is a binary clause {-# SPECIALIZE INLINE get' :: Clause -> IO Int #-} get' = get' . lits -- getSize (BinaryClause _) = return 1 -- | sets the number of literals in a clause, even if the given clause is a binary clause {-# SPECIALIZE INLINE set' :: Clause -> Int -> IO () #-} set' c n = set' (lits c) n -- getSize (BinaryClause _) = return 1 -- | 'Clause' is a 'Stackfamily'on literals since literals in it will be discared if satisifed at level = 0. instance StackFamily Clause Lit where -- | drop the last /N/ literals in a 'Clause' to eliminate unsatisfied literals {-# SPECIALIZE INLINE shrinkBy :: Clause -> Int -> IO () #-} shrinkBy c n = modifyNth (lits c) (subtract n) 0 -- returns True if it is a 'BinaryClause'. -- FIXME: this might be discarded in minisat 2.2 -- isLit :: Clause -> Bool -- isLit (BinaryClause _) = True -- isLit _ = False -- returns the literal in a BinaryClause. -- FIXME: this might be discarded in minisat 2.2 -- getLit :: Clause -> Lit -- getLit (BinaryClause x) = x -- coverts a binary clause to normal clause in order to reuse map-on-literals-in-a-clause codes. -- liftToClause :: Clause -> Clause -- liftToClause (BinaryClause _) = errorWithoutStackTrace "So far I use generic function approach instead of lifting" -- | copies /vec/ and return a new 'Clause'. -- Since 1.0.100 DIMACS reader should use a scratch buffer allocated statically. {-# INLINABLE newClauseFromStack #-} newClauseFromStack :: Bool -> Stack -> IO Clause newClauseFromStack l vec = do n <- get' vec v <- newStack n let loop ((<= n) -> False) = return () loop i = (setNth v i =<< getNth vec i) >> loop (i + 1) loop 0 Clause l <$> {- new' 0 <*> -} new' 0.0 <*> new' False <*> return v -------------------------------------------------------------------------------- Clause Vector -- | Mutable 'Clause' Vector type ClauseVector = MV.IOVector Clause -- | 'ClauseVector' is a vector of 'Clause'. instance VecFamily ClauseVector Clause where {-# SPECIALIZE INLINE getNth :: ClauseVector -> Int -> IO Clause #-} getNth = MV.unsafeRead {-# SPECIALIZE INLINE setNth :: ClauseVector -> Int -> Clause -> IO () #-} setNth = MV.unsafeWrite {-# SPECIALIZE INLINE swapBetween :: ClauseVector -> Int -> Int -> IO () #-} swapBetween = MV.unsafeSwap newVec n c = do v <- MV.new n MV.set v c return v asList cv = V.toList <$> V.freeze cv {- dump mes cv = do l <- asList cv sts <- mapM (dump ",") (l :: [Clause]) return $ mes ++ tail (concat sts) -} lenClauseVector :: ClauseVector -> Int lenClauseVector = MV.length
shnarazk/mios
MultiConflict/SAT/Mios/Clause.hs
gpl-3.0
5,229
0
13
1,273
655
363
292
77
2
{- The authors of this work have released all rights to it and placed it in the public domain under the Creative Commons CC0 1.0 waiver (http://creativecommons.org/publicdomain/zero/1.0/). 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. Retrieved from: http://en.literateprograms.org/Sieve_of_Eratosthenes_(Haskell)?oldid=19210 -} module Main where merge :: (Ord a) => [a] -> [a] -> [a] merge xs@(x:xt) ys@(y:yt) = case compare x y of LT -> x : (merge xt ys) EQ -> x : (merge xt yt) GT -> y : (merge xs yt) diff :: (Ord a) => [a] -> [a] -> [a] diff xs@(x:xt) ys@(y:yt) = case compare x y of LT -> x : (diff xt ys) EQ -> diff xt yt GT -> diff xs yt primes, nonprimes :: [Integer] primes = [2, 3, 5] ++ (diff [7, 9 ..] nonprimes) nonprimes = foldr1 f $ map g $ tail primes where f (x:xt) ys = x : (merge xt ys) g p = [ n * p | n <- [p, p + 2 ..]] main :: IO () main = do putStrLn "Which prime do you want?" inputjar <- readLn print $ show (primes !! (inputjar :: Int))
dkensinger/haskell
prime_sieve_better_test.hs
gpl-3.0
1,494
0
11
374
420
225
195
23
3
module Pipes.DSP.ReferenceSignals where import Pipes import qualified Pipes.Prelude as P type Time = Double type SignalValue = Double type FreqHz = Double type Coef = Double type Phase = Double -- |Signal producer signalP :: Monad m => (Time -> SignalValue) -- ^ x(t) -> FreqHz -- ^ Sampling Frequency (Hz) -> Producer SignalValue m () signalP fn freq = each [0..] >-> P.map (fn . (* dt)) where dt = 1 / freq -- |Signal producer renamed for infix use -- (ie (simpleOscillator 100 pi) `sampledAt` 100) sampledAt :: Monad m => (Time -> SignalValue) -- ^ x(t) -> FreqHz -- ^ Sampling Frequency (Hz) -> Producer SignalValue m () sampledAt = signalP -- |Produce values sampled from the function along with the sampling -- times (useful for plotting) signalWithTime :: Monad m => (Time -> SignalValue) -> FreqHz -> Producer (Time,SignalValue) m () signalWithTime fn freq = (each [0..]) >-> P.map (\n -> (n*dt, fn(n*dt))) where dt = 1 / freq simpleOscillator :: Coef -- ^ amplitude -> FreqHz -- ^ frequency -> Phase -- ^ phase offset -> (Time -> SignalValue) -- ^ x(t) simpleOscillator a freq p = \t -> a * cos(2*pi*freq*t - p) sawtoothWave :: Coef -- ^ amplitude -> FreqHz -- ^ frequency -> Time -- ^ time offset -> (Time -> SignalValue) -- ^ x(t) sawtoothWave a f t0 = \t -> a * 2 * ((t-t0)*f - (fromIntegral . (floor :: Double -> Int) ) (0.5 + (t-t0)*f))
imalsogreg/pipes-dsp
src/Pipes/DSP/ReferenceSignals.hs
gpl-3.0
1,597
0
14
493
470
264
206
37
1
{- The Delve Programming Language Copyright 2009 John Morrice Distributed under the terms of the GNU General Public License v3, or ( at your option ) any later version. This file is part of Delve. Delve 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 3 of the License, or (at your option) any later version. Delve 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 Delve. If not, see <http://www.gnu.org/licenses/>. -} module VirtualMachineExtension where import Data.ByteString.Char8 import DMachineState import DHelper import DelveVM import Data.Map as M import DHelper import DHelper import Foreign.Marshal.Alloc import Foreign.Ptr import DHelper import DelveVM import Data.ByteString.Char8 as B import qualified Data.Map as M bytecode = [NewBlock [MachineInstruction _V_n], AssignLocal 0 [] (pack "stats"), NewBlock [MachineInstruction _V_o], AssignLocal 0 [] (pack "current"), NewBlock [MachineInstruction _V_p], AssignLocal 0 [] (pack "print_obj"), NewBlock [MachineInstruction _V_q], AssignLocal 0 [] (pack "mk_obj"), CallLocal 0 [(pack "mk_obj")], AssignLocal 0 [] (pack "Object"), RefLocal 0 [(pack "mk_obj")], AssignLocal 0 [(pack "Object")] (pack "new"), LoadLocal 0 [(pack "Object")], CallObj [(pack "new")], PopObject, AssignLocal 0 [] (pack "Symbol"), LoadLocal 0 [(pack "Object")], CallObj [(pack "new")], PopObject, AssignLocal 0 [(pack "Symbol")] (pack "instance_methods"), NewBlock [PushLocal, WriteArg 0 (pack "s"), RefLocal 0 [(pack "s")], AssignObject [] (pack "prim"), PopFrame], AssignLocal 0 [] (pack "_V_ac"), RememberLocalLocal 0 [(pack "_V_ac")], AssignLocal 0 [(pack "Symbol"), (pack "instance_methods")] (pack "initialize"), NewBlock [PushLocal, NewBlock [MachineInstruction _V_r], AssignLocal 0 [] (pack "_V_m"), PushObjArg [(pack "prim")] 0, FrameTailCallLocal 0 [(pack "_V_m")]], AssignLocal 0 [] (pack "_V_ad"), RememberLocalLocal 0 [(pack "_V_ad")], AssignLocal 0 [(pack "Symbol"), (pack "instance_methods")] (pack "print"), NewBlock [PushLocal, WriteArg 0 (pack "x"), LoadLocal 1 [(pack "Object")], CallObj [(pack "new")], PopObject, AssignLocal 0 [] (pack "instance"), RefSelf, AssignLocal 0 [(pack "instance")] (pack "class"), PushLocalArg 0 [(pack "x")] 0, LoadLocal 0 [(pack "instance")], CallObj [(pack "initialize")], PopObject, RefLocal 0 [(pack "instance")], PopFrame], AssignLocal 0 [] (pack "_V_ae"), RememberLocalLocal 0 [(pack "_V_ae")], AssignLocal 0 [(pack "Symbol")] (pack "new"), LoadLocal 0 [(pack "Object")], CallObj [(pack "new")], PopObject, AssignLocal 0 [] (pack "Bool"), LoadLocal 0 [(pack "Object")], CallObj [(pack "new")], PopObject, AssignLocal 0 [(pack "Bool")] (pack "instance_methods"), NewBlock [PushLocal, WriteArg 0 (pack "sym"), LoadLocal 1 [(pack "Object")], CallObj [(pack "new")], PopObject, AssignLocal 0 [] (pack "instance"), RefSelf, AssignLocal 0 [(pack "instance")] (pack "class"), PushLocalArg 0 [(pack "sym")] 0, LoadLocal 1 [(pack "Symbol")], CallObj [(pack "new")], PopObject, AssignLocal 0 [] (pack "_V_l"), PushLocalArg 0 [(pack "_V_l")] 0, LoadLocal 0 [(pack "instance")], CallObj [(pack "initialize")], PopObject, RefLocal 0 [(pack "instance")], PopFrame], AssignLocal 0 [] (pack "_V_af"), RememberLocalLocal 0 [(pack "_V_af")], AssignLocal 0 [(pack "Bool")] (pack "new"), NewBlock [PushLocal, WriteArg 0 (pack "sym"), RefLocal 0 [(pack "sym")], AssignObject [] (pack "sym"), PopFrame], AssignLocal 0 [] (pack "_V_ag"), RememberLocalLocal 0 [(pack "_V_ag")], AssignLocal 0 [(pack "Bool"), (pack "instance_methods")] (pack "initialize"), NewSymbol (pack "False"), AssignLocal 0 [] (pack "_V_k"), PushLocalArg 0 [(pack "_V_k")] 0, LoadLocal 0 [(pack "Bool")], CallObj [(pack "new")], PopObject, AssignLocal 0 [] (pack "False"), NewSymbol (pack "True"), AssignLocal 0 [] (pack "_V_j"), PushLocalArg 0 [(pack "_V_j")] 0, LoadLocal 0 [(pack "Bool")], CallObj [(pack "new")], PopObject, AssignLocal 0 [] (pack "True"), NewBlock [PushLocal, MatchObj [(pack "sym"), (pack "prim")] [((pack "True"), [PushLocal, RefLocal 2 [(pack "False")], PopFrame]), ((pack "False"), [PushLocal, RefLocal 2 [(pack "True")], PopFrame])]], AssignLocal 0 [] (pack "_V_ah"), RememberLocalLocal 0 [(pack "_V_ah")], AssignLocal 0 [(pack "Bool"), (pack "instance_methods")] (pack "not"), NewBlock [PushLocal, WriteArg 0 (pack "other"), MatchObj [(pack "sym"), (pack "prim")] [((pack "True"), [PushLocal, MatchLocal 1 [(pack "other"), (pack "sym"), (pack "prim")] [((pack "True"), [PushLocal, RefLocal 3 [(pack "False")], PopFrame]), ((pack "False"), [PushLocal, RefLocal 3 [(pack "True")], PopFrame])]]), ((pack "False"), [PushLocal, RefLocal 2 [(pack "True")], PopFrame])]], AssignLocal 0 [] (pack "_V_ai"), RememberLocalLocal 0 [(pack "_V_ai")], AssignLocal 0 [(pack "Bool"), (pack "instance_methods")] (pack "nand"), NewBlock [PushLocal, WriteArg 0 (pack "other"), PushLocalArg 0 [(pack "other")] 0, CallObj [(pack "nand")], AssignLocal 0 [] (pack "n"), LoadLocal 0 [(pack "n")], FrameTailCallObj [(pack "not")]], AssignLocal 0 [] (pack "_V_aj"), RememberLocalLocal 0 [(pack "_V_aj")], AssignLocal 0 [(pack "Bool"), (pack "instance_methods")] (pack "and"), NewBlock [PushLocal, WriteArg 0 (pack "q"), PushLocalArg 1 [(pack "True")] 0, CallObj [(pack "nand")], AssignLocal 0 [] (pack "ntp"), PushLocalArg 1 [(pack "True")] 0, LoadLocal 0 [(pack "q")], CallObj [(pack "nand")], PopObject, AssignLocal 0 [] (pack "ntq"), PushLocalArg 0 [(pack "ntq")] 0, LoadLocal 0 [(pack "ntp")], FrameTailCallObj [(pack "nand")]], AssignLocal 0 [] (pack "_V_ak"), RememberLocalLocal 0 [(pack "_V_ak")], AssignLocal 0 [(pack "Bool"), (pack "instance_methods")] (pack "or"), NewBlock [PushLocal, LoadObj [(pack "sym")], FrameTailCallObj [(pack "print")]], AssignLocal 0 [] (pack "_V_al"), RememberLocalLocal 0 [(pack "_V_al")], AssignLocal 0 [(pack "Bool"), (pack "instance_methods")] (pack "print"), LoadLocal 0 [(pack "Object")], CallObj [(pack "new")], PopObject, AssignLocal 0 [] (pack "Int"), LoadLocal 0 [(pack "Object")], CallObj [(pack "new")], PopObject, AssignLocal 0 [(pack "Int")] (pack "instance_methods"), NewBlock [PushLocal, WriteArg 0 (pack "prim"), RefLocal 0 [(pack "prim")], AssignObject [] (pack "prim"), PopFrame], AssignLocal 0 [] (pack "_V_am"), RememberLocalLocal 0 [(pack "_V_am")], AssignLocal 0 [(pack "Int"), (pack "instance_methods")] (pack "initialize"), NewBlock [PushLocal, WriteArg 0 (pack "other"), NewBlock [MachineInstruction _V_s], AssignLocal 0 [] (pack "machine_addition"), PushObjArg [(pack "prim")] 0, PushLocalArg 0 [(pack "other"), (pack "prim")] 1, CallLocal 0 [(pack "machine_addition")], AssignLocal 0 [] (pack "p"), PushLocalArg 0 [(pack "p")] 0, LoadLocal 1 [(pack "Int")], FrameTailCallObj [(pack "new")]], AssignLocal 0 [] (pack "_V_an"), RememberLocalLocal 0 [(pack "_V_an")], AssignLocal 0 [(pack "Int"), (pack "instance_methods")] (pack "+"), NewBlock [PushLocal, WriteArg 0 (pack "other"), NewBlock [MachineInstruction _V_t], AssignLocal 0 [] (pack "machine_subtraction"), PushObjArg [(pack "prim")] 0, PushLocalArg 0 [(pack "other"), (pack "prim")] 1, CallLocal 0 [(pack "machine_subtraction")], AssignLocal 0 [] (pack "_V_i"), PushLocalArg 0 [(pack "_V_i")] 0, LoadLocal 1 [(pack "Int")], FrameTailCallObj [(pack "new")]], AssignLocal 0 [] (pack "_V_ao"), RememberLocalLocal 0 [(pack "_V_ao")], AssignLocal 0 [(pack "Int"), (pack "instance_methods")] (pack "-"), NewBlock [PushLocal, WriteArg 0 (pack "other"), NewBlock [MachineInstruction _V_u], AssignLocal 0 [] (pack "machine_lte"), PushObjArg [(pack "prim")] 0, PushLocalArg 0 [(pack "other"), (pack "prim")] 1, CallLocal 0 [(pack "machine_lte")], AssignLocal 0 [] (pack "_V_h"), PushLocalArg 0 [(pack "_V_h")] 0, LoadLocal 1 [(pack "Bool")], FrameTailCallObj [(pack "new")]], AssignLocal 0 [] (pack "_V_ap"), RememberLocalLocal 0 [(pack "_V_ap")], AssignLocal 0 [(pack "Int"), (pack "instance_methods")] (pack "<="), NewBlock [PushLocal, WriteArg 0 (pack "other"), NewBlock [MachineInstruction _V_v], AssignLocal 0 [] (pack "machine_eq"), PushObjArg [(pack "prim")] 0, PushLocalArg 0 [(pack "other"), (pack "prim")] 1, CallLocal 0 [(pack "machine_eq")], AssignLocal 0 [] (pack "_V_g"), PushLocalArg 0 [(pack "_V_g")] 0, LoadLocal 1 [(pack "Bool")], FrameTailCallObj [(pack "new")]], AssignLocal 0 [] (pack "_V_aq"), RememberLocalLocal 0 [(pack "_V_aq")], AssignLocal 0 [(pack "Int"), (pack "instance_methods")] (pack "="), NewBlock [PushLocal, WriteArg 0 (pack "other"), PushLocalArg 0 [(pack "other")] 0, CallObj [(pack "<=")], AssignLocal 0 [] (pack "lte"), LoadLocal 0 [(pack "lte")], FrameTailCallObj [(pack "not")]], AssignLocal 0 [] (pack "_V_ar"), RememberLocalLocal 0 [(pack "_V_ar")], AssignLocal 0 [(pack "Int"), (pack "instance_methods")] (pack ">"), NewBlock [PushLocal, WriteArg 0 (pack "other"), PushLocalArg 0 [(pack "other")] 0, CallObj [(pack ">")], AssignLocal 0 [] (pack "gt"), PushLocalArg 0 [(pack "other")] 0, CallObj [(pack "=")], AssignLocal 0 [] (pack "_V_f"), PushLocalArg 0 [(pack "_V_f")] 0, LoadLocal 0 [(pack "gt")], FrameTailCallObj [(pack "or")]], AssignLocal 0 [] (pack "_V_as"), RememberLocalLocal 0 [(pack "_V_as")], AssignLocal 0 [(pack "Int"), (pack "instance_methods")] (pack ">="), NewBlock [PushLocal, WriteArg 0 (pack "other"), PushLocalArg 0 [(pack "other")] 0, CallObj [(pack "<=")], AssignLocal 0 [] (pack "lte"), PushLocalArg 0 [(pack "other")] 0, CallObj [(pack "=")], AssignLocal 0 [] (pack "eq"), LoadLocal 0 [(pack "eq")], CallObj [(pack "not")], PopObject, AssignLocal 0 [] (pack "_V_e"), PushLocalArg 0 [(pack "_V_e")] 0, LoadLocal 0 [(pack "lte")], FrameTailCallObj [(pack "and")]], AssignLocal 0 [] (pack "_V_at"), RememberLocalLocal 0 [(pack "_V_at")], AssignLocal 0 [(pack "Int"), (pack "instance_methods")] (pack "<"), NewBlock [PushLocal, WriteArg 0 (pack "other"), NewBlock [MachineInstruction _V_w], AssignLocal 0 [] (pack "_V_d"), PushObjArg [(pack "prim")] 0, PushLocalArg 0 [(pack "other"), (pack "prim")] 1, FrameTailCallLocal 0 [(pack "_V_d")]], AssignLocal 0 [] (pack "_V_au"), RememberLocalLocal 0 [(pack "_V_au")], AssignLocal 0 [(pack "Int"), (pack "instance_methods")] (pack "*"), NewBlock [PushLocal, WriteArg 0 (pack "other"), NewBlock [MachineInstruction _V_x], AssignLocal 0 [] (pack "_V_c"), PushObjArg [(pack "prim")] 0, PushLocalArg 0 [(pack "other"), (pack "prim")] 1, FrameTailCallLocal 0 [(pack "_V_c")]], AssignLocal 0 [] (pack "_V_av"), RememberLocalLocal 0 [(pack "_V_av")], AssignLocal 0 [(pack "Int"), (pack "instance_methods")] (pack "/"), NewBlock [PushLocal, WriteArg 0 (pack "other"), NewBlock [MachineInstruction _V_y], AssignLocal 0 [] (pack "_V_b"), PushObjArg [(pack "prim")] 0, PushLocalArg 0 [(pack "other"), (pack "prim")] 1, FrameTailCallLocal 0 [(pack "_V_b")]], AssignLocal 0 [] (pack "_V_aw"), RememberLocalLocal 0 [(pack "_V_aw")], AssignLocal 0 [(pack "Int"), (pack "instance_methods")] (pack "^"), NewBlock [PushLocal, NewBlock [MachineInstruction _V_z], AssignLocal 0 [] (pack "machine_print"), PushObjArg [(pack "prim")] 0, FrameTailCallLocal 0 [(pack "machine_print")]], AssignLocal 0 [] (pack "_V_ax"), RememberLocalLocal 0 [(pack "_V_ax")], AssignLocal 0 [(pack "Int"), (pack "instance_methods")] (pack "print"), NewBlock [PushLocal, WriteArg 0 (pack "prim"), LoadLocal 1 [(pack "Object")], CallObj [(pack "new")], PopObject, AssignLocal 0 [] (pack "instance"), RefSelf, AssignLocal 0 [(pack "instance")] (pack "class"), PushLocalArg 0 [(pack "prim")] 0, LoadLocal 0 [(pack "instance")], CallObj [(pack "initialize")], PopObject, RefLocal 0 [(pack "instance")], PopFrame], AssignLocal 0 [] (pack "_V_ay"), RememberLocalLocal 0 [(pack "_V_ay")], AssignLocal 0 [(pack "Int")] (pack "new"), NewBlock [PushLocal, WriteArg 0 (pack "exec"), NewBlock [MachineInstruction _V_aa], AssignLocal 0 [] (pack "machine_call/cc"), NewBlock [MachineInstruction _V_ab], AssignLocal 0 [] (pack "_V_a"), CallLocal 0 [(pack "_V_a")], PushLocalArg 0 [(pack "exec")] 0, FrameTailCallLocal 0 [(pack "machine_call/cc")]], AssignLocal 0 [] (pack "_V_az"), RememberLocalLocal 0 [(pack "_V_az")], RememberObjLocal 0 [(pack "_V_az")], AssignLocal 0 [] (pack "call/cc")] _V_n = stats _V_o = do o <- get_current_object liftIO $ Prelude.putStrLn "Current object:" liftIO $ Prelude.putStrLn $ show $ M.keys $ members o _V_p = do a <- get_arg 0 liftIO $ do o <- readIORef $ get_object a Prelude.putStrLn "An Object:" Prelude.putStrLn $ show $ M.keys $ members o _V_q = new _V_r = print_sym _V_s = add_ints _V_t = subtract_ints _V_u = primative_lte _V_v = primative_eq _V_w = primative_mult _V_x = primative_div _V_y = primative_pow _V_z = print_int _V_aa = let jumper = B.singleton 'j' cont = B.singleton 'c' result = B.singleton 'r' exec = B.singleton 'e' call = [PushLocal, WriteArg 0 exec, CallCC [PushLocal, WriteArg 0 cont, NewBlock [WriteArg 0 result, RefLocal 0 [result], JumpLocal 0 [cont]], AssignLocal 0 [] jumper, RememberLocalLocal 0 [jumper], PushLocalArg 0 [jumper] 0, LocalTailCallLocal False 1 [exec]], PopLocal] in push_code $! call _V_ab = stats
elginer/Delve
src/VirtualMachineExtension.hs
gpl-3.0
15,459
0
19
3,821
6,128
3,227
2,901
324
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE IncoherentInstances #-} {-# LANGUAGE DeriveGeneric #-} module Test.QuickFuzz.Gen.Code.Go where import Data.Default import Test.QuickCheck import Control.DeepSeq import Control.Monad import Control.Monad.Trans import Control.Monad.Trans.State import Data.List import Language.Go.Syntax.AST import Language.Go.Pretty import Text.PrettyPrint (render) import Test.QuickFuzz.Derive.Arbitrary import Test.QuickFuzz.Derive.Fixable import Test.QuickFuzz.Derive.Show import Test.QuickFuzz.Derive.NFData import Test.QuickFuzz.Gen.FormatInfo import Test.QuickFuzz.Gen.Base.ByteString import Test.QuickFuzz.Gen.Base.String import qualified Data.ByteString.Lazy.Char8 as L8 devArbitrary ''GoSource devNFData ''GoSource goInfo :: FormatInfo GoSource NoActions goInfo = def { encode = L8.pack . render . pretty , random = arbitrary , value = show , ext = "go" }
CIFASIS/QuickFuzz
src/Test/QuickFuzz/Gen/Code/Go.hs
gpl-3.0
961
0
9
125
202
131
71
31
1
module Database.Design.Ampersand.FSpec.Switchboard (SwitchBdDiagram(..),switchboardAct,sbDiagram,processModel) where import Data.GraphViz import Data.GraphViz.Attributes.Complete import Data.List import Database.Design.Ampersand.Basics (fatalMsg,Named(..), flp) import Database.Design.Ampersand.ADL1 import Database.Design.Ampersand.Classes import Database.Design.Ampersand.Core.AbstractSyntaxTree import Database.Design.Ampersand.FSpec.FSpec import Database.Design.Ampersand.FSpec.ShowADL (ShowADL(..), LanguageDependent(..)) import Data.String --import Database.Design.Ampersand.FSpec.ShowECA (showECA) -- for testing purposes fatal :: Int -> String -> a fatal = fatalMsg "FSpec.Switchboard" data SwitchBdDiagram = SBdgrm { sbName :: String , sbdotGraph :: DotGraph String } instance Named SwitchBdDiagram where name = sbName processModel :: [Activity] -> DotGraph String processModel acts = DotGraph { strictGraph = False , directedGraph = True , graphID = Just (Str (fromString "Process Model")) , graphStatements = DotStmts { attrStmts = [GraphAttrs [{-Splines SplineEdges,-} RankDir FromLeft]] , subGraphs = [] , nodeStmts = activityNodes , edgeStmts = edges } } where activityNodes = [ DotNode { nodeID = "act_"++name a , nodeAttributes = [Style [SItem Filled []], FillColor [WC(X11Color Orange) Nothing], Label (StrLabel (fromString (name a)))] } | a<-acts] edges = nub [ DotEdge { fromNode = "act_"++name from , toNode = "act_"++name to , edgeAttributes = [Len 2, Label (StrLabel (fromString (show e++" "++name d))), Dir Forward] } | (from,to,e,d) <- allEdges ] allEdges = nub[(from,to,e,d) | (e,d,from)<-eventsOut, (e',d',to)<-eventsIn, e==e', d==d'] eventsIn = [(e,d,act) | act<-acts, eca<-actEcas act, let On e d = ecaTriggr eca] eventsOut = [(e,d,act) | act<-acts, eca<-actEcas act, (e,d)<-(nub.evs.ecaAction) eca] where evs :: PAclause -> [(InsDel,Declaration)] evs clause = case clause of CHC{} -> (concat.map evs) (paCls clause) GCH{} -> concat [ evs p | (_,_,p)<-paGCls clause] ALL{} -> (concat.map evs) (paCls clause) Do{} -> [(paSrt clause, paTo clause)] New{} -> evs (paCl clause (makePSingleton "")) Rmv{} -> evs (paCl clause (makePSingleton "")) Nop{} -> [] Blk{} -> [] Let{} -> fatal 305 "events for let undetermined" Ref{} -> fatal 306 "events for Ref undetermined" colorRule :: Rule -> X11Color colorRule r | isSignal r = Orange | otherwise = Green sbDiagram :: FSpec -> SwitchBdDiagram sbDiagram fSpec = SBdgrm { sbName = name fSpec , sbdotGraph = DotGraph { strictGraph = False , directedGraph = True , graphID = Just (Str (fromString "Switchboard")) , graphStatements = DotStmts { attrStmts = [GraphAttrs [Splines SplineEdges, RankDir FromLeft]] , subGraphs = [] , nodeStmts = inEvNodes++conjNodes++ecaNodes++outEvNods , edgeStmts = edgesEvCj++edgesCjEc++edgesEcEv } } } where fsb = fSwitchboard fSpec --DESCR -> The relations from which changes can come inEvNodes = [ DotNode { nodeID = nameINode eventsIn ev , nodeAttributes = [Label (StrLabel (fromString (show (eSrt ev)++" "++showADL (eDcl ev))))] } | ev<-eventsIn ] --DESCR -> All conjuncts conjNodes = [ DotNode { nodeID = nameCNode (fsbConjs fsb) (rul,c) , nodeAttributes = [Style [SItem Filled []], FillColor [WC(X11Color (colorRule rul)) Nothing], (Label . StrLabel . fromString . name) rul] } | (rul,c)<-fsbConjs fsb] --DESCR -> All ECA rules ecaNodes = [ DotNode { nodeID = nameENode (fsbECAs fsb) eca , nodeAttributes = if isBlk (ecaAction eca) then [Style [SItem Filled []], FillColor [WC(X11Color Red)Nothing], (Label . StrLabel . fromString) ("ERR #"++show (ecaNum eca))] else [(Label . StrLabel . fromString. showADL) eca] } | eca<-fsbECAs fsb, not (isBlk (ecaAction eca))] --DESCR -> The relations to which changes are made outEvNods = [ DotNode { nodeID = nameONode eventsOut ev , nodeAttributes = [Label (StrLabel (fromString (show (eSrt ev)++" "++showADL (eDcl ev))))] } | ev<-eventsOut ] --DESCR -> Each edge represents an insert between a relation on the left and a term on the right to which the relation contributes to an insert. edgesEvCj = [ DotEdge { fromNode = nameINode eventsIn ev , toNode = nameCNode (fsbConjs fsb) (rul,c) , edgeAttributes = [Dir Forward] } | (rul,c)<-fsbConjs fsb, ev<-eventsIn, eDcl ev `elem` relsUsedIn c] edgesCjEc = [ DotEdge { fromNode = nameCNode (fsbConjs fsb) (rul,c) , toNode = nameENode (fsbECAs fsb) eca , edgeAttributes = [Dir Forward] } | (rul,c)<-fsbConjs fsb, eca<-fsbECAs fsb, not (isBlk (ecaAction eca)), rul `elem` concat [r | (_,r)<-paMotiv (ecaAction eca)] ] edgesEcEv = nub [ DotEdge { fromNode = nameENode (fsbECAs fsb) eca , toNode = nameONode eventsOut (On tOp rel) , edgeAttributes = [Dir Forward] } | eca<-fsbECAs fsb, not (isBlk (ecaAction eca)) , On tOp rel<-eventsFrom (ecaAction eca) ] nameINode = nmLkp fSpec "in_" nameCNode = nmLkp fSpec "cj_" nameENode = nmLkp fSpec "eca_" nameONode = nmLkp fSpec "out_" eventsIn = nub [ecaTriggr eca | eca<-fsbECAs fsb, not (isBlk (ecaAction eca)) ] eventsOut = nub [evt | eca<-fsbECAs fsb, let act=ecaAction eca, not (isBlk act), evt<-eventsFrom act] switchboardAct :: FSpec -> Activity -> SwitchBdDiagram switchboardAct fSpec act = SBdgrm { sbName = name act , sbdotGraph = DotGraph { strictGraph = False , directedGraph = True , graphID = Just (Str (fromString "Switchboard")) , graphStatements = DotStmts { attrStmts = [GraphAttrs [Splines SplineEdges, RankDir FromLeft]] , subGraphs = [] , nodeStmts = inMorNodes++conjunctNodes++outMorNodes , edgeStmts = edgesIn++edgesOut } } } where fromRels = nub (actTrig act) toRels :: [Declaration] toRels = nub (actAffect act) conjuncts = nub [ (qRule q,expr) | q<-actQuads act, expr<-(map rc_conjunct . qConjuncts) q] --DESCR -> The relations from which changes can come inMorNodes = [ DotNode { nodeID = nameINode fromRels r , nodeAttributes = [Label (StrLabel (fromString (showADL r)))] } | r<-fromRels --TODOHAN , (not.null) [e |e<-edgesIn, (nodeID (fromNode e))==nameINode fromRels r] ] --DESCR -> The relations to which changes are made outMorNodes = [ DotNode { nodeID = nameONode toRels r , nodeAttributes = [Label (StrLabel (fromString (showADL r)))] } | r<-toRels --TODOHAN , (not.null) [e |e<-edgesOut, (nodeID . toNode) e==nameONode toRels r ] ] --DESCR -> All conjuncts conjunctNodes = [ DotNode { nodeID = nameCNode conjuncts (rul,c) , nodeAttributes = [Style [SItem Filled []], FillColor [WC(X11Color (colorRule rul))Nothing], Label (StrLabel (fromString (name rul)))] } | (rul,c)<-conjuncts] --DESCR -> Each edge represents an insert between a relation on the left and a term on the right to which the relation contributes to an insert. edgesIn = [ DotEdge { fromNode = nameINode fromRels r , toNode = nameCNode conjuncts (rul,c) , edgeAttributes = [Label (StrLabel (fromString (if or (positiveIn c r) then "-" else if or [not b |b<-positiveIn c r] then "+" else "+-"))) ,Dir Forward] } | (rul,c)<-conjuncts, r<-relsUsedIn c, r `elem` fromRels] edgesOut = [ DotEdge { fromNode = nameCNode conjuncts (rul,c) , toNode = nameONode toRels r , edgeAttributes = [Label (StrLabel (fromString (if or (positiveIn c r) then "+" else if or [not b |b<-positiveIn c r] then "-" else "+-"))) ,Dir Forward] } | (rul,c)<-conjuncts, r<-relsUsedIn c] nameINode :: [Declaration] -> Declaration -> String nameINode = nmLkp fSpec "in_" nameCNode = nmLkp fSpec "cj_" nameONode :: [Declaration] -> Declaration -> String nameONode = nmLkp fSpec "out_" nmLkp :: (LanguageDependent a, Eq a, ShowADL a) => FSpec -> String -> [a] -> a -> String nmLkp _ prefix xs x = head ([prefix++show (i::Int) | (i,e)<-zip [1..] xs, e==x]++ fatal 216 ("illegal lookup in nmLkp "++show prefix++": " ++showADL x++ "\nin: ["++intercalate "\n , " (map showADL xs)++"\n ]") ) positiveIn :: Expression -> Declaration -> [Bool] positiveIn expr decl = f expr -- all are True, so an insert in rel means an insert in expr where f (EEqu _) = fatal 237 "Illegal call of positiveIn." f (EImp (l,r)) = f (notCpl l .\/. r) f (EIsc (l,r)) = f l ++ f r f (EUni (l,r)) = f l ++ f r f (EDif (l,r)) = f l ++ f (notCpl r) f (ELrs (l,r)) = f l ++ f (notCpl r) f (ERrs (l,r)) = f (notCpl l) ++ f r f (EDia (l,r)) = f (flp l .\. r ./\. l ./. flp r) f (ECps (l,r)) = f l ++ f r f (ERad (l,r)) = f l ++ f r f (EPrd (l,r)) = f l ++ f r f (EKl0 e) = f e f (EKl1 e) = f e f (EFlp e) = f e f (ECpl e) = [ not b | b<- f e] f (EBrk e) = f e f (EDcD d) = [ True | d==decl ] f (EDcI c) = [ True | detyp decl==c ] f EEps{} = [] f EDcV{} = [] f EMp1{} = []
guoy34/ampersand
src/Database/Design/Ampersand/FSpec/Switchboard.hs
gpl-3.0
12,170
0
23
5,076
3,665
1,952
1,713
180
21
{-# 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.Genomics.AnnotationSets.Search -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Searches for annotation sets that match the given criteria. Annotation -- sets are returned in an unspecified order. This order is consistent, -- such that two queries for the same content (regardless of page size) -- yield annotation sets in the same order across their respective streams -- of paginated responses. Caller must have READ permission for the queried -- datasets. -- -- /See:/ <https://cloud.google.com/genomics Genomics API Reference> for @genomics.annotationsets.search@. module Network.Google.Resource.Genomics.AnnotationSets.Search ( -- * REST Resource AnnotationSetsSearchResource -- * Creating a Request , annotationSetsSearch , AnnotationSetsSearch -- * Request Lenses , assXgafv , assUploadProtocol , assPp , assAccessToken , assUploadType , assPayload , assBearerToken , assCallback ) where import Network.Google.Genomics.Types import Network.Google.Prelude -- | A resource alias for @genomics.annotationsets.search@ method which the -- 'AnnotationSetsSearch' request conforms to. type AnnotationSetsSearchResource = "v1" :> "annotationsets" :> "search" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] SearchAnnotationSetsRequest :> Post '[JSON] SearchAnnotationSetsResponse -- | Searches for annotation sets that match the given criteria. Annotation -- sets are returned in an unspecified order. This order is consistent, -- such that two queries for the same content (regardless of page size) -- yield annotation sets in the same order across their respective streams -- of paginated responses. Caller must have READ permission for the queried -- datasets. -- -- /See:/ 'annotationSetsSearch' smart constructor. data AnnotationSetsSearch = AnnotationSetsSearch' { _assXgafv :: !(Maybe Xgafv) , _assUploadProtocol :: !(Maybe Text) , _assPp :: !Bool , _assAccessToken :: !(Maybe Text) , _assUploadType :: !(Maybe Text) , _assPayload :: !SearchAnnotationSetsRequest , _assBearerToken :: !(Maybe Text) , _assCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AnnotationSetsSearch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'assXgafv' -- -- * 'assUploadProtocol' -- -- * 'assPp' -- -- * 'assAccessToken' -- -- * 'assUploadType' -- -- * 'assPayload' -- -- * 'assBearerToken' -- -- * 'assCallback' annotationSetsSearch :: SearchAnnotationSetsRequest -- ^ 'assPayload' -> AnnotationSetsSearch annotationSetsSearch pAssPayload_ = AnnotationSetsSearch' { _assXgafv = Nothing , _assUploadProtocol = Nothing , _assPp = True , _assAccessToken = Nothing , _assUploadType = Nothing , _assPayload = pAssPayload_ , _assBearerToken = Nothing , _assCallback = Nothing } -- | V1 error format. assXgafv :: Lens' AnnotationSetsSearch (Maybe Xgafv) assXgafv = lens _assXgafv (\ s a -> s{_assXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). assUploadProtocol :: Lens' AnnotationSetsSearch (Maybe Text) assUploadProtocol = lens _assUploadProtocol (\ s a -> s{_assUploadProtocol = a}) -- | Pretty-print response. assPp :: Lens' AnnotationSetsSearch Bool assPp = lens _assPp (\ s a -> s{_assPp = a}) -- | OAuth access token. assAccessToken :: Lens' AnnotationSetsSearch (Maybe Text) assAccessToken = lens _assAccessToken (\ s a -> s{_assAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). assUploadType :: Lens' AnnotationSetsSearch (Maybe Text) assUploadType = lens _assUploadType (\ s a -> s{_assUploadType = a}) -- | Multipart request metadata. assPayload :: Lens' AnnotationSetsSearch SearchAnnotationSetsRequest assPayload = lens _assPayload (\ s a -> s{_assPayload = a}) -- | OAuth bearer token. assBearerToken :: Lens' AnnotationSetsSearch (Maybe Text) assBearerToken = lens _assBearerToken (\ s a -> s{_assBearerToken = a}) -- | JSONP assCallback :: Lens' AnnotationSetsSearch (Maybe Text) assCallback = lens _assCallback (\ s a -> s{_assCallback = a}) instance GoogleRequest AnnotationSetsSearch where type Rs AnnotationSetsSearch = SearchAnnotationSetsResponse type Scopes AnnotationSetsSearch = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/genomics", "https://www.googleapis.com/auth/genomics.readonly"] requestClient AnnotationSetsSearch'{..} = go _assXgafv _assUploadProtocol (Just _assPp) _assAccessToken _assUploadType _assBearerToken _assCallback (Just AltJSON) _assPayload genomicsService where go = buildClient (Proxy :: Proxy AnnotationSetsSearchResource) mempty
rueshyna/gogol
gogol-genomics/gen/Network/Google/Resource/Genomics/AnnotationSets/Search.hs
mpl-2.0
6,262
0
19
1,506
877
513
364
126
1
main = do a <- getLine b <- getLine return $ a ++ b -- fmap = <$> -- apply = <*> -- -- Execution sequence is -- (++) fmap getLine ==> IO (++ . getLine) -- then apply -- IO (getLine ++ getLine) -- main1 = (++) <$> getLine <*> getLine main2 = do a <- (++) <$> getLine <*> getLine putStrLn $ "Concatenated Lines: " ++ a main3 = do -- use applicative functor instead of list comprehensions putStrLn $ show [x * y | x <- [1, 2, 3], y <- [1, 2, 3]] main4 = do -- using pure applicative functor putStrLn $ show $ [(*0), (+100), (^2)] <*> [1, 2, 3] main5 = do -- using functor + applicative functor putStrLn $ show $ (*) <$> [1, 2, 3] <*> [100, 200, 300] --main6 = do -- making zip like functionality --class (Functor f) => ZipList -- pure x = --instance Applicative ZipList where -- pure x = ZipList (repeat x) -- ZipList fs <*> ZipList xs = ZipList (zipWith (\f x -> f x) fs xs) -- (+) <$> (+3) <*> (*100) <*> 5 -- gives 508 -- --(\x y z -> [x, y, z]) <$> (+3) <*> (*2) <*> (/2) $ 5 --(\x y z -> [x, y, z]) <$> (5+3) <*> (5*2) <*> (5/2) --(\ (5+3) (5*2) <*> (5/2) -> [x, y, z]) --gives [8, 10, 2.5]
dongarerahul/lyah
chapter11-functorApplicativeMonad/Applicative.hs
apache-2.0
1,134
0
12
276
253
152
101
14
1
module TUT20190115A where data Tree a = Tree a [Tree a] deriving Show data Tree2 a = Leaf a | Branch a [Tree2 a] deriving Show visit :: Tree a -> [a] visit (Tree a []) = [a] visit (Tree a childern) = foldl (++) [a] (map visit childern) -- visit2 (Leaf a ) = [a] -- visit2 (Tree a leaves) = foldl (++) [a] (map visit2 leaves) -- concatMap :: (a -> a) -> [[a]] -> [a] -- concatMap f l = map f $ foldl (++) [] l countnodes :: Tree a -> Int countnodes (Tree a []) = 1 countnodes (Tree a l ) = foldl (+) 1 (map countnodes l) -- instance Eq (Tree a) where -- t1 == t2 = (countnodes t1) == (countnodes t2) instance (Eq a) => Eq (Tree a) where t1 == t2 = (visit t1) == (visit t2) zip2list :: [(a,a)] -> [a] zip2list [] = [] zip2list ((x,y):xs) = [x,y] ++ zip2list xs
riccardotommasini/plp16
haskell/tutoring/TUT20190115A.hs
apache-2.0
871
0
8
275
309
169
140
14
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QDialog_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:15 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QDialog_h where import Qtc.Enums.Base import Qtc.Enums.Gui.QPaintDevice import Qtc.Enums.Core.Qt 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 (QDialog ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDialog_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QDialog_unSetUserMethod" qtc_QDialog_unSetUserMethod :: Ptr (TQDialog a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QDialogSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDialog_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QDialog ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDialog_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QDialogSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDialog_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QDialog ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDialog_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QDialogSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDialog_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QDialog ()) (QDialog x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QDialog setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QDialog_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QDialog_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQDialog 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_QDialog_setUserMethod" qtc_QDialog_setUserMethod :: Ptr (TQDialog a) -> CInt -> Ptr (Ptr (TQDialog x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QDialog :: (Ptr (TQDialog x0) -> IO ()) -> IO (FunPtr (Ptr (TQDialog x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QDialog_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QDialogSc a) (QDialog x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QDialog setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QDialog_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QDialog_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQDialog 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 (QDialog ()) (QDialog x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QDialog setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QDialog_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QDialog_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQDialog 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_QDialog_setUserMethodVariant" qtc_QDialog_setUserMethodVariant :: Ptr (TQDialog a) -> CInt -> Ptr (Ptr (TQDialog x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QDialog :: (Ptr (TQDialog x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQDialog x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QDialog_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QDialogSc a) (QDialog x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QDialog setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QDialog_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QDialog_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQDialog 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 (QDialog ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QDialog_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QDialog_unSetHandler" qtc_QDialog_unSetHandler :: Ptr (TQDialog a) -> CWString -> IO (CBool) instance QunSetHandler (QDialogSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QDialog_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QDialog ()) (QDialog x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> IO () setHandlerWrapper x0 = do x0obj <- qDialogFromPtr 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_QDialog_setHandler1" qtc_QDialog_setHandler1 :: Ptr (TQDialog a) -> CWString -> Ptr (Ptr (TQDialog x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialog1 :: (Ptr (TQDialog x0) -> IO ()) -> IO (FunPtr (Ptr (TQDialog x0) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QDialog1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogSc a) (QDialog x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> IO () setHandlerWrapper x0 = do x0obj <- qDialogFromPtr 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 Qaccept_h (QDialog ()) (()) where accept_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_accept cobj_x0 foreign import ccall "qtc_QDialog_accept" qtc_QDialog_accept :: Ptr (TQDialog a) -> IO () instance Qaccept_h (QDialogSc a) (()) where accept_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_accept cobj_x0 instance QsetHandler (QDialog ()) (QDialog x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDialogFromPtr 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_QDialog_setHandler2" qtc_QDialog_setHandler2 :: Ptr (TQDialog a) -> CWString -> Ptr (Ptr (TQDialog x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialog2 :: (Ptr (TQDialog x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQDialog x0) -> Ptr (TQEvent t1) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QDialog2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogSc a) (QDialog x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDialogFromPtr 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 QcloseEvent_h (QDialog ()) ((QCloseEvent t1)) where closeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_closeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_closeEvent" qtc_QDialog_closeEvent :: Ptr (TQDialog a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent_h (QDialogSc a) ((QCloseEvent t1)) where closeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_closeEvent cobj_x0 cobj_x1 instance QcontextMenuEvent_h (QDialog ()) ((QContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_contextMenuEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_contextMenuEvent" qtc_QDialog_contextMenuEvent :: Ptr (TQDialog a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent_h (QDialogSc a) ((QContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_contextMenuEvent cobj_x0 cobj_x1 instance QsetHandler (QDialog ()) (QDialog x0 -> Int -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> CInt -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDialogFromPtr 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_QDialog_setHandler3" qtc_QDialog_setHandler3 :: Ptr (TQDialog a) -> CWString -> Ptr (Ptr (TQDialog x0) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialog3 :: (Ptr (TQDialog x0) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQDialog x0) -> CInt -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QDialog3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogSc a) (QDialog x0 -> Int -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> CInt -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDialogFromPtr 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 Qdone_h (QDialog ()) ((Int)) where done_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_done cobj_x0 (toCInt x1) foreign import ccall "qtc_QDialog_done" qtc_QDialog_done :: Ptr (TQDialog a) -> CInt -> IO () instance Qdone_h (QDialogSc a) ((Int)) where done_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_done cobj_x0 (toCInt x1) instance QsetHandler (QDialog ()) (QDialog x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qDialogFromPtr 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_QDialog_setHandler4" qtc_QDialog_setHandler4 :: Ptr (TQDialog a) -> CWString -> Ptr (Ptr (TQDialog x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialog4 :: (Ptr (TQDialog x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDialog x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDialog4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogSc a) (QDialog x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qDialogFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qevent_h (QDialog ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_event cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_event" qtc_QDialog_event :: Ptr (TQDialog a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QDialogSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_event cobj_x0 cobj_x1 instance QkeyPressEvent_h (QDialog ()) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_keyPressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_keyPressEvent" qtc_QDialog_keyPressEvent :: Ptr (TQDialog a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent_h (QDialogSc a) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_keyPressEvent cobj_x0 cobj_x1 instance QsetHandler (QDialog ()) (QDialog x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qDialogFromPtr 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_QDialog_setHandler5" qtc_QDialog_setHandler5 :: Ptr (TQDialog a) -> CWString -> Ptr (Ptr (TQDialog x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialog5 :: (Ptr (TQDialog x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQDialog x0) -> IO (Ptr (TQSize t0)))) foreign import ccall "wrapper" wrapSetHandler_QDialog5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogSc a) (QDialog x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qDialogFromPtr 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 QqminimumSizeHint_h (QDialog ()) (()) where qminimumSizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_minimumSizeHint cobj_x0 foreign import ccall "qtc_QDialog_minimumSizeHint" qtc_QDialog_minimumSizeHint :: Ptr (TQDialog a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint_h (QDialogSc a) (()) where qminimumSizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_minimumSizeHint cobj_x0 instance QminimumSizeHint_h (QDialog ()) (()) where minimumSizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QDialog_minimumSizeHint_qth" qtc_QDialog_minimumSizeHint_qth :: Ptr (TQDialog a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint_h (QDialogSc a) (()) where minimumSizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance Qreject_h (QDialog ()) (()) where reject_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_reject cobj_x0 foreign import ccall "qtc_QDialog_reject" qtc_QDialog_reject :: Ptr (TQDialog a) -> IO () instance Qreject_h (QDialogSc a) (()) where reject_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_reject cobj_x0 instance QresizeEvent_h (QDialog ()) ((QResizeEvent t1)) where resizeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_resizeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_resizeEvent" qtc_QDialog_resizeEvent :: Ptr (TQDialog a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent_h (QDialogSc a) ((QResizeEvent t1)) where resizeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_resizeEvent cobj_x0 cobj_x1 instance QsetHandler (QDialog ()) (QDialog x0 -> Bool -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> CBool -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDialogFromPtr x0 let x1bool = fromCBool x1 if (objectIsNull x0obj) then return () else _handler x0obj x1bool setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDialog_setHandler6" qtc_QDialog_setHandler6 :: Ptr (TQDialog a) -> CWString -> Ptr (Ptr (TQDialog x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialog6 :: (Ptr (TQDialog x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQDialog x0) -> CBool -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QDialog6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogSc a) (QDialog x0 -> Bool -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> CBool -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDialogFromPtr x0 let x1bool = fromCBool x1 if (objectIsNull x0obj) then return () else _handler x0obj x1bool setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetVisible_h (QDialog ()) ((Bool)) where setVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_setVisible cobj_x0 (toCBool x1) foreign import ccall "qtc_QDialog_setVisible" qtc_QDialog_setVisible :: Ptr (TQDialog a) -> CBool -> IO () instance QsetVisible_h (QDialogSc a) ((Bool)) where setVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_setVisible cobj_x0 (toCBool x1) instance QshowEvent_h (QDialog ()) ((QShowEvent t1)) where showEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_showEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_showEvent" qtc_QDialog_showEvent :: Ptr (TQDialog a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent_h (QDialogSc a) ((QShowEvent t1)) where showEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_showEvent cobj_x0 cobj_x1 instance QqsizeHint_h (QDialog ()) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_sizeHint cobj_x0 foreign import ccall "qtc_QDialog_sizeHint" qtc_QDialog_sizeHint :: Ptr (TQDialog a) -> IO (Ptr (TQSize ())) instance QqsizeHint_h (QDialogSc a) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_sizeHint cobj_x0 instance QsizeHint_h (QDialog ()) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QDialog_sizeHint_qth" qtc_QDialog_sizeHint_qth :: Ptr (TQDialog a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint_h (QDialogSc a) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance QactionEvent_h (QDialog ()) ((QActionEvent t1)) where actionEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_actionEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_actionEvent" qtc_QDialog_actionEvent :: Ptr (TQDialog a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent_h (QDialogSc a) ((QActionEvent t1)) where actionEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_actionEvent cobj_x0 cobj_x1 instance QchangeEvent_h (QDialog ()) ((QEvent t1)) where changeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_changeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_changeEvent" qtc_QDialog_changeEvent :: Ptr (TQDialog a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent_h (QDialogSc a) ((QEvent t1)) where changeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_changeEvent cobj_x0 cobj_x1 instance QsetHandler (QDialog ()) (QDialog x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qDialogFromPtr 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_QDialog_setHandler7" qtc_QDialog_setHandler7 :: Ptr (TQDialog a) -> CWString -> Ptr (Ptr (TQDialog x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialog7 :: (Ptr (TQDialog x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQDialog x0) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QDialog7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogSc a) (QDialog x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qDialogFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QdevType_h (QDialog ()) (()) where devType_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_devType cobj_x0 foreign import ccall "qtc_QDialog_devType" qtc_QDialog_devType :: Ptr (TQDialog a) -> IO CInt instance QdevType_h (QDialogSc a) (()) where devType_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_devType cobj_x0 instance QdragEnterEvent_h (QDialog ()) ((QDragEnterEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_dragEnterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_dragEnterEvent" qtc_QDialog_dragEnterEvent :: Ptr (TQDialog a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent_h (QDialogSc a) ((QDragEnterEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_dragEnterEvent cobj_x0 cobj_x1 instance QdragLeaveEvent_h (QDialog ()) ((QDragLeaveEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_dragLeaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_dragLeaveEvent" qtc_QDialog_dragLeaveEvent :: Ptr (TQDialog a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent_h (QDialogSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_dragLeaveEvent cobj_x0 cobj_x1 instance QdragMoveEvent_h (QDialog ()) ((QDragMoveEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_dragMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_dragMoveEvent" qtc_QDialog_dragMoveEvent :: Ptr (TQDialog a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent_h (QDialogSc a) ((QDragMoveEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_dragMoveEvent cobj_x0 cobj_x1 instance QdropEvent_h (QDialog ()) ((QDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_dropEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_dropEvent" qtc_QDialog_dropEvent :: Ptr (TQDialog a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent_h (QDialogSc a) ((QDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_dropEvent cobj_x0 cobj_x1 instance QenterEvent_h (QDialog ()) ((QEvent t1)) where enterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_enterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_enterEvent" qtc_QDialog_enterEvent :: Ptr (TQDialog a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent_h (QDialogSc a) ((QEvent t1)) where enterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_enterEvent cobj_x0 cobj_x1 instance QfocusInEvent_h (QDialog ()) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_focusInEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_focusInEvent" qtc_QDialog_focusInEvent :: Ptr (TQDialog a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent_h (QDialogSc a) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_focusInEvent cobj_x0 cobj_x1 instance QfocusOutEvent_h (QDialog ()) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_focusOutEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_focusOutEvent" qtc_QDialog_focusOutEvent :: Ptr (TQDialog a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent_h (QDialogSc a) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_focusOutEvent cobj_x0 cobj_x1 instance QsetHandler (QDialog ()) (QDialog x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qDialogFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDialog_setHandler8" qtc_QDialog_setHandler8 :: Ptr (TQDialog a) -> CWString -> Ptr (Ptr (TQDialog x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialog8 :: (Ptr (TQDialog x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQDialog x0) -> CInt -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QDialog8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogSc a) (QDialog x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qDialogFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QheightForWidth_h (QDialog ()) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_heightForWidth cobj_x0 (toCInt x1) foreign import ccall "qtc_QDialog_heightForWidth" qtc_QDialog_heightForWidth :: Ptr (TQDialog a) -> CInt -> IO CInt instance QheightForWidth_h (QDialogSc a) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_heightForWidth cobj_x0 (toCInt x1) instance QhideEvent_h (QDialog ()) ((QHideEvent t1)) where hideEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_hideEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_hideEvent" qtc_QDialog_hideEvent :: Ptr (TQDialog a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent_h (QDialogSc a) ((QHideEvent t1)) where hideEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_hideEvent cobj_x0 cobj_x1 instance QsetHandler (QDialog ()) (QDialog x0 -> InputMethodQuery -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- qDialogFromPtr 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_QDialog_setHandler9" qtc_QDialog_setHandler9 :: Ptr (TQDialog a) -> CWString -> Ptr (Ptr (TQDialog x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialog9 :: (Ptr (TQDialog x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQDialog x0) -> CLong -> IO (Ptr (TQVariant t0)))) foreign import ccall "wrapper" wrapSetHandler_QDialog9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogSc a) (QDialog x0 -> InputMethodQuery -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- qDialogFromPtr 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 (QDialog ()) ((InputMethodQuery)) where inputMethodQuery_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QDialog_inputMethodQuery" qtc_QDialog_inputMethodQuery :: Ptr (TQDialog a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery_h (QDialogSc a) ((InputMethodQuery)) where inputMethodQuery_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) instance QkeyReleaseEvent_h (QDialog ()) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_keyReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_keyReleaseEvent" qtc_QDialog_keyReleaseEvent :: Ptr (TQDialog a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent_h (QDialogSc a) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_keyReleaseEvent cobj_x0 cobj_x1 instance QleaveEvent_h (QDialog ()) ((QEvent t1)) where leaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_leaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_leaveEvent" qtc_QDialog_leaveEvent :: Ptr (TQDialog a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent_h (QDialogSc a) ((QEvent t1)) where leaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_leaveEvent cobj_x0 cobj_x1 instance QmouseDoubleClickEvent_h (QDialog ()) ((QMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_mouseDoubleClickEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_mouseDoubleClickEvent" qtc_QDialog_mouseDoubleClickEvent :: Ptr (TQDialog a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent_h (QDialogSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_mouseDoubleClickEvent cobj_x0 cobj_x1 instance QmouseMoveEvent_h (QDialog ()) ((QMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_mouseMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_mouseMoveEvent" qtc_QDialog_mouseMoveEvent :: Ptr (TQDialog a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent_h (QDialogSc a) ((QMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_mouseMoveEvent cobj_x0 cobj_x1 instance QmousePressEvent_h (QDialog ()) ((QMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_mousePressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_mousePressEvent" qtc_QDialog_mousePressEvent :: Ptr (TQDialog a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent_h (QDialogSc a) ((QMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_mousePressEvent cobj_x0 cobj_x1 instance QmouseReleaseEvent_h (QDialog ()) ((QMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_mouseReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_mouseReleaseEvent" qtc_QDialog_mouseReleaseEvent :: Ptr (TQDialog a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent_h (QDialogSc a) ((QMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_mouseReleaseEvent cobj_x0 cobj_x1 instance QmoveEvent_h (QDialog ()) ((QMoveEvent t1)) where moveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_moveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_moveEvent" qtc_QDialog_moveEvent :: Ptr (TQDialog a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent_h (QDialogSc a) ((QMoveEvent t1)) where moveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_moveEvent cobj_x0 cobj_x1 instance QsetHandler (QDialog ()) (QDialog x0 -> IO (QPaintEngine t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> IO (Ptr (TQPaintEngine t0)) setHandlerWrapper x0 = do x0obj <- qDialogFromPtr 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_QDialog_setHandler10" qtc_QDialog_setHandler10 :: Ptr (TQDialog a) -> CWString -> Ptr (Ptr (TQDialog x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialog10 :: (Ptr (TQDialog x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQDialog x0) -> IO (Ptr (TQPaintEngine t0)))) foreign import ccall "wrapper" wrapSetHandler_QDialog10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogSc a) (QDialog x0 -> IO (QPaintEngine t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> IO (Ptr (TQPaintEngine t0)) setHandlerWrapper x0 = do x0obj <- qDialogFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QpaintEngine_h (QDialog ()) (()) where paintEngine_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_paintEngine cobj_x0 foreign import ccall "qtc_QDialog_paintEngine" qtc_QDialog_paintEngine :: Ptr (TQDialog a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine_h (QDialogSc a) (()) where paintEngine_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_paintEngine cobj_x0 instance QpaintEvent_h (QDialog ()) ((QPaintEvent t1)) where paintEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_paintEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_paintEvent" qtc_QDialog_paintEvent :: Ptr (TQDialog a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent_h (QDialogSc a) ((QPaintEvent t1)) where paintEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_paintEvent cobj_x0 cobj_x1 instance QtabletEvent_h (QDialog ()) ((QTabletEvent t1)) where tabletEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_tabletEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_tabletEvent" qtc_QDialog_tabletEvent :: Ptr (TQDialog a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent_h (QDialogSc a) ((QTabletEvent t1)) where tabletEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_tabletEvent cobj_x0 cobj_x1 instance QwheelEvent_h (QDialog ()) ((QWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_wheelEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_wheelEvent" qtc_QDialog_wheelEvent :: Ptr (TQDialog a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent_h (QDialogSc a) ((QWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_wheelEvent cobj_x0 cobj_x1 instance QsetHandler (QDialog ()) (QDialog x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog11 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog11_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qDialogFromPtr 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_QDialog_setHandler11" qtc_QDialog_setHandler11 :: Ptr (TQDialog a) -> CWString -> Ptr (Ptr (TQDialog 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_QDialog11 :: (Ptr (TQDialog x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDialog x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDialog11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogSc a) (QDialog x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialog11 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialog11_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialog_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialog x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qDialogFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QeventFilter_h (QDialog ()) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QDialog_eventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QDialog_eventFilter" qtc_QDialog_eventFilter :: Ptr (TQDialog a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter_h (QDialogSc a) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QDialog_eventFilter cobj_x0 cobj_x1 cobj_x2
uduki/hsQt
Qtc/Gui/QDialog_h.hs
bsd-2-clause
62,076
91
19
13,844
21,164
10,202
10,962
-1
-1
module CodeGen.Platform.ARM where import CmmExpr #define MACHREGS_NO_REGS 0 #define MACHREGS_arm 1 #include "../../../../includes/CodeGen.Platform.hs"
nomeata/ghc
compiler/codeGen/CodeGen/Platform/ARM.hs
bsd-3-clause
155
0
3
17
13
10
3
2
0
-- | -- This module reexports the commonly used infix operators -- from the \"lens\" package. module Prelude.Lens.BasicInfix ( module E ) where import Control.Lens as E ( (^.) , (^..) , (^?) , (.~) )
andrewthad/lens-prelude
src/Prelude/Lens/BasicInfix.hs
bsd-3-clause
219
0
5
55
45
34
11
7
0
{-# LANGUAGE ScopedTypeVariables #-} module HistogramExec where import Histogram import Prelude hiding (replicate) import Prelude as P import Obsidian import Obsidian.Run.CUDA.Exec import qualified Data.Vector.Storable as V import Control.Monad.State import Data.Word -- allocaVector does not zero out the memory. performSmall = withCUDA $ do kern <- capture 256 (histogram 1 256) useVector (V.fromList (P.replicate 256 1)) $ \i -> allocaVector 256 $ \ (m :: CUDAVector Word32) -> do fill m 0 exec $ (1,kern) <:> m <> i r <- peekCUDAVector m lift $ putStrLn $ show r performLarge = withCUDA $ do kern <- capture 256 (histogram 256 256) useVector (V.fromList [0..65535 :: Word32]) $ \i -> allocaVector 65536 $ \ (m :: CUDAVector Word32) -> do fill m 0 exec $ (1,kern) <:> m <> i r <- peekCUDAVector m lift $ putStrLn $ show r
svenssonjoel/ObsidianGFX
Examples/Simple/HistogramExec.hs
bsd-3-clause
971
0
17
284
325
168
157
32
1
#define IncludedListLemmata appendGroup :: List a -> List a -> List a -> List a -> List a -> Proof {-@ appendGroup :: x1:List a -> x2:List a -> x3:List a -> x4:List a -> x5:List a -> { (append (append x1 x2) (append (append x3 x4) x5)) == (append x1 (append (append (append x2 x3) x4) x5)) } @-} appendGroup x1 x2 x3 x4 x5 = append (append x1 x2) (append (append x3 x4) x5) ==. append x1 (append x2 (append (append x3 x4) x5)) ? listAssoc x1 x2 (append (append x3 x4) x5) ==. append x1 (append (append x2 (append x3 x4)) x5) ? listAssoc x2 (append x3 x4) x5 ==. append x1 (append (append (append x2 x3) x4) x5) ? listAssoc x2 x3 x4 *** QED appendUnGroup :: List a -> List a -> List a -> List a -> List a -> Proof {-@ appendUnGroup :: x1:List a -> x2:List a -> x3:List a -> x4:List a -> x5:List a -> { (append x1 (append (append (append x2 x3) x4) x5)) == (append (append (append (append x1 x2) x3) x4) x5) } @-} appendUnGroup x1 x2 x3 x4 x5 = append x1 (append (append (append x2 x3) x4) x5) ==. append x1 (append (append x2 (append x3 x4)) x5) ? listAssoc x2 x3 x4 ==. append (append x1 (append x2 (append x3 x4))) x5 ? listAssoc x1 (append x2 (append x3 x4)) x5 ==. append (append (append x1 x2) (append x3 x4)) x5 ? listAssoc x1 x2 (append x3 x4) ==. append (append (append (append x1 x2) x3) x4) x5 ? listAssoc (append x1 x2) x3 x4 *** QED mapAppend :: (a -> b) -> List a -> List a -> Proof {-@ mapAppend :: f:(a -> b) -> xs:List a -> ys:List a -> {map f (append xs ys) == append (map f xs) (map f ys)} @-} mapAppend f N ys = map f (append N ys) ==. map f ys ==. append N (map f ys) ==. append (map f N) (map f ys) *** QED mapAppend f (C x xs) ys = map f (append (C x xs) ys) ==. map f (x `C` (append xs ys)) ==. f x `C` (map f (append xs ys)) ==. f x `C` (append (map f xs) (map f ys)) ? mapAppend f xs ys ==. append (f x `C` map f xs) (map f ys) ==. append (map f (x `C` xs)) (map f ys) *** QED
nikivazou/verified_string_matching
src/Proofs/ListLemmata.hs
bsd-3-clause
2,097
0
20
609
873
426
447
38
1
module Main where -- Quickly sums numbers form 1 to N quicksum :: Integer -> Integer quicksum n = (n + 1) * n `div` 2 diff :: Integer -> Integer diff n = toInteger $ floor $ (fromInteger (quicksum n) :: Float) ** 2 - sumOfSquares n where sumOfSquares n = sum $ map (\x -> (fromInteger x) ** 2) [1..n] main = do putStrLn $ "Diff(10): " ++ show (diff 10) putStrLn $ "Diff(10): " ++ show (diff 100)
tomob/euler
006/006.hs
bsd-3-clause
426
0
13
111
177
92
85
9
1
-- | -- Module : Core.Primitive.Types -- License : BSD-style -- Maintainer : Vincent Hanquez <[email protected]> -- Stability : experimental -- Portability : portable -- {-# LANGUAGE MagicHash #-} {-# LANGUAGE UnboxedTuples #-} module Core.Primitive.Types ( PrimType(..) ) where import GHC.Prim import GHC.Int import GHC.Types import GHC.Word import Core.Proxy import Core.Internal.Primitive import Core.Internal.Base import Core.Primitive.Monad -- | Represent the accessor for types that can be stored in the UVector and MUVector. -- -- Types need to be a instance of storable and have fixed sized. class PrimType ty where -- | get the size in bits of a ty element sizeInBits :: Proxy ty -> Int ----- -- ByteArray section ----- -- | return the element stored at a specific index primBaIndex :: ByteArray# -> Int -> ty ----- -- MutableByteArray section ----- -- | Read an element at an index in a mutable array primMbaRead :: PrimMonad prim => MutableByteArray# (PrimState prim) -- ^ mutable array to read from -> Int -- ^ index of the element to retrieve -> prim ty -- ^ the element returned -- | Write an element to a specific cell in a mutable array. primMbaWrite :: PrimMonad prim => MutableByteArray# (PrimState prim) -- ^ mutable array to modify -> Int -- ^ index of the element to modify -> ty -- ^ the new value to store -> prim () -- return the index and mask to a bit in a bitmap bitmapAddr :: Int# -> (# Int# , Word# #) bitmapAddr !i = (# idx, mask #) where (# !idx, !bit #) = quotRemInt# i 4# !mask = case bit of 0# -> 0x1## 1# -> 0x2## 2# -> 0x4## 3# -> 0x8## 4# -> 0x10## 5# -> 0x20## 6# -> 0x40## 7# -> 0x80## 8# -> 0x100## 9# -> 0x200## 10# -> 0x400## 11# -> 0x800## 12# -> 0x1000## 13# -> 0x2000## 14# -> 0x4000## 15# -> 0x8000## 16# -> 0x10000## 17# -> 0x20000## 18# -> 0x40000## 19# -> 0x80000## 20# -> 0x100000## 21# -> 0x200000## 22# -> 0x400000## 23# -> 0x800000## 24# -> 0x1000000## 25# -> 0x2000000## 26# -> 0x4000000## 27# -> 0x8000000## 28# -> 0x10000000## 29# -> 0x20000000## 30# -> 0x40000000## _ -> 0x80000000## instance PrimType Bool where sizeInBits _ = 1 {-# INLINE sizeInBits #-} primBaIndex ba (I# n) = bool# (0# /=# word2Int# (and# v mask)) where (# idx, mask #) = bitmapAddr n !v = indexWord32Array# ba idx {-# INLINE primBaIndex #-} primMbaRead mba (I# n) = primitive $ \s1 -> case readWord32Array# mba idx s1 of (# s2, v #) -> (# s2, bool# (word2Int# (and# v mask) ==# 0#) #) where (# !idx, !mask #) = bitmapAddr n {-# INLINE primMbaRead #-} primMbaWrite mba (I# n) setValue = primitive $ \s1 -> case readWord32Array# mba idx s1 of (# s2, v #) -> (# writeWord32Array# mba idx (newVal v) s2, () #) where (# !idx, !mask #) = bitmapAddr n newVal v | setValue = or# v mask | otherwise = and# v (not# mask) {-# INLINE primMbaWrite #-} instance PrimType Word8 where sizeInBits _ = 8 {-# INLINE sizeInBits #-} primBaIndex ba (I# n) = W8# (indexWord8Array# ba n) {-# INLINE primBaIndex #-} primMbaRead mba (I# n) = primitive $ \s1 -> let (# s2, r #) = readWord8Array# mba n s1 in (# s2, W8# r #) {-# INLINE primMbaRead #-} primMbaWrite mba (I# n) (W8# w) = primitive $ \s1 -> (# writeWord8Array# mba n w s1, () #) {-# INLINE primMbaWrite #-} instance PrimType Word16 where sizeInBits _ = 16 {-# INLINE sizeInBits #-} primBaIndex ba (I# n) = W16# (indexWord16Array# ba n) {-# INLINE primBaIndex #-} primMbaRead mba (I# n) = primitive $ \s1 -> let (# s2, r #) = readWord16Array# mba n s1 in (# s2, W16# r #) {-# INLINE primMbaRead #-} primMbaWrite mba (I# n) (W16# w) = primitive $ \s1 -> (# writeWord16Array# mba n w s1, () #) {-# INLINE primMbaWrite #-} instance PrimType Word32 where sizeInBits _ = 32 {-# INLINE sizeInBits #-} primBaIndex ba (I# n) = W32# (indexWord32Array# ba n) {-# INLINE primBaIndex #-} primMbaRead mba (I# n) = primitive $ \s1 -> let (# s2, r #) = readWord32Array# mba n s1 in (# s2, W32# r #) {-# INLINE primMbaRead #-} primMbaWrite mba (I# n) (W32# w) = primitive $ \s1 -> (# writeWord32Array# mba n w s1, () #) {-# INLINE primMbaWrite #-} instance PrimType Word64 where sizeInBits _ = 64 {-# INLINE sizeInBits #-} primBaIndex ba (I# n) = W64# (indexWord64Array# ba n) {-# INLINE primBaIndex #-} primMbaRead mba (I# n) = primitive $ \s1 -> let (# s2, r #) = readWord64Array# mba n s1 in (# s2, W64# r #) {-# INLINE primMbaRead #-} primMbaWrite mba (I# n) (W64# w) = primitive $ \s1 -> (# writeWord64Array# mba n w s1, () #) {-# INLINE primMbaWrite #-} instance PrimType Int8 where sizeInBits _ = 8 {-# INLINE sizeInBits #-} primBaIndex ba (I# n) = I8# (indexInt8Array# ba n) {-# INLINE primBaIndex #-} primMbaRead mba (I# n) = primitive $ \s1 -> let (# s2, r #) = readInt8Array# mba n s1 in (# s2, I8# r #) {-# INLINE primMbaRead #-} primMbaWrite mba (I# n) (I8# w) = primitive $ \s1 -> (# writeInt8Array# mba n w s1, () #) {-# INLINE primMbaWrite #-} instance PrimType Int16 where sizeInBits _ = 16 {-# INLINE sizeInBits #-} primBaIndex ba (I# n) = I16# (indexInt16Array# ba n) {-# INLINE primBaIndex #-} primMbaRead mba (I# n) = primitive $ \s1 -> let (# s2, r #) = readInt16Array# mba n s1 in (# s2, I16# r #) {-# INLINE primMbaRead #-} primMbaWrite mba (I# n) (I16# w) = primitive $ \s1 -> (# writeInt16Array# mba n w s1, () #) {-# INLINE primMbaWrite #-} instance PrimType Int32 where sizeInBits _ = 32 {-# INLINE sizeInBits #-} primBaIndex ba (I# n) = I32# (indexInt32Array# ba n) {-# INLINE primBaIndex #-} primMbaRead mba (I# n) = primitive $ \s1 -> let (# s2, r #) = readInt32Array# mba n s1 in (# s2, I32# r #) {-# INLINE primMbaRead #-} primMbaWrite mba (I# n) (I32# w) = primitive $ \s1 -> (# writeInt32Array# mba n w s1, () #) {-# INLINE primMbaWrite #-} instance PrimType Int64 where sizeInBits _ = 64 {-# INLINE sizeInBits #-} primBaIndex ba (I# n) = I64# (indexInt64Array# ba n) {-# INLINE primBaIndex #-} primMbaRead mba (I# n) = primitive $ \s1 -> let (# s2, r #) = readInt64Array# mba n s1 in (# s2, I64# r #) {-# INLINE primMbaRead #-} primMbaWrite mba (I# n) (I64# w) = primitive $ \s1 -> (# writeInt64Array# mba n w s1, () #) {-# INLINE primMbaWrite #-} instance PrimType Float where sizeInBits _ = 32 {-# INLINE sizeInBits #-} primBaIndex ba (I# n) = F# (indexFloatArray# ba n) {-# INLINE primBaIndex #-} primMbaRead mba (I# n) = primitive $ \s1 -> let (# s2, r #) = readFloatArray# mba n s1 in (# s2, F# r #) {-# INLINE primMbaRead #-} primMbaWrite mba (I# n) (F# w) = primitive $ \s1 -> (# writeFloatArray# mba n w s1, () #) {-# INLINE primMbaWrite #-} instance PrimType Double where sizeInBits _ = 64 {-# INLINE sizeInBits #-} primBaIndex ba (I# n) = D# (indexDoubleArray# ba n) {-# INLINE primBaIndex #-} primMbaRead mba (I# n) = primitive $ \s1 -> let (# s2, r #) = readDoubleArray# mba n s1 in (# s2, D# r #) {-# INLINE primMbaRead #-} primMbaWrite mba (I# n) (D# w) = primitive $ \s1 -> (# writeDoubleArray# mba n w s1, () #) {-# INLINE primMbaWrite #-}
vincenthz/hs-xyz-test
Core/Primitive/Types.hs
bsd-3-clause
8,380
0
17
2,815
2,277
1,171
1,106
-1
-1
module Data.Builder.Textual where class Textual a where textual :: a -> Builder class Textual a => FormatTexutal a where data Format a format :: Format a -> a -> Builder -------------------------------------------------------------------------------- class ParseTextual a where parseTextual :: Parser a
winterland1989/stdio
Data/Textual.hs
bsd-3-clause
325
0
8
61
79
41
38
-1
-1
{-# LANGUAGE OverloadedStrings,DuplicateRecordFields,OverloadedLabels,InstanceSigs,RecordWildCards,ViewPatterns,PatternSynonyms,ScopedTypeVariables #-} module Api.Stockfighter.Jailbreak.Decompiler.Passes where import Api.Stockfighter.Jailbreak.Decompiler.AST import Api.Stockfighter.Jailbreak.Types import Control.Monad import Control.Monad.Trans.State.Strict import Control.Lens hiding (Context, elements) import Data.Bits import Data.Data import Data.Data.Lens import Data.Function (on) import Data.List import Data.List.Extra (disjoint) import Data.Maybe import qualified Data.Map as Map import qualified Data.IntMap as M import qualified Data.Text as T import qualified Data.Text.Read as T type PassM a = StateT Context IO a type Pass = PassM () mapi :: (a -> Int -> b) -> [a] -> [b] mapi f xs = zipWith f xs [0..] parseSymbol :: T.Text -> Symbol parseSymbol symbolS = let name = T.takeWhile (/= '>') $ T.tail $ T.dropWhile (/= '<') $ symbolS reader = case T.find (=='<') symbolS of Nothing -> T.decimal Just _ -> T.hexadecimal offset = fromIntegral $ fst $ either undefined id $ reader $ T.takeWhile (/= ':') symbolS in Symbol { _sym_symbol = name, _sym_offset = offset } parseInstruction :: Instruction -> AstInstruction parseInstruction instruction = let arg_dest = Register $ dest instruction arg_src = Register $ src instruction arg_imm8a = Imm8 $ fromMaybe (Prelude.error $ show instruction) $ a instruction arg_imm8 = Imm8 $ k instruction arg_imm16 = Imm16 $ k instruction arg_imm32 = Imm32 $ k instruction arg_relptr = mkRelptr $ k instruction arg_absptr = AbsPtr $ k instruction arg_bitidx = BitIdx $ b instruction arg_reg16 = mkReg16 $ dest instruction arg_op = Imm8 $ case q instruction of Just x -> x absptr :: (AbsPtr -> AstInstruction) -> AstInstruction absptr f = f arg_absptr relptr :: (RelPtr -> AstInstruction) -> AstInstruction relptr f = f arg_relptr reg_reg :: (Register -> Register -> AstInstruction) -> AstInstruction reg_reg f = f arg_dest arg_src reg_imm32 :: (Register -> Imm32 -> AstInstruction) -> AstInstruction reg_imm32 f = f arg_dest arg_imm32 imm8_reg :: (Imm8 -> Register -> AstInstruction) -> AstInstruction imm8_reg f = f arg_imm8 arg_src imm8a_reg f = f arg_imm8a arg_src imm16_reg f = f arg_imm16 arg_src reg16_imm8 f = f arg_reg16 arg_imm8 reg_imm16 f = f arg_dest arg_imm16 reg_imm8 f = f arg_dest arg_imm8 reg_imm8a f = f arg_dest arg_imm8a reg16_reg16 f = f (mkReg16 $ dest instruction) (mkReg16 $ src instruction) reg_bit :: (Register -> BitIdx -> AstInstruction) -> AstInstruction reg_bit f = f arg_src arg_bitidx reg_op :: (Register -> Imm8 -> AstInstruction) -> AstInstruction reg_op f = f arg_dest arg_op op_reg f = f arg_op arg_src imm32 :: (Imm32 -> AstInstruction) -> AstInstruction imm32 f = f arg_imm32 table :: [ (T.Text, AstInstruction) ] table = [ ("mov", reg_reg Mov), ("cli", Cli), ("sei", Sei), ("clc", Clc), ("clh", Clh), ("cln", Cln), ("cls", Cls), ("clv", Clv), ("clz", Clz), ("clt", Clt), ("sec", Sec), ("seh", Seh), ("sen", Sen), ("ses", Ses), ("sev", Sev), ("sez", Sez), ("set", Set), ("jmp", absptr Jmp), ("ijmp", Ijmp), ("rjmp", relptr Rjmp), ("add", reg_reg Add), ("adc", reg_reg Adc), ("sub", reg_reg Sub), ("sbc", reg_reg Sbc), ("andi", reg_imm8 Andi), ("ldi", reg_imm8 Ldi), ("cpi", reg_imm8 Cpi), ("ori", reg_imm8 Ori), ("subi", reg_imm8 Subi), ("sbci", reg_imm8 Sbci), ("in", reg_imm8a In), ("out", imm8a_reg Out), ("sbi", reg_bit Sbi), ("cbi", reg_bit Cbi), ("sbic", reg_bit Sbic), ("sbis", reg_bit Sbis), ("sbrc", reg_bit Sbrc), ("sbrs", reg_bit Sbrs), ("cpse", reg_reg Cpse), ("bld", reg_bit Bld), ("bst", reg_bit Bst), ("adiw", reg16_imm8 Adiw), ("sbiw", reg16_imm8 Sbiw), ("movw", reg16_reg16 Movw), ("push", Push arg_src), ("pop", Pop arg_dest), ("brcc", relptr Brcc), ("brcs", relptr Brcs), ("brtc", relptr Brtc), ("brts", relptr Brts), ("breq", relptr Breq), ("brne", relptr Brne), ("brlt", relptr Brlt), ("brge", relptr Brge), ("brpl", relptr Brpl), ("brmi", relptr Brmi), ("cp", reg_reg Cp), ("cpc", reg_reg Cpc), ("inc", Inc arg_dest), ("dec", Dec arg_dest), ("ldx", Ldx arg_dest), ("ldxp", Ldxp arg_dest), ("ldxm", Ldxm arg_dest), ("ldy", Ldy arg_dest), ("ldyp", Ldyp arg_dest), ("ldym", Ldym arg_dest), ("ldz", Ldz arg_dest), ("ldzp", Ldzp arg_dest), ("ldzm", Ldzm arg_dest), ("lds", reg_imm16 Lds), ("lddx", reg_op Lddx), ("lddy", reg_op Lddy), ("lddz", reg_op Lddz), ("stx", Stx arg_src), ("stxp", Stxp arg_src), ("stxm", Stxm arg_src), ("sty", Sty arg_src), ("sts", imm16_reg Sts), ("sty", Sty arg_src), ("styp", op_reg Styp), ("stz", Stz arg_src), ("stzp", Stzp arg_src), ("stdz", op_reg Stdz), ("lpmz", Lpmz arg_dest), ("lpmzp", Lpmzp arg_dest), ("spm", Spm), ("call", imm32 Call), ("rcall", relptr Rcall), ("icall", Icall), ("ret", Ret), ("com", Com arg_dest), ("neg", Neg arg_dest), ("and", reg_reg And), ("eor", reg_reg Eor), ("or", reg_reg Or), ("ror", Ror arg_dest), ("rol", Rol arg_dest), ("lsr", Lsr arg_dest), ("asr", Asr arg_dest), ("swap", Swap arg_dest), ("mul", reg_reg Mul), ("break", Break), ("reti", Reti), ("unknown", Unknown), ("nop", Nop) ] tableMap = Map.fromList table mnemonic = mnem instruction in case Map.lookup mnemonic tableMap of Nothing -> Prelude.error $ "Unknown mnemonic: " ++ T.unpack mnemonic Just x -> x iex_asm :: InstructionEx -> Statement iex_asm x@(InstructionEx{ iex_i = Instruction{ offset = o }}) = SAsm (StatementAnnotation o Nothing [ x ]) x -- | Groups instructions by their symbol attribute, adding entries in the global symbol table pass_groupBySymbol :: Pass pass_groupBySymbol = do statements <- _ctx_statements <$> get let iexs = catMaybes $ map (\x -> case x of { SAsm _ y -> Just y ; _ -> Nothing }) statements is = map iex_i iexs newIndexBase <- _nextId <$> _ctx_functions <$> get let groups = groupBy (\a b -> not $ isJust $ symbol b) is let split_groups = flip mapi groups $ \disassembly i -> let (symbolI : instructions) = disassembly symbolS = fromJust $ symbol symbolI sym = parseSymbol symbolS symbolIStripped = symbolI { symbol = Nothing } in (newIndexBase + i, sym, symbolIStripped : instructions) let newFunctions = M.fromList $ map (\(a,b,c) -> (a,b)) split_groups mkInstructionEx i = InstructionEx i (parseInstruction i) let statements = flip map split_groups $ \(idx, sym, instructions) -> let anno = (StatementAnnotation (sym ^. sym_offset) Nothing iexs) in SFunction anno TVoid sym [] $ SBlock anno $ map iex_asm $ map mkInstructionEx instructions ctx_functions <>= Table newFunctions (M.size newFunctions) ctx_statements .= statements -- | Looks at a function's assembly to figure out parameters and adds them to the argument list. -- 1. The lowest uninitialized register in r24-r8 determines the number of arguments. -- 2. A register that is used uninitialized might not count if it's only being stored(via a 'Push' and later 'Pop'). -- 3. Types are deduced by seeing what kinds of instructions use them. adiw for example takes register pairs. deduceFunctionParameters :: Function -> Function deduceFunctionParameters function = undefined set_expr :: Setter' Statement Expression set_expr = setting f where f g = replaceSubtree (replaceExprs g) replaceExprs g stmt = case stmt of SExpression a e -> pure $ SExpression a $ transform g e SIfElse a cond s1 s2 -> pure $ SIfElse a (transform g cond) s1 s2 SWhile a cond s -> pure $ SWhile a (transform g cond) s _ -> [stmt] spliceListPoints :: [(Int, a)] -> [Int] -> [[(Int, a)]] spliceListPoints elems splicePoints = case splicePoints of [] -> [ elems ] (sp : sps) -> let (chunk, remainder) = span (\x -> fst x < sp) elems in chunk : spliceListPoints remainder sps pass_replaceLocalJumpsWithGotos :: Pass pass_replaceLocalJumpsWithGotos = do ctx <- get ctx_statements %= map (replaceSubtree replaceLocalJumpsWithGotos) return () pass_replaceBranchesWithJumps :: Pass pass_replaceBranchesWithJumps = do ctx <- get ctx_statements %= map (replaceGroup 2 replaceBranchesWithJumps) return () -- instance Functor StatementEx where -- fmap f statement = -- let mapChildren xs = map (fmap f) -- in case statement of -- SAssign a b c -> SAssign (f a) b c -- SLabel a b -> SLabel (f a) b -- SGoto a b -> SGoto (f a) b -- SAsm a b -> SAsm (f a) b -- SBlock a xs -> SBlock (f a) $ mapChildren xs -- SVariable a b c d -> SVariable (f a) b c d -- SFunction a b c d e -> SFunction (f a) b c (mapChildren d) (fmap f e) -- SIfElse a b c d -> SIfElse (f a) b (fmap f c) (fmap f d) -- instance Foldable StatementEx where -- foldMap :: Monoid m => (a -> m) -> t a -> m -- foldMap f statement = -- let fm = foldMap f -- mapChildren = map fm -- in case statement of -- SAssign a b c -> f a -- SLabel a b -> f a -- SGoto a b -> f a -- SBlock a xs -> f a <> mconcat (mapChildren xs) -- SVariable a _ _ _ -> f a -- SFunction a _ _ cs d -> f a <> mconcat (mapChildren cs) <> d -- SIfElse a _ c d -> f a <> fm c <> fm d -- instance Traversable StatementEx where -- traverse :: Applicative f => (a -> f b) -> StatementEx a -> f (StatementEx b) -- traverse f statement = case statement of -- SAssign a b c -> SAssign <$> f a <*> b <*> c -- SLabel a b -> SLabel <$> f a <*> b -- SGoto a b -> SGoto <$> f a <*> b -- SBlock a xs -> SBlock <$> f a <*> traverse (traverse f) xs -- SVariable a b c d -> SVariable <$> f a <*> b <*> c <*> d -- SFunction a b c ds e -> SFunction <$> f a <*> b <*> c <*> traverse (traverse f) d <*> traverse f e -- SIfElse a b c d -> SIfElse <$> f a <*> b <*> traverse f c <*> traverse f d normalizeStatement :: Statement -> Statement normalizeStatement stat = let expandChild stmt = case stmt of SBlock _ children -> children _ -> [ stmt ] in case stat of SExpression _ _ -> stat SLabel _ _ -> stat SGoto _ _ -> stat SAsm _ _ -> stat SBlock offset children -> case children of [ x ] -> normalizeStatement x _ -> SBlock offset $ sortBy (compare `on` (^. annotation)) $ concatMap expandChild children SVariable _ _ _ _ -> stat SFunction a b c ds e -> SFunction a b c (map normalizeStatement ds) (normalizeStatement e) SIfElse a b c d -> SIfElse a b (normalizeStatement c) (normalizeStatement d) SReturn _ _ -> stat SWhile a b stmt -> SWhile a b (normalizeStatement stmt) SContinue _ -> stat SPush _ _ -> stat SPop _ _ -> stat SGotoSymbol _ _ -> stat replaceSubtree :: (Statement -> [ Statement ] ) -> Statement -> Statement replaceSubtree f stat = let rewrite = replaceSubtree f in normalizeStatement $ SBlock (stat ^. annotation) $ f $ case stat of SExpression _ _ -> stat SLabel _ _ -> stat SGoto _ _ -> stat SAsm _ _ -> stat SBlock offset children -> SBlock offset $ map rewrite children SVariable _ _ _ _ -> stat SFunction a b c ds e -> SFunction a b c (map rewrite ds) (rewrite e) SIfElse a b c d -> SIfElse a b (rewrite c) (rewrite d) SReturn _ _ -> stat SWhile a b c -> SWhile a b (rewrite c) SContinue _ -> stat SPush _ _ -> stat SPop _ _ -> stat SGotoSymbol _ _ -> stat replace :: Int -> ([a] -> Maybe [a]) -> [a] -> [a] replace i f [] = [] replace i f xs | length xs < i = xs replace i f xs = case f $ take i xs of Nothing -> (head xs) : replace i f (tail xs) Just ys -> ys ++ replace i f (drop i xs) replaceGroup :: Int -> ([Statement] -> Maybe [Statement]) -> Statement -> Statement replaceGroup i f stat = let rewrite = replaceGroup i f in normalizeStatement $ case stat of SExpression _ _ -> stat SLabel _ _ -> stat SGoto _ _ -> stat SAsm _ _ -> stat SBlock anno children -> SBlock anno $ replace i f $ map rewrite children SVariable _ _ _ _ -> stat SFunction a b c ds e -> SFunction a b c (replace i f $ map rewrite ds) (rewrite e) SIfElse a b c d -> SIfElse a b (rewrite c) (rewrite d) SReturn _ _ -> stat SPush _ _ -> stat SPop _ _ -> stat SGotoSymbol _ _ -> stat labelAndGotoForRelptr :: StatementAnnotation -> RelPtr -> (Statement, Statement) labelAndGotoForRelptr anno (RelPtr o) = let initOff = anno ^. stmtAnno_offset labelId = LabelId $ initOff + o in ((SLabel (StatementAnnotation (initOff + o) (Just labelId) []) labelId), (SGoto anno labelId)) eAssign = EBinop Assign eAssignPlus = EBinop AssignPlus eAssignMinus = EBinop AssignMinus eAssignXor = EBinop AssignBitXor eAssignAnd = EBinop AssignBitAnd eAssignOr = EBinop AssignBitOr eAssignShiftRight = EBinop AssignBitShiftRight ePostIncrement = EUnop PostIncrement ePostDecrement = EUnop PostDecrement eNot = EUnop Not eAssignShiftLeft = EBinop AssignBitShiftLeft ePlus = EBinop Plus eMinus = EBinop Subtract eSub = EBinop Subtract eMultiply = EBinop Multiply eDivide = EBinop Divide eXor = EBinop BitXor eOr = EBinop BitOr eAnd = EBinop BitAnd eShiftRight = EBinop BitShiftRight eShiftLeft = EBinop BitShiftLeft eDereference = EUnop Dereference eZero = eImm8 $ Imm8 0 eOne = eImm8 $ Imm8 1 eImm8 = ELiteral . LImm8 eImm16 = ELiteral . LImm16 eImm32 = ELiteral . LImm32 pImm8 (ELiteral (LImm8 x)) = Just x pImm8 _ = Nothing pImm16 (ELiteral (LImm16 x)) = Just x pImm16 _ = Nothing pImm32 (ELiteral (LImm32 x)) = Just x pImm32 _ = Nothing reg16_odd :: Register -> Maybe Reg16 reg16_odd (Register 27) = Just RX reg16_odd (Register 29) = Just RY reg16_odd (Register 31) = Just RZ reg16_odd _ = Nothing replaceSingleInstructions :: Statement -> [ Statement ] replaceSingleInstructions stmt = let postInc = EUnop PostIncrement postDec = EUnop PostDecrement anyLdReg16 (Ldxp r) = Just (r, postInc (EReg16 RX)) anyLdReg16 (Ldyp r) = Just (r, postInc (EReg16 RY)) anyLdReg16 (Ldzp r) = Just (r, postInc (EReg16 RZ)) anyLdReg16 (Ldxm r) = Just (r, postInc (EReg16 RX)) anyLdReg16 (Ldym r) = Just (r, postInc (EReg16 RY)) anyLdReg16 (Ldzm r) = Just (r, postInc (EReg16 RZ)) anyLdReg16 (Ldx r) = Just (r, EReg16 RX) anyLdReg16 (Ldy r) = Just (r, EReg16 RY) anyLdReg16 (Ldz r) = Just (r, EReg16 RZ) anyLdReg16 _ = Nothing in case stmt of SAsm anno (iex_astI -> Eor r1 r2) | r1 == r2 -> [ SExpression anno $ eAssign (EReg8 r1) eZero ] SAsm anno (iex_astI -> Eor r1 r2) -> [ SExpression anno $ eAssignXor (EReg8 r1) (EReg8 r2) ] SAsm anno (iex_astI -> Andi r imm) -> [ SExpression anno $ eAssignAnd (EReg8 r) (eImm8 imm) ] SAsm anno (iex_astI -> And r1 r2) -> [ SExpression anno $ eAssignAnd (EReg8 r1) (EReg8 r2) ] SAsm anno (iex_astI -> Or r1 r2) -> [ SExpression anno $ eAssignOr (EReg8 r1) (EReg8 r2) ] SAsm anno (iex_astI -> Ori r imm) -> [ SExpression anno $ eAssignOr (EReg8 r) (eImm8 imm) ] SAsm anno (iex_astI -> Lsr r) -> [ SExpression anno $ eAssignShiftRight (EReg8 r) eOne ] SAsm anno (iex_astI -> Lsl r) -> [ SExpression anno $ eAssignShiftLeft (EReg8 r) eOne ] SAsm anno (iex_astI -> Mov r1 r2) -> [ SExpression anno $ eAssign (EReg8 r1) (EReg8 r2) ] SAsm anno (iex_astI -> Add r1 r2) -> [ SExpression anno $ eAssignPlus (EReg8 r1) (EReg8 r2) ] SAsm anno (iex_astI -> Lds r imm) -> [ SExpression anno $ EBinop Assign (EReg8 r) (EUnop Dereference $ ELiteral $ LImm16 imm) ] SAsm anno (iex_astI -> Lddx r imm) -> [SExpression anno $ EBinop Assign (EReg8 r) (EUnop Dereference $ EBinop Plus (EReg16 RX) (ELiteral $ LImm8 imm))] SAsm anno (iex_astI -> Lddy r imm) -> [SExpression anno $ EBinop Assign (EReg8 r) (EUnop Dereference $ EBinop Plus (EReg16 RY) (ELiteral $ LImm8 imm))] SAsm anno (iex_astI -> Lddz r imm) -> [SExpression anno $ EBinop Assign (EReg8 r) (EUnop Dereference $ EBinop Plus (EReg16 RZ) (ELiteral $ LImm8 imm))] SAsm anno (iex_astI -> Ldi r imm) -> [ SExpression anno $ EBinop Assign (EReg8 r) (ELiteral $ LImm8 imm) ] SAsm anno (iex_astI -> Adiw r1 imm) -> [ SExpression anno $ EBinop AssignPlus (EReg16 r1) (ELiteral $ LImm8 imm) ] SAsm anno (iex_astI -> Sbiw r1 imm) -> [ SExpression anno $ EBinop AssignMinus (EReg16 r1) (ELiteral $ LImm8 imm) ] SAsm anno (iex_astI -> Movw r1 r2) -> [ SExpression anno $ EBinop Assign (EReg16 r1) (EReg16 r2) ] SAsm anno (iex_astI -> (anyLdReg16 -> Just (r8, e))) -> [ SExpression anno $ EBinop Assign (EReg8 r8) (EUnop Dereference e) ] SAsm anno (iex_astI -> Ldxp r) -> [ SExpression anno $ EBinop Assign (EReg8 r) (EUnop PostIncrement (EUnop Dereference (EReg16 RX))) ] SAsm anno (iex_astI -> Ldyp r) -> [ SExpression anno $ EBinop Assign (EReg8 r) (EUnop PostIncrement (EUnop Dereference (EReg16 RY))) ] SAsm anno (iex_astI -> Ldyp r) -> [ SExpression anno $ EBinop Assign (EReg8 r) (EUnop PostIncrement (EUnop Dereference (EReg16 RY))) ] SAsm anno (iex_astI -> Stdz imm r) -> [ SExpression anno $ EBinop Assign (EUnop Dereference (EBinop Plus (EReg16 RZ) (ELiteral $ LImm8 imm))) (EReg8 r)] SAsm anno (iex_astI -> Stx r) -> [ SExpression anno $ eAssign (eDereference $ EReg16 RX) (EReg8 r)] SAsm anno (iex_astI -> Sty r) -> [ SExpression anno $ eAssign (eDereference $ EReg16 RY) (EReg8 r)] SAsm anno (iex_astI -> Stz r) -> [ SExpression anno $ eAssign (eDereference $ EReg16 RZ) (EReg8 r)] SAsm anno (iex_astI -> Stxp r) -> [ SExpression anno $ eAssign (eDereference $ ePostIncrement (EReg16 RX)) (EReg8 r) ] SAsm anno (iex_astI -> Stxm r) -> [ SExpression anno $ eAssign (eDereference $ ePostDecrement (EReg16 RX)) (EReg8 r) ] SAsm anno (iex_astI -> Styp q r) -> [ SExpression anno $ eAssign (eDereference $ ePlus (EReg16 RY) (eImm8 q)) (EReg8 r) ] SAsm anno (iex_astI -> Stzp r) -> [ SExpression anno $ eAssign (eDereference $ ePostIncrement (EReg16 RZ)) (EReg8 r) ] SAsm anno (iex_astI -> Icall) -> [ SExpression anno $ ECall (EReg16 RZ) [] ] SAsm anno (iex_astI -> Ret) -> [ SReturn anno Nothing ] SAsm anno (iex_astI -> Subi (reg16_odd->Just r16) (Imm8 i)) -> [ SExpression anno $ eAssignMinus (EReg16 r16) (eImm16 $ Imm16 $ i * 256) ] SAsm anno (iex_astI -> Subi r imm) -> [ SExpression anno $ eAssignMinus (EReg8 r) (eImm8 imm) ] SAsm anno (iex_astI -> Inc r) -> [ SExpression anno $ EUnop PreIncrement (EReg8 r) ] SAsm anno (iex_astI -> Dec r) -> [ SExpression anno $ EUnop PreDecrement (EReg8 r) ] SAsm anno (iex_astI -> Push r) -> [ SPush anno $ EReg8 r ] SAsm anno (iex_astI -> Pop r) -> [ SPop anno $ EReg8 r ] SAsm anno (iex_astI -> Swap r) -> let higher = eShiftLeft (eAnd (EReg8 r) (eImm8 $ Imm8 0x07)) (eImm8 $ Imm8 4) lower = eShiftRight (eAnd (EReg8 r) (eImm8 $ Imm8 0x70)) (eImm8 $ Imm8 4) in [ SExpression anno $ eAssign (EReg8 r) (eOr higher lower) ] _ -> [ stmt ] pass_replaceSingleInstructions :: Pass pass_replaceSingleInstructions = do ctx <- get ctx_statements %= map (replaceSubtree replaceSingleInstructions) return () replaceLocalJumpsWithGotos :: Statement -> [ Statement ] replaceLocalJumpsWithGotos stat = let emitForRelptr anno relptr = let (a,b) = labelAndGotoForRelptr anno relptr in [ a, b] in case stat of SAsm anno instr@(iex_astI -> Rjmp relptr) -> emitForRelptr anno relptr _ -> [ stat ] withPair r1 r2 f = case getRegisterPair r1 r2 of Nothing -> Nothing Just x -> f x withPairEither :: Register -> Register -> (Reg16 -> a) -> Maybe a withPairEither r1 r2 f = case getRegisterPair r1 r2 of Nothing -> f <$> getRegisterPair r2 r1 Just x -> Just $ f x converge :: (a -> a -> Bool) -> [a] -> a converge p (x:ys@(y:_)) | p x y = y | otherwise = converge p ys anyCompare :: Binop -> Bool anyCompare NotEqual = True anyCompare Equal = True anyCompare GreaterOrEqual = True anyCompare Greater = True anyCompare LessOrEqual = True anyCompare Less = True anyCompare _ = False expr_simplify :: Expression -> Maybe Expression expr_simplify = let lit (ELiteral x) = Just $ anyLiteral x lit _ = Nothing associativeBinop = \case Plus -> True Multiply -> True BitAnd -> True BitOr -> True BitXor -> True _ -> False in \case EBinop AssignPlus x1 x2 | x1 == x2 -> Just $ EBinop AssignMultiply x1 (eImm8 $ Imm8 2) EBinop binop@(anyCompare -> True) (EBinop Subtract e1 e2) (ELiteral (anyLiteral -> 0)) -> Just $ EBinop binop e1 e2 EUnop Not (EUnop Not x) -> Just x EBinop AssignMinus x1 e | e == eOne -> Just $ EUnop PreDecrement x1 EBinop Plus (EUnop PreDecrement x1) e | e == eOne -> Just $ EUnop PostDecrement x1 EBinop binop1@(associativeBinop -> True) (EBinop binop2@(associativeBinop -> True) e1 (lit -> Just x)) (lit -> Just y) | binop1 == binop2 -> Just $ EBinop binop1 e1 (EBinop binop1 (eImm8 $ Imm8 x) (eImm8 $ Imm8 x)) EBinop binop1@(associativeBinop -> True) (lit -> Just x) (EBinop binop2@(associativeBinop -> True) e1 (lit -> Just y)) | binop1 == binop2 -> Just $ EBinop binop1 e1 (EBinop binop1 (eImm8 $ Imm8 x) (eImm8 $ Imm8 x)) EBinop Plus (lit -> Just x) (lit -> Just y) -> Just $ eImm8 $ Imm8 $ x + y EBinop Subtract (lit -> Just x) (lit -> Just y) -> Just $ eImm8 $ Imm8 $ x - y EBinop Multiply (lit -> Just x) (lit -> Just y) -> Just $ eImm8 $ Imm8 $ x * y EBinop BitAnd (lit -> Just x) (lit -> Just y) -> Just $ eImm8 $ Imm8 $ x .&. y EBinop BitXor (lit -> Just x) (lit -> Just y) -> Just $ eImm8 $ Imm8 $ x `xor` y EBinop BitOr (lit -> Just x) (lit -> Just y) -> Just $ eImm8 $ Imm8 $ x .|. y EBinop AssignBitAnd e1 (lit -> Just 0) -> Just $ EBinop Assign e1 eZero x -> Nothing pass_simplify :: Pass pass_simplify = do ctx_statements %= map (converge (==) . iterate (replaceSubtree simplify)) ctx_statements %= map (replaceSubtree deleteEmptyBlocks) return () where simplify stmt = pure $ stmt & set_expr %~ \e -> fromMaybe e (expr_simplify e) deleteEmptyBlocks stmt = case stmt of (SBlock anno1 []) -> [] _ -> [ stmt ] expandAssignment :: Expression -> Expression expandAssignment x = let table binop = case binop of AssignPlus -> Just ePlus AssignMinus -> Just eMinus AssignMultiply -> Just eMultiply AssignDivide -> Just eDivide AssignBitXor -> Just eXor AssignBitOr -> Just eOr AssignBitAnd -> Just eAnd AssignBitShiftRight -> Just eShiftRight AssignBitShiftLeft -> Just eShiftLeft _ -> Nothing in case x of EBinop (table -> Just binop) a b -> eAssign a (binop a b) _ -> x anyLiteral :: Literal -> Int anyLiteral (LImm8 (Imm8 x)) = x anyLiteral (LImm16 (Imm16 x)) = x anyLiteral (LImm32 (Imm32 x)) = x assignBinop :: Binop -> Maybe Binop assignBinop AssignPlus = Just Plus assignBinop AssignMultiply = Just Multiply assignBinop AssignMinus = Just Subtract assignBinop AssignBitAnd = Just BitAnd assignBinop AssignBitOr = Just BitOr assignBinop AssignBitXor = Just BitXor assignBinop AssignBitShiftRight = Just BitShiftRight assignBinop AssignBitShiftLeft = Just BitShiftLeft assignBinop _ = Nothing swapStatements :: (Statement, Statement) -> (Statement, Statement) swapStatements (s1, s2) = let f = set (annotation . stmtAnno_offset) g x = x ^. annotation ^. stmtAnno_offset in (f (g s2) s1, f (g s1) s2) pass_reorderStatements :: Pass pass_reorderStatements = do ctx_statements %= map (converge (==) . iterate (replaceGroup 2 reorder2Statements)) return () where reorder2Statements stmts = case stmts of (s1@(SExpression anno1 e1): s2@(SExpression anno2 e2): []) | shouldSwap e1 e2 -> let (t1, t2) = swapStatements (s1, s2) in Just [ t1, t2 ] _ -> Nothing get :: (Eq a, Typeable a) => Expression -> [a] get e = foldMapOf template (pure) e check :: forall a. (Eq a, Typeable a) => Expression -> Expression -> Proxy a -> Bool check e1 e2 p = (get e1 :: [a]) `disjoint` (get e2 :: [a]) isDisjoint e1 e2 = check e1 e2 (Proxy :: Proxy Register) && check e1 e2 (Proxy :: Proxy Reg16) && check e1 e2 (Proxy :: Proxy VariableId) shouldSwap e1 e2 = case (e1, e2) of (EBinop binop1@(assignBinop -> Just _) x1 x2, EBinop binop2 y1 y2) -> isDisjoint x1 y2 && isDisjoint x2 y1 && (binop1 < binop2 || (binop1 == binop2 && shouldSwap x1 y1)) (EReg8 r1, EReg8 r2) -> r2 < r1 (_, EReg8 _) -> True (EReg16 r1, EReg16 r2) -> r2 < r1 _ -> False commutativeBinop = \case (assignBinop -> Just binop) -> commutativeBinop binop Plus -> True Multiply -> True BitAnd -> True BitXor -> True BitShiftRight -> True BitShiftLeft -> True _ -> False pass_fuse2Statements :: Pass pass_fuse2Statements = do ctx_statements %= map (converge (==) . iterate (replaceGroup 2 fuse2Statements)) return () where plusLike Plus = Just Plus plusLike Subtract = Just Subtract plusLike _ = Nothing fuse2Statements stmts = case stmts of (SExpression anno1 (EBinop binop1@(assignBinop -> Just binop2) x1 x2): SExpression anno2 (EBinop binop3@(assignBinop -> Just binop4) x3 x4): []) | x1 == x3 && binop1 == binop3 -> Just [ SExpression anno1 (EBinop binop1 x1 (EBinop binop2 x2 x4))] (SExpression anno1 (EBinop AssignBitShiftRight x1 x2): SExpression anno2 (EBinop AssignBitShiftRight x3 x4):[]) | x1 == x3 -> Just [SExpression anno1 (EBinop AssignBitShiftRight x1 (EBinop Plus x2 x4))] (SExpression anno1 (EBinop Assign x1 x2): SExpression anno2 (expandAssignment -> EBinop Assign x3 (EBinop binop x4 x5)):[]) | x1 == x3 && x3 == x4 -> Just [ SExpression anno1 (EBinop Assign x1 (EBinop binop x2 x5)) ] (SExpression anno1 e1: SExpression anno2 e2:[]) -> (pure . SExpression anno1) <$> fuse2Expressions [e1,e2] _ -> Nothing withExprPair :: Expression -> Expression -> (Expression -> Maybe Expression) -> Maybe Expression withExprPair x1 x2 f = case (x1, x2) of (EUnop Dereference e1, EUnop Dereference e2) -> withExprPair e1 e2 (f . EUnop Dereference) (EBinop (plusLike -> Just binop1) e1 e2, EBinop (plusLike -> Just binop2) e3 e4) | e2 == e4 && binop1 == binop2 -> withExprPair e1 e3 (f . (\e -> EBinop binop1 e e2)) (EBinop (plusLike -> Just binop1) e1 e2, EBinop (plusLike -> Just binop2) e3 e4) | e1 == e3 && binop1 == binop2 -> withExprPair e2 e4 (f . (\e -> EBinop binop2 e1 e)) (e1@(ELiteral (anyLiteral -> i1)), ELiteral (anyLiteral -> i2)) | i1 + 1 == i2 -> f e1 (ELiteral (anyLiteral -> i1), e2@(ELiteral (anyLiteral -> i2))) | i1 == i2 + 1 -> f e2 (pImm8 -> Just (Imm8 imm8_1), pImm8 -> Just (Imm8 imm8_2)) -> f $ eImm16 $ Imm16 $ imm8_1 + 256 * imm8_2 (EReg16 r16_1, EBinop Plus (EReg16 r16_2) (ELiteral (anyLiteral -> 1)))| r16_1 == r16_2 -> f $ EReg16 r16_1 (EBinop Plus (EReg16 r16_1) (ELiteral (anyLiteral -> 1)), EReg16 r16_2)| r16_1 == r16_2 -> f $ EReg16 r16_1 (EReg8 r1, EReg8 r2) -> f =<< withPairEither r1 r2 EReg16 _ -> Nothing fuse2Expressions :: [Expression] -> Maybe Expression fuse2Expressions exprs = case exprs of (EBinop Assign (EReg8 r1) x1: EBinop Assign (EReg8 r2) x2:[]) -> join $ withPairEither r1 r2 $ \r16 -> withExprPair x1 x2 $ \exp -> Just $ eAssign (EReg16 r16) exp (EBinop Assign x1 (EReg8 r1): EBinop Assign x2 (EReg8 r2):[]) -> join $ withPairEither r1 r2 $ \r16 -> withExprPair x1 x2 $ \exp -> Just $ eAssign exp (EReg16 r16) _ -> Nothing fuseMultibytePtrs :: [ Statement ] -> Maybe [ Statement ] fuseMultibytePtrs stmts = let lift2_reg16 anno r1 r2 r3 r4 binop = withPair r1 r2 $ \r16_1 -> withPair r3 r4 $ \r16_2 -> Just $ SExpression anno (EBinop binop (EReg16 r16_1) (EReg16 r16_2)) in case stmts of (SAsm anno1 (iex_astI -> (Add r1 r3)): SAsm anno2 (iex_astI -> (Adc r2 r4)):[]) -> pure <$> lift2_reg16 anno1 r1 r2 r3 r4 AssignPlus (SAsm anno1 (iex_astI -> (Subi r1 (Imm8 imm8_1))): SAsm anno2 (iex_astI -> (Sbci r2 (Imm8 imm8_2))):[]) -> withPair r1 r2 $ \r16 -> Just [ SExpression anno1 (EBinop AssignMinus (EReg16 r16) (ELiteral $ LImm8 (Imm8 $ imm8_1 + 2^8 * imm8_2))) ] (SAsm anno1 (iex_astI -> Sub r1 r3): SAsm anno2 (iex_astI -> Sbc r2 r4):[]) -> pure <$> lift2_reg16 anno1 r1 r2 r3 r4 AssignMinus (SAsm anno1 (iex_astI -> Mov r1 r3): SAsm anno2 (iex_astI -> Or r2 r4):[]) -> pure <$> lift2_reg16 anno1 r1 r2 r3 r4 Assign (SAsm anno1 (iex_astI -> Eor r1 r3): SAsm anno2 (iex_astI -> Eor r2 r4):[]) -> pure <$> lift2_reg16 anno1 r1 r2 r3 r4 AssignBitXor (SAsm anno1 (iex_astI -> Ldxp r1): SAsm anno2 (iex_astI -> Ldx r2):[]) -> withPair r1 r2 $ \r16 -> Just [ SExpression anno1 (EBinop Assign (EReg16 r16) (EUnop Dereference (EUnop PostIncrement (EReg16 RX))))] (SAsm anno1 (iex_astI -> Ldxp r1): SAsm anno2 (iex_astI -> Ldxp r2):[]) -> withPair r1 r2 $ \r16 -> Just [ SExpression anno1 (EBinop Assign (EReg16 r16) (EUnop Dereference (EUnop PostIncrement (EReg16 RX)))), SExpression anno1 (EUnop PostIncrement (EReg16 RX))] (SAsm anno1 (iex_astI -> Ldyp r1): SAsm anno2 (iex_astI -> Ldy r2):[]) -> withPair r1 r2 $ \r16 -> Just [ SExpression anno1 (EBinop Assign (EReg16 r16) (EUnop Dereference (EUnop PostIncrement (EReg16 RY))))] (SAsm anno1 (iex_astI -> Ldy r1): SAsm anno2 (iex_astI -> Lddy r2 (Imm8 1)):[]) -> withPair r1 r2 $ \r16 -> Just [ SExpression anno1 (EBinop Assign (EReg16 r16) (EUnop Dereference (EReg16 RY))) ] (SAsm anno1 (iex_astI -> Ldy r1): SAsm anno2 (iex_astI -> Lddy r2 (Imm8 1)):[]) -> withPair r1 r2 $ \r16 -> Just [ SExpression anno1 (EBinop Assign (EReg16 r16) (EUnop Dereference (EReg16 RY))) ] (SAsm anno1 (iex_astI -> Ldz r1): SAsm anno2 (iex_astI -> Lddz r2 (Imm8 1)):[]) -> withPair r1 r2 $ \r16 -> Just [ SExpression anno1 (EBinop Assign (EReg16 r16) (EUnop Dereference (EReg16 RZ))) ] (SAsm anno1 (iex_astI -> Push r1): SAsm anno2 (iex_astI -> Push r2): []) -> withPair r1 r2 $ \r16 -> Just [ SPush anno1 (EReg16 r16) ] (SAsm anno1 (iex_astI -> Pop r2): SAsm anno2 (iex_astI -> Pop r1): []) -> withPair r1 r2 $ \r16 -> Just [ SPop anno1 (EReg16 r16) ] _ -> Nothing anyBranch :: AstInstruction -> Maybe (RelPtr, Expression -> Expression) anyBranch (Brne relptr) = Just (relptr, id) anyBranch (Breq relptr) = Just (relptr, EUnop Not) anyBranch (Brge relptr) = Just (relptr, \e -> EBinop GreaterOrEqual e eZero) anyBranch (Brlt relptr) = Just (relptr, \e -> EBinop Less e eZero) anyBranch (Brcc relptr) = Just (relptr, \e -> EBinop GreaterOrEqual e eZero) anyBranch (Brcs relptr) = Just (relptr, \e -> EBinop Less e eZero) anyBranch _ = Nothing fuse3Instrs :: [ Statement ] -> Maybe [ Statement ] fuse3Instrs stmts = let compare e1 e2 e3 e4 = let sub1 = eSub e1 e3 sub2 = eSub e2 e4 condition = ePlus sub1 (eShiftLeft sub2 (eImm8 $ Imm8 8)) in condition anyBranchI = anyBranch . iex_astI genIfElse annoIf annoBlock relptr condMod condition = let (label,goto) = labelAndGotoForRelptr annoBlock relptr in Just [ label, SIfElse annoIf (condMod condition) goto (SBlock annoBlock []) ] in case stmts of (SAsm anno1 (iex_astI -> Cpi r1 imm): SAsm anno2 (iex_astI -> Cpc r2 r3): SAsm anno3 (anyBranchI -> Just (relptr, condMod)):[]) -> withPair r1 r2 $ \r16 -> genIfElse anno1 anno3 relptr condMod $ compare (EReg8 r1) (EReg8 r2) (eImm8 imm) (EReg8 r3) (SAsm anno1 (iex_astI -> Cp r1 r2): SAsm anno2 (iex_astI -> Cpc r3 r4):SAsm anno3 (anyBranchI -> Just (relptr, condMod)):[]) -> if r2 == regZero && r4 == regZero then withPair r1 r2 $ \r16 -> genIfElse anno1 anno3 relptr condMod $ EReg16 r16 else withPair r1 r3 $ \r16_1 -> withPair r2 r4 $ \r16_2 -> genIfElse anno1 anno3 relptr condMod $ eSub (EReg16 r16_1) (EReg16 r16_2) _ -> Nothing fuseRedundantLabels :: [ Statement ] -> Maybe [ Statement ] fuseRedundantLabels stmts = case stmts of (i@(SLabel ann1 (LabelId id1)): SLabel ann2 (LabelId id2): []) | id1 == id2 -> Just [ i ] _ -> Nothing pass_fuseMultibytePtrs :: Pass pass_fuseMultibytePtrs = do ctx_statements %= map (replaceGroup 2 fuseMultibytePtrs) return () pass_fuseRedundantLabels :: Pass pass_fuseRedundantLabels = do ctx_statements %= map (replaceGroup 2 fuseRedundantLabels) return () pass_fuse3Instrs :: Pass pass_fuse3Instrs =do ctx_statements %= map (replaceGroup 3 fuse3Instrs) return () replaceBranchesWithJumps :: [Statement] -> Maybe [ Statement ] replaceBranchesWithJumps stmts = case stmts of (SAsm x (iex_astI -> Or r1 r2): SAsm y (iex_astI -> Breq relptr):[]) -> withPair r1 r2 $ \r16 -> let (label, goto) = labelAndGotoForRelptr y relptr in Just [ label, SIfElse x (EUnop Not $ EReg16 r16) goto (SBlock y []) ] (SAsm x (iex_astI -> Or r1 r2): SAsm y (iex_astI -> Brne relptr):[]) -> withPair r1 r2 $ \r16 -> let (label, goto) = labelAndGotoForRelptr y relptr in Just [ label, SIfElse x (EReg16 r16) goto (SBlock y []) ] (SAsm anno instr@(iex_astI -> Sbrs r (BitIdx idx)) : s2 :[]) -> Just [ SIfElse anno (EUnop Not (EBinop BitAnd (EReg8 r) (ELiteral $ LImm8 $ Imm8 $ 2^idx))) s2 (SBlock anno [])] (SAsm anno1 (iex_astI -> And r1 r2): SAsm anno2 (iex_astI -> (anyBranch -> Just (relptr, condMod))):[]) | r1 == r2 -> let (label, goto) = labelAndGotoForRelptr anno2 relptr in Just [ label, SIfElse anno1 (condMod (EReg8 r1)) goto (SBlock anno2 [])] (SExpression anno1 e: SAsm anno2 (iex_astI -> (anyBranch -> Just (relptr, condMod))):[]) -> let (label, goto) = labelAndGotoForRelptr anno2 relptr in Just [ label, SIfElse anno1 (condMod e) goto (SBlock anno2 []) ] _ -> Nothing extractSubsequence :: (a -> Maybe b) -> (b -> a -> Maybe c) -> [a] -> ([a], (Maybe b, Maybe c, [a]),[a]) extractSubsequence fstart fstop xs = let g start middle end mStartS mStopS [] = (reverse start, (mStartS, mStopS, reverse middle), reverse end) g start middle end mStartS mStopS (x:xs) = case (mStartS, mStopS) of (Nothing, Nothing) -> case fstart x of Nothing -> g (x:start) middle end mStartS mStopS xs Just s -> g start (x:middle) end (Just s) mStopS xs (Just startS, Nothing) -> case fstop startS x of Nothing -> g start (x:middle) end mStartS mStopS xs _ | any isJust $ map (fstop startS) xs -> g start (x:middle) end mStartS mStopS xs Just s -> g start (x:middle) end mStartS (Just s) xs (Just startS, Just endS) -> g start middle (x:end) mStartS (Just endS) xs (Nothing, Just _) -> Prelude.error "extractSubsequence: Impossible case" in g [] [] [] Nothing Nothing xs -- | Given functions that mark the start and end of a subsequence, and a function to replace the subsequence, executes a replace of the entire sequence that changes only the subsequence. replaceSubsequence::(Statement-> Maybe a)-> (a-> Statement-> Maybe b) -> (a -> Maybe b -> [Statement] -> Maybe [Statement]) -> [ Statement ] -> Maybe [Statement] replaceSubsequence fstart fend ffinalize stmts = let (start, (ms_start, ms_end, middle), end) = extractSubsequence fstart fend stmts in case ms_start of Nothing -> Nothing Just s_start -> case ffinalize s_start ms_end middle of Nothing -> Nothing Just newMiddle -> Just $ start ++ newMiddle ++ end replaceBlockSubsequence ::(Statement->Maybe a)->(a->Statement->Maybe b)->(a->Maybe b->[Statement]->Maybe [Statement])->[Statement]->[Statement] replaceBlockSubsequence fstart fend ffinalize stmts = map (replaceSubtree f) stmts where f stmt = case stmt of SBlock _ children -> case replaceSubsequence fstart fend ffinalize children of Nothing -> [stmt] Just stmts -> stmts _ -> [ stmt ] pass_fuseLabelsAndGotosIntoWhileLoops :: Pass pass_fuseLabelsAndGotosIntoWhileLoops = do ctx_statements %= (replaceBlockSubsequence markLabel markGoto wrapWhile) return () where markLabel stmt = case stmt of SLabel _ labelId -> Just labelId _ -> Nothing markGoto labelId stmt = case stmt of SIfElse anno cond (SGoto _ gotoLabelId) (SBlock _ []) | labelId == gotoLabelId -> Just (anno, cond) SGoto anno gotoLabelId | labelId == gotoLabelId -> Just (anno, eImm8 $ Imm8 1) _ -> Nothing replaceGotosWithContinue labelId stmts = flip replaceSubtree stmts $ \case SGoto anno labelId2 | labelId == labelId2 -> [ SContinue (anno & stmtAnno_label .~ Just labelId) ] SLabel anno labelId2 | labelId == labelId2 -> [] stmt -> [ stmt ] wrapWhile labelId mEnd stmts = case mEnd of Nothing -> Nothing Just (anno, cond) -> let newStmts = map (replaceGotosWithContinue labelId) $ init stmts in Just [ SWhile anno cond (SBlock anno newStmts)] pass_fuseLabelsGotosIfsIntoIfBlocks :: Pass pass_fuseLabelsGotosIfsIntoIfBlocks = do ctx_statements %= (replaceBlockSubsequence markIf markLabel wrapIf) return () where markIf stmt = case stmt of SIfElse anno cond (SGoto _ labelId) (SBlock _ []) -> Just (anno, cond, labelId) _ -> Nothing markLabel (_, _, gotoLabelId) stmt = case stmt of label@(SLabel _ labelId) | gotoLabelId == labelId -> Just label _ -> Nothing wrapIf (anno, cond, labelId) mLabel stmts = case mLabel of Nothing -> Nothing Just label -> Just [ SIfElse anno (eNot cond) (SBlock anno $ init stmts) (SBlock (label ^. annotation) []), label ] offsetSymbolTable :: Table Symbol -> M.IntMap Symbol offsetSymbolTable symbolTable = M.fromList $ map (\(k, sym@(Symbol _ offset)) -> (offset, sym)) $ M.assocs $ symbolTable ^. elements fixPass :: String -> Pass -> Pass fixPass name pass = f 100 where f 0 = Prelude.error $ "fixPass: Recursion limit on " ++ name f n = do ctx1 <- get pass ctx2 <- get when (ctx1 /= ctx2) $ f (n-1) pass_rewriteCallInstructionsToCallSymbols :: Pass pass_rewriteCallInstructionsToCallSymbols = do ctx <- get let offsetTable = offsetSymbolTable $ ctx ^. ctx_functions ctx_statements %= map (replaceSubtree (rewriteCalls offsetTable)) return () where rewriteCalls offsetTable stmt = case stmt of SAsm anno (iex_astI -> Call (Imm32 offset)) -> case M.lookup offset offsetTable of Nothing -> [ stmt ] Just sym -> [ SExpression anno $ ECall (ESymbol sym) [] ] SAsm anno (iex_astI -> Jmp (AbsPtr offset)) -> case M.lookup offset offsetTable of Nothing -> [ stmt ] Just sym -> [ SGotoSymbol anno sym ] _ -> [ stmt ] newVar :: PassM VariableId newVar = do varId <- _nextId <$> _ctx_variables <$> get ctx_variables %= (& nextId %~ (+1)) return $ VariableId varId withNewVar :: (VariableId -> Pass) -> Pass withNewVar action = do varId <- newVar stmts1 <- (^. ctx_statements) <$> get action varId stmts2 <- (^. ctx_statements) <$> get if stmts1 == stmts2 then ctx_variables %= (& nextId %~ (subtract 1)) else return () expr_type :: Expression -> Type expr_type e = case e of ELiteral lit -> case lit of LImm8 _ -> TChar LImm16 _ -> TInt LImm32 _ -> TLong EUnop _ a -> expr_type a EBinop _ a b -> expr_type a ECall _ _ -> undefined EReg8 _ -> TChar EReg16 _ -> TInt ESymbol _ -> undefined EVariable _ -> undefined replaceExpression :: (Expression -> Maybe Expression) -> Statement -> Statement replaceExpression f stmt = stmt & set_expr %~ \e -> fromMaybe e (f e) pass_convertPushesAndPopsIntoVariables :: Pass pass_convertPushesAndPopsIntoVariables = withNewVar $ \varId -> ctx_statements %= (replaceBlockSubsequence markPush markPop (defineVariable varId)) where markPush stmt = case stmt of SPush anno e -> Just (anno, e) _ -> Nothing markPop (anno, e1) stmt = case stmt of SPop anno e2 | e1 == e2 -> Just anno _ -> Nothing defineVariable :: VariableId -> (StatementAnnotation, Expression) -> Maybe StatementAnnotation -> [ Statement ] -> Maybe [Statement] defineVariable varId (annoPush, e1) mAnnoPop stmts = case mAnnoPop of Nothing -> Nothing Just annoPop -> let declaration = SVariable annoPush varId (expr_type e1) $ Just e1 finish = SExpression annoPop $ EBinop Assign e1 (EVariable varId) eMod nodeE = if nodeE == e1 then Just $ EVariable varId else Nothing in Just $ [declaration] ++ (map (replaceExpression eMod) $ init $ tail stmts) ++ [finish]
MichaelBurge/stockfighter-jailbreak
src/Api/Stockfighter/Jailbreak/Decompiler/Passes.hs
bsd-3-clause
41,938
956
16
10,457
16,006
8,352
7,654
-1
-1
{-# LANGUAGE FlexibleContexts #-} -- | -- Module : Database.HyperDex.Internal.Util.Resource -- Copyright : (c) Aaron Friel 2014 -- License : BSD-style -- Maintainer : [email protected] -- Stability : unstable -- Portability : portable -- module Database.HyperDex.Internal.Util.Resource ( -- Resource Allocation rNew , rMallocArray , rMalloc , rNewCBString0 , rNewCBStringLen , unwrapResourceT -- Resource Contexts , ResourceContext , mkContext , runInContext , closeContext ) where import Control.Monad import Control.Monad.Base import Control.Monad.IO.Class import Control.Monad.Trans.Resource import Control.Monad.Trans.Resource.Internal import Control.Monad.Trans.Control (control) import qualified Control.Exception as E import Data.Acquire import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Data.ByteString.Unsafe (unsafeUseAsCString, unsafeUseAsCStringLen) -- See Note [Foreign imports] in Foreign.hs import Database.HyperDex.Internal.Util.Foreign import Foreign ( new, free, malloc, mallocArray, mallocArray0, copyBytes , newStablePtr, freeStablePtr, pokeElemOff ) import Foreign.C.String -- See Note [Resource handling] hAcquire :: IO a -> (a -> IO ()) -> Acquire a hAcquire createFn freeFn = mkAcquireType createFn freeFn' where freeFn' _ ReleaseException = return () freeFn' x _ = freeFn x {-# INLINE hAcquire #-} rNew :: (Storable a, MonadResource m) => a -> m (Ptr a) rNew a = fmap snd $ allocateAcquire $ hAcquire (new a) free rMallocArray :: (Storable a, MonadResource m) => Int -> m (Ptr a) rMallocArray sz = fmap snd $ allocateAcquire $ hAcquire (mallocArray sz) free rMalloc :: (Storable a, MonadResource m) => m (Ptr a) rMalloc = fmap snd $ allocateAcquire $ hAcquire malloc free -- | Run as a ResourceT but do not return resources until explicitly -- asked, or when freed by the garbage collector. -- -- In the latter case, the release type provided is "ReleaseException". -- See Note [Resource handling] for details. -- -- The internal state is newtype ResourceContext = ResourceContext InternalState mkContext :: MonadBase IO m => m ResourceContext mkContext = liftM ResourceContext createInternalState runInContext :: MonadBaseControl IO m => ResourceContext -> ResourceT m a -> m a runInContext (ResourceContext istate) (ResourceT r) = control $ \run -> E.mask $ \restore -> restore (run (r istate)) `E.onException` stateCleanup ReleaseException istate closeContext :: MonadBase IO m => ResourceContext -> m () closeContext (ResourceContext istate) = closeInternalState istate -- | Use a 'ByteString' as a NUL-terminated 'CString' in 'MonadResource'. -- -- /O(n) construction/ -- -- This method of construction permits several advantages to 'newCBString'. -- -- * If the 'ByteString' is already NUL terminated, the internal byte array is -- returned and no allocation occurs. This permits the consuming client to -- optimize strings for performance by constructing common strings with NUL -- terminations. -- -- * If the string requires NUL termination, a new string is allocated and freed -- when the resource monad completes or an exception is thrown. -- -- * When the allocation-less process occurs, to prevent garbage collection, a -- stable pointer to the parent ByteString is held with a 'StablePtr'. This -- also utilizes 'MonadResource'. -- rNewCBString0 :: MonadResource m => ByteString -> m CString rNewCBString0 bs = case isNulTerminated of True -> do (_, (_, cstr)) <- allocateAcquire $ hAcquire alloc' free' return cstr where alloc' = unsafeUseAsCString bs $ \cstr -> do ptr <- newStablePtr bs return (ptr, cstr) free' (ptr, _) = freeStablePtr ptr False -> do (_, cstr) <- allocateAcquire $ hAcquire alloc' free' return cstr where alloc' = unsafeUseAsCString bs $ \cstr -> do buf <- mallocArray0 bsLen copyBytes buf cstr bsLen pokeElemOff buf bsLen 0 return buf free' = free where bsLen = BS.length bs isNulTerminated = bsLen >= 1 && BS.last bs == 0 -- | Use a 'ByteString' as a 'CStringLen' in a 'MonadResource'. -- -- /O(1) construction/ -- -- This method of construction permits several advantages to 'newCBStringLen'. -- -- * The internal byte array is used without copying. -- -- * To prevent garbage collection of the internal storage of the ByteString, a -- stable pointer to the parent ByteString is held with a 'StablePtr'. This is -- freed when the resource monad completes or an exception is thrown. -- rNewCBStringLen :: MonadResource m => ByteString -> m CStringLen rNewCBStringLen bs = do (_, (_, cstrLen)) <- allocateAcquire $ hAcquire alloc' free' return cstrLen where alloc' = unsafeUseAsCStringLen bs $ \cstrLen -> do ptr <- newStablePtr bs return (ptr, cstrLen) free' (ptr, _) = freeStablePtr ptr -- | Run a ResourceT in an environment, capturing the resources it allocates and -- registering them in a parent MonadResource. Return the release key for the -- captured resources, and the result of the action. unwrapResourceT :: (MonadResource m, MonadBase IO m) => ResourceT IO a -> m (ReleaseKey, a) unwrapResourceT (ResourceT r) = do istate <- createInternalState rkey <- register (closeInternalState istate) result <- liftIO $ r istate return (rkey, result) {- Note [Resource handling] ~~~~~~~~~~~~~~~~~~~~~~ Pointers passed to HyperDex must live until the HyperDex library "_loop" function indicates that the call is complete. Resources in this library are thus allocated using the "registerType" and "mkAcquireType" functions which differentiate between normal, early, and failure release conditions. Consider this pseudocode example: 00 main = do 01 con <- connectToHyperDex 02 asyncResult <- get "Key" con 03 (something within the Hyhac library blows up the connection) 04 result <- asyncResult If we have freed the pointers that "get" allocates, the HyperDex library will write to their location regardless, and perform a use-after-free, which in the worst case could result in code execution. If for some reason the connection is lost in an error state, the resources allocated are held indefinitely. A memory leak is the preferred result. A future version may make this a toggle and permit a fail-fast alternative. -}
AaronFriel/hyhac
src/Database/HyperDex/Internal/Util/Resource.hs
bsd-3-clause
6,618
0
15
1,420
1,138
618
520
89
2
{-# LANGUAGE OverloadedStrings, RankNTypes #-} module Main where import Control.Monad.Trans import Data.Attoparsec import Prelude hiding (catch) import System.Console.Haskeline import System.Environment (getArgs, getEnv) import System.FilePath ((</>)) import qualified Data.ByteString as BS import Hummus.Types import Hummus.Parser import Hummus.Runtime import qualified Hummus.Prelude as Prelude main :: IO () main = do as <- getArgs runVM $ do Prelude.fromGround $ \e -> do case as of [] -> do home <- liftIO (getEnv "HOME") runInputT (defaultSettings { historyFile = Just (home </> ".hummus_history") }) (repl "" e) [f] -> do s <- liftIO (BS.readFile f) case parseOnly sexps s of Right ss -> mapM_ (evaluate e) ss Left m -> error m _ -> error "unknown argument form" return Inert return () -- TODO: super hacky instance MonadException (VM ans) where catch x _ = x -- TODO block x = x -- TODO unblock x = x -- TODO repl :: String -> Value ans -> InputT (VM ans) () repl p e = do mi <- getInputLine (if null p then "Hummus> " else "....... ") case mi of Just i -> case parse sexps (BS.pack . map (toEnum . fromEnum) $ p ++ i) of Done _ ss -> finish ss Fail rest context message -> do outputStrLn "Parse error!" outputStrLn ("at: " ++ show rest) if not (null context) then outputStrLn "Context:" else return () mapM_ (outputStrLn . (" " ++)) context outputStrLn message repl "" e Partial f -> case f "" of Done _ ss -> finish ss _ -> repl (p ++ i ++ "\n") e Nothing -> return () where finish ss = do v <- lift (evaluateSequence e ss) String s <- lift (evaluate e (Pair (Symbol "send") (Pair v (Pair (Symbol "->string") Null)))) outputStrLn s repl "" e
vito/hummus
src/Main.hs
bsd-3-clause
2,002
0
25
644
723
356
367
62
7
-- | -- Module: $Header$ -- Description: Data type representing environment variable. -- Copyright: (c) 2018-2020 Peter Trško -- License: BSD3 -- -- Maintainer: [email protected] -- Stability: experimental -- Portability: GHC specific language extensions. -- -- Data type representing environment variable. module CommandWrapper.Core.Config.Environment ( EnvironmentVariable(..) , toTuple , fromTuple ) where import GHC.Generics (Generic) import Text.Show (Show) import Dhall (FromDhall, ToDhall) import CommandWrapper.Core.Environment.Variable (EnvVarName, EnvVarValue) -- | Represents environment variable @name=value@. -- -- For example @FOO=bar@ would be: -- -- @ -- fooVar :: 'EnvironmentVariable' -- fooVar = 'EnvironmentVariable' -- { 'name' = \"FOO\" -- , 'value' = \"bar\" -- } -- @ -- -- Encoded into Dhall (with type annotation) it would be: -- -- > { name = "FOO", value = "bar" } : { name : Text, value : Text } data EnvironmentVariable = EnvironmentVariable { name :: EnvVarName , value :: EnvVarValue } deriving stock (Generic, Show) deriving anyclass (FromDhall, ToDhall) -- | Standard functions usually use tuples to represent environment variables. -- This function converts 'EnvironmentVariable' into such representation. Dual -- function is 'fromTuple' toTuple :: EnvironmentVariable -> (EnvVarName, EnvVarValue) toTuple EnvironmentVariable{name, value} = (name, value) -- | Standard functions usually use tuples to represent environment variables. -- This function converts such representation into 'EnvironmentVariable'. Dual -- function is 'toTuple' fromTuple :: (EnvVarName, EnvVarValue) -> EnvironmentVariable fromTuple (name, value) = EnvironmentVariable{..}
trskop/command-wrapper
command-wrapper-core/src/CommandWrapper/Core/Config/Environment.hs
bsd-3-clause
1,754
0
8
290
220
146
74
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Utility functions on @Core@ syntax -} {-# LANGUAGE CPP #-} module CoreSubst ( -- * Main data types Subst(..), -- Implementation exported for supercompiler's Renaming.hs only TvSubstEnv, IdSubstEnv, InScopeSet, -- ** Substituting into expressions and related types deShadowBinds, substSpec, substRulesForImportedIds, substTy, substCo, substExpr, substExprSC, substBind, substBindSC, substUnfolding, substUnfoldingSC, lookupIdSubst, lookupTCvSubst, substIdOcc, substTickish, substDVarSet, -- ** Operations on substitutions emptySubst, mkEmptySubst, mkSubst, mkOpenSubst, substInScope, isEmptySubst, extendIdSubst, extendIdSubstList, extendTCvSubst, extendTvSubstList, extendSubst, extendSubstList, extendSubstWithVar, zapSubstEnv, addInScopeSet, extendInScope, extendInScopeList, extendInScopeIds, isInScope, setInScope, delBndr, delBndrs, -- ** Substituting and cloning binders substBndr, substBndrs, substRecBndrs, cloneBndr, cloneBndrs, cloneIdBndr, cloneIdBndrs, cloneRecIdBndrs, -- ** Simple expression optimiser simpleOptPgm, simpleOptExpr, simpleOptExprWith, exprIsConApp_maybe, exprIsLiteral_maybe, exprIsLambda_maybe, ) where #include "HsVersions.h" import CoreSyn import CoreFVs import CoreSeq import CoreUtils import Literal ( Literal(MachStr) ) import qualified Data.ByteString as BS import OccurAnal( occurAnalyseExpr, occurAnalysePgm ) import qualified Type import qualified Coercion -- We are defining local versions import Type hiding ( substTy, extendTvSubst, extendCvSubst, extendTvSubstList , isInScope, substTyVarBndr, cloneTyVarBndr ) import Coercion hiding ( substCo, substCoVarBndr ) import TyCon ( tyConArity ) import DataCon import PrelNames import OptCoercion ( optCoercion ) import PprCore ( pprCoreBindings, pprRules ) import Module ( Module ) import VarSet import VarEnv import Id import Name ( Name ) import Var import IdInfo import UniqSupply import Maybes import ErrUtils import DynFlags import BasicTypes ( isAlwaysActive ) import Util import Pair import Outputable import PprCore () -- Instances import FastString import Data.List import TysWiredIn {- ************************************************************************ * * \subsection{Substitutions} * * ************************************************************************ -} -- | A substitution environment, containing 'Id', 'TyVar', and 'CoVar' -- substitutions. -- -- Some invariants apply to how you use the substitution: -- -- 1. #in_scope_invariant# The in-scope set contains at least those 'Id's and 'TyVar's that will be in scope /after/ -- applying the substitution to a term. Precisely, the in-scope set must be a superset of the free vars of the -- substitution range that might possibly clash with locally-bound variables in the thing being substituted in. -- -- 2. #apply_once# You may apply the substitution only /once/ -- -- There are various ways of setting up the in-scope set such that the first of these invariants hold: -- -- * Arrange that the in-scope set really is all the things in scope -- -- * Arrange that it's the free vars of the range of the substitution -- -- * Make it empty, if you know that all the free vars of the substitution are fresh, and hence can't possibly clash data Subst = Subst InScopeSet -- Variables in in scope (both Ids and TyVars) /after/ -- applying the substitution IdSubstEnv -- Substitution from NcIds to CoreExprs TvSubstEnv -- Substitution from TyVars to Types CvSubstEnv -- Substitution from CoVars to Coercions -- INVARIANT 1: See #in_scope_invariant# -- This is what lets us deal with name capture properly -- It's a hard invariant to check... -- -- INVARIANT 2: The substitution is apply-once; see Note [Apply once] with -- Types.TvSubstEnv -- -- INVARIANT 3: See Note [Extending the Subst] {- Note [Extending the Subst] ~~~~~~~~~~~~~~~~~~~~~~~~~~ For a core Subst, which binds Ids as well, we make a different choice for Ids than we do for TyVars. For TyVars, see Note [Extending the TCvSubst] with Type.TvSubstEnv For Ids, we have a different invariant The IdSubstEnv is extended *only* when the Unique on an Id changes Otherwise, we just extend the InScopeSet In consequence: * If all subst envs are empty, substExpr would be a no-op, so substExprSC ("short cut") does nothing. However, substExpr still goes ahead and substitutes. Reason: we may want to replace existing Ids with new ones from the in-scope set, to avoid space leaks. * In substIdBndr, we extend the IdSubstEnv only when the unique changes * If the CvSubstEnv, TvSubstEnv and IdSubstEnv are all empty, substExpr does nothing (Note that the above rule for substIdBndr maintains this property. If the incoming envts are both empty, then substituting the type and IdInfo can't change anything.) * In lookupIdSubst, we *must* look up the Id in the in-scope set, because it may contain non-trivial changes. Example: (/\a. \x:a. ...x...) Int We extend the TvSubstEnv with [a |-> Int]; but x's unique does not change so we only extend the in-scope set. Then we must look up in the in-scope set when we find the occurrence of x. * The requirement to look up the Id in the in-scope set means that we must NOT take no-op short cut when the IdSubst is empty. We must still look up every Id in the in-scope set. * (However, we don't need to do so for expressions found in the IdSubst itself, whose range is assumed to be correct wrt the in-scope set.) Why do we make a different choice for the IdSubstEnv than the TvSubstEnv and CvSubstEnv? * For Ids, we change the IdInfo all the time (e.g. deleting the unfolding), and adding it back later, so using the TyVar convention would entail extending the substitution almost all the time * The simplifier wants to look up in the in-scope set anyway, in case it can see a better unfolding from an enclosing case expression * For TyVars, only coercion variables can possibly change, and they are easy to spot -} -- | An environment for substituting for 'Id's type IdSubstEnv = IdEnv CoreExpr -- Domain is NcIds, i.e. not coercions ---------------------------- isEmptySubst :: Subst -> Bool isEmptySubst (Subst _ id_env tv_env cv_env) = isEmptyVarEnv id_env && isEmptyVarEnv tv_env && isEmptyVarEnv cv_env emptySubst :: Subst emptySubst = Subst emptyInScopeSet emptyVarEnv emptyVarEnv emptyVarEnv mkEmptySubst :: InScopeSet -> Subst mkEmptySubst in_scope = Subst in_scope emptyVarEnv emptyVarEnv emptyVarEnv mkSubst :: InScopeSet -> TvSubstEnv -> CvSubstEnv -> IdSubstEnv -> Subst mkSubst in_scope tvs cvs ids = Subst in_scope ids tvs cvs -- | Find the in-scope set: see "CoreSubst#in_scope_invariant" substInScope :: Subst -> InScopeSet substInScope (Subst in_scope _ _ _) = in_scope -- | Remove all substitutions for 'Id's and 'Var's that might have been built up -- while preserving the in-scope set zapSubstEnv :: Subst -> Subst zapSubstEnv (Subst in_scope _ _ _) = Subst in_scope emptyVarEnv emptyVarEnv emptyVarEnv -- | Add a substitution for an 'Id' to the 'Subst': you must ensure that the in-scope set is -- such that the "CoreSubst#in_scope_invariant" is true after extending the substitution like this extendIdSubst :: Subst -> Id -> CoreExpr -> Subst -- ToDo: add an ASSERT that fvs(subst-result) is already in the in-scope set extendIdSubst (Subst in_scope ids tvs cvs) v r = ASSERT2( isNonCoVarId v, ppr v $$ ppr r ) Subst in_scope (extendVarEnv ids v r) tvs cvs -- | Adds multiple 'Id' substitutions to the 'Subst': see also 'extendIdSubst' extendIdSubstList :: Subst -> [(Id, CoreExpr)] -> Subst extendIdSubstList (Subst in_scope ids tvs cvs) prs = ASSERT( all (isNonCoVarId . fst) prs ) Subst in_scope (extendVarEnvList ids prs) tvs cvs -- | Add a substitution for a 'TyVar' to the 'Subst' -- The 'TyVar' *must* be a real TyVar, and not a CoVar -- You must ensure that the in-scope set is such that -- the "CoreSubst#in_scope_invariant" is true after extending -- the substitution like this. extendTvSubst :: Subst -> TyVar -> Type -> Subst extendTvSubst (Subst in_scope ids tvs cvs) tv ty = ASSERT( isTyVar tv ) Subst in_scope ids (extendVarEnv tvs tv ty) cvs -- | Adds multiple 'TyVar' substitutions to the 'Subst': see also 'extendTvSubst' extendTvSubstList :: Subst -> [(TyVar,Type)] -> Subst extendTvSubstList subst vrs = foldl' extend subst vrs where extend subst (v, r) = extendTvSubst subst v r -- | Add a substitution from a 'CoVar' to a 'Coercion' to the 'Subst': you must ensure that the in-scope set is -- such that the "CoreSubst#in_scope_invariant" is true after extending the substitution like this extendCvSubst :: Subst -> CoVar -> Coercion -> Subst extendCvSubst (Subst in_scope ids tvs cvs) v r = ASSERT( isCoVar v ) Subst in_scope ids tvs (extendVarEnv cvs v r) -- | Add a substitution appropriate to the thing being substituted -- (whether an expression, type, or coercion). See also -- 'extendIdSubst', 'extendTvSubst', 'extendCvSubst' extendSubst :: Subst -> Var -> CoreArg -> Subst extendSubst subst var arg = case arg of Type ty -> ASSERT( isTyVar var ) extendTvSubst subst var ty Coercion co -> ASSERT( isCoVar var ) extendCvSubst subst var co _ -> ASSERT( isId var ) extendIdSubst subst var arg extendSubstWithVar :: Subst -> Var -> Var -> Subst extendSubstWithVar subst v1 v2 | isTyVar v1 = ASSERT( isTyVar v2 ) extendTvSubst subst v1 (mkTyVarTy v2) | isCoVar v1 = ASSERT( isCoVar v2 ) extendCvSubst subst v1 (mkCoVarCo v2) | otherwise = ASSERT( isId v2 ) extendIdSubst subst v1 (Var v2) -- | Add a substitution as appropriate to each of the terms being -- substituted (whether expressions, types, or coercions). See also -- 'extendSubst'. extendSubstList :: Subst -> [(Var,CoreArg)] -> Subst extendSubstList subst [] = subst extendSubstList subst ((var,rhs):prs) = extendSubstList (extendSubst subst var rhs) prs -- | Find the substitution for an 'Id' in the 'Subst' lookupIdSubst :: SDoc -> Subst -> Id -> CoreExpr lookupIdSubst doc (Subst in_scope ids _ _) v | not (isLocalId v) = Var v | Just e <- lookupVarEnv ids v = e | Just v' <- lookupInScope in_scope v = Var v' -- Vital! See Note [Extending the Subst] | otherwise = WARN( True, text "CoreSubst.lookupIdSubst" <+> doc <+> ppr v $$ ppr in_scope) Var v -- | Find the substitution for a 'TyVar' in the 'Subst' lookupTCvSubst :: Subst -> TyVar -> Type lookupTCvSubst (Subst _ _ tvs cvs) v | isTyVar v = lookupVarEnv tvs v `orElse` Type.mkTyVarTy v | otherwise = mkCoercionTy $ lookupVarEnv cvs v `orElse` mkCoVarCo v delBndr :: Subst -> Var -> Subst delBndr (Subst in_scope ids tvs cvs) v | isCoVar v = Subst in_scope ids tvs (delVarEnv cvs v) | isTyVar v = Subst in_scope ids (delVarEnv tvs v) cvs | otherwise = Subst in_scope (delVarEnv ids v) tvs cvs delBndrs :: Subst -> [Var] -> Subst delBndrs (Subst in_scope ids tvs cvs) vs = Subst in_scope (delVarEnvList ids vs) (delVarEnvList tvs vs) (delVarEnvList cvs vs) -- Easiest thing is just delete all from all! -- | Simultaneously substitute for a bunch of variables -- No left-right shadowing -- ie the substitution for (\x \y. e) a1 a2 -- so neither x nor y scope over a1 a2 mkOpenSubst :: InScopeSet -> [(Var,CoreArg)] -> Subst mkOpenSubst in_scope pairs = Subst in_scope (mkVarEnv [(id,e) | (id, e) <- pairs, isId id]) (mkVarEnv [(tv,ty) | (tv, Type ty) <- pairs]) (mkVarEnv [(v,co) | (v, Coercion co) <- pairs]) ------------------------------ isInScope :: Var -> Subst -> Bool isInScope v (Subst in_scope _ _ _) = v `elemInScopeSet` in_scope -- | Add the 'Var' to the in-scope set, but do not remove -- any existing substitutions for it addInScopeSet :: Subst -> VarSet -> Subst addInScopeSet (Subst in_scope ids tvs cvs) vs = Subst (in_scope `extendInScopeSetSet` vs) ids tvs cvs -- | Add the 'Var' to the in-scope set: as a side effect, -- and remove any existing substitutions for it extendInScope :: Subst -> Var -> Subst extendInScope (Subst in_scope ids tvs cvs) v = Subst (in_scope `extendInScopeSet` v) (ids `delVarEnv` v) (tvs `delVarEnv` v) (cvs `delVarEnv` v) -- | Add the 'Var's to the in-scope set: see also 'extendInScope' extendInScopeList :: Subst -> [Var] -> Subst extendInScopeList (Subst in_scope ids tvs cvs) vs = Subst (in_scope `extendInScopeSetList` vs) (ids `delVarEnvList` vs) (tvs `delVarEnvList` vs) (cvs `delVarEnvList` vs) -- | Optimized version of 'extendInScopeList' that can be used if you are certain -- all the things being added are 'Id's and hence none are 'TyVar's or 'CoVar's extendInScopeIds :: Subst -> [Id] -> Subst extendInScopeIds (Subst in_scope ids tvs cvs) vs = Subst (in_scope `extendInScopeSetList` vs) (ids `delVarEnvList` vs) tvs cvs setInScope :: Subst -> InScopeSet -> Subst setInScope (Subst _ ids tvs cvs) in_scope = Subst in_scope ids tvs cvs -- Pretty printing, for debugging only instance Outputable Subst where ppr (Subst in_scope ids tvs cvs) = text "<InScope =" <+> in_scope_doc $$ text " IdSubst =" <+> ppr ids $$ text " TvSubst =" <+> ppr tvs $$ text " CvSubst =" <+> ppr cvs <> char '>' where in_scope_doc = pprVarSet (getInScopeVars in_scope) (braces . fsep . map ppr) {- ************************************************************************ * * Substituting expressions * * ************************************************************************ -} -- | Apply a substitution to an entire 'CoreExpr'. Remember, you may only -- apply the substitution /once/: see "CoreSubst#apply_once" -- -- Do *not* attempt to short-cut in the case of an empty substitution! -- See Note [Extending the Subst] substExprSC :: SDoc -> Subst -> CoreExpr -> CoreExpr substExprSC doc subst orig_expr | isEmptySubst subst = orig_expr | otherwise = -- pprTrace "enter subst-expr" (doc $$ ppr orig_expr) $ subst_expr doc subst orig_expr substExpr :: SDoc -> Subst -> CoreExpr -> CoreExpr substExpr doc subst orig_expr = subst_expr doc subst orig_expr subst_expr :: SDoc -> Subst -> CoreExpr -> CoreExpr subst_expr doc subst expr = go expr where go (Var v) = lookupIdSubst (doc $$ text "subst_expr") subst v go (Type ty) = Type (substTy subst ty) go (Coercion co) = Coercion (substCo subst co) go (Lit lit) = Lit lit go (App fun arg) = App (go fun) (go arg) go (Tick tickish e) = mkTick (substTickish subst tickish) (go e) go (Cast e co) = Cast (go e) (substCo subst co) -- Do not optimise even identity coercions -- Reason: substitution applies to the LHS of RULES, and -- if you "optimise" an identity coercion, you may -- lose a binder. We optimise the LHS of rules at -- construction time go (Lam bndr body) = Lam bndr' (subst_expr doc subst' body) where (subst', bndr') = substBndr subst bndr go (Let bind body) = Let bind' (subst_expr doc subst' body) where (subst', bind') = substBind subst bind go (Case scrut bndr ty alts) = Case (go scrut) bndr' (substTy subst ty) (map (go_alt subst') alts) where (subst', bndr') = substBndr subst bndr go_alt subst (con, bndrs, rhs) = (con, bndrs', subst_expr doc subst' rhs) where (subst', bndrs') = substBndrs subst bndrs -- | Apply a substitution to an entire 'CoreBind', additionally returning an updated 'Subst' -- that should be used by subsequent substitutions. substBind, substBindSC :: Subst -> CoreBind -> (Subst, CoreBind) substBindSC subst bind -- Short-cut if the substitution is empty | not (isEmptySubst subst) = substBind subst bind | otherwise = case bind of NonRec bndr rhs -> (subst', NonRec bndr' rhs) where (subst', bndr') = substBndr subst bndr Rec pairs -> (subst', Rec (bndrs' `zip` rhss')) where (bndrs, rhss) = unzip pairs (subst', bndrs') = substRecBndrs subst bndrs rhss' | isEmptySubst subst' = rhss | otherwise = map (subst_expr (text "substBindSC") subst') rhss substBind subst (NonRec bndr rhs) = (subst', NonRec bndr' (subst_expr (text "substBind") subst rhs)) where (subst', bndr') = substBndr subst bndr substBind subst (Rec pairs) = (subst', Rec (bndrs' `zip` rhss')) where (bndrs, rhss) = unzip pairs (subst', bndrs') = substRecBndrs subst bndrs rhss' = map (subst_expr (text "substBind") subst') rhss -- | De-shadowing the program is sometimes a useful pre-pass. It can be done simply -- by running over the bindings with an empty substitution, because substitution -- returns a result that has no-shadowing guaranteed. -- -- (Actually, within a single /type/ there might still be shadowing, because -- 'substTy' is a no-op for the empty substitution, but that's probably OK.) -- -- [Aug 09] This function is not used in GHC at the moment, but seems so -- short and simple that I'm going to leave it here deShadowBinds :: CoreProgram -> CoreProgram deShadowBinds binds = snd (mapAccumL substBind emptySubst binds) {- ************************************************************************ * * Substituting binders * * ************************************************************************ Remember that substBndr and friends are used when doing expression substitution only. Their only business is substitution, so they preserve all IdInfo (suitably substituted). For example, we *want* to preserve occ info in rules. -} -- | Substitutes a 'Var' for another one according to the 'Subst' given, returning -- the result and an updated 'Subst' that should be used by subsequent substitutions. -- 'IdInfo' is preserved by this process, although it is substituted into appropriately. substBndr :: Subst -> Var -> (Subst, Var) substBndr subst bndr | isTyVar bndr = substTyVarBndr subst bndr | isCoVar bndr = substCoVarBndr subst bndr | otherwise = substIdBndr (text "var-bndr") subst subst bndr -- | Applies 'substBndr' to a number of 'Var's, accumulating a new 'Subst' left-to-right substBndrs :: Subst -> [Var] -> (Subst, [Var]) substBndrs subst bndrs = mapAccumL substBndr subst bndrs -- | Substitute in a mutually recursive group of 'Id's substRecBndrs :: Subst -> [Id] -> (Subst, [Id]) substRecBndrs subst bndrs = (new_subst, new_bndrs) where -- Here's the reason we need to pass rec_subst to subst_id (new_subst, new_bndrs) = mapAccumL (substIdBndr (text "rec-bndr") new_subst) subst bndrs substIdBndr :: SDoc -> Subst -- ^ Substitution to use for the IdInfo -> Subst -> Id -- ^ Substitution and Id to transform -> (Subst, Id) -- ^ Transformed pair -- NB: unfolding may be zapped substIdBndr _doc rec_subst subst@(Subst in_scope env tvs cvs) old_id = -- pprTrace "substIdBndr" (doc $$ ppr old_id $$ ppr in_scope) $ (Subst (in_scope `extendInScopeSet` new_id) new_env tvs cvs, new_id) where id1 = uniqAway in_scope old_id -- id1 is cloned if necessary id2 | no_type_change = id1 | otherwise = setIdType id1 (substTy subst old_ty) old_ty = idType old_id no_type_change = (isEmptyVarEnv tvs && isEmptyVarEnv cvs) || isEmptyVarSet (tyCoVarsOfType old_ty) -- new_id has the right IdInfo -- The lazy-set is because we're in a loop here, with -- rec_subst, when dealing with a mutually-recursive group new_id = maybeModifyIdInfo mb_new_info id2 mb_new_info = substIdInfo rec_subst id2 (idInfo id2) -- NB: unfolding info may be zapped -- Extend the substitution if the unique has changed -- See the notes with substTyVarBndr for the delVarEnv new_env | no_change = delVarEnv env old_id | otherwise = extendVarEnv env old_id (Var new_id) no_change = id1 == old_id -- See Note [Extending the Subst] -- it's /not/ necessary to check mb_new_info and no_type_change {- Now a variant that unconditionally allocates a new unique. It also unconditionally zaps the OccInfo. -} -- | Very similar to 'substBndr', but it always allocates a new 'Unique' for -- each variable in its output. It substitutes the IdInfo though. cloneIdBndr :: Subst -> UniqSupply -> Id -> (Subst, Id) cloneIdBndr subst us old_id = clone_id subst subst (old_id, uniqFromSupply us) -- | Applies 'cloneIdBndr' to a number of 'Id's, accumulating a final -- substitution from left to right cloneIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id]) cloneIdBndrs subst us ids = mapAccumL (clone_id subst) subst (ids `zip` uniqsFromSupply us) cloneBndrs :: Subst -> UniqSupply -> [Var] -> (Subst, [Var]) -- Works for all kinds of variables (typically case binders) -- not just Ids cloneBndrs subst us vs = mapAccumL (\subst (v, u) -> cloneBndr subst u v) subst (vs `zip` uniqsFromSupply us) cloneBndr :: Subst -> Unique -> Var -> (Subst, Var) cloneBndr subst uniq v | isTyVar v = cloneTyVarBndr subst v uniq | otherwise = clone_id subst subst (v,uniq) -- Works for coercion variables too -- | Clone a mutually recursive group of 'Id's cloneRecIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id]) cloneRecIdBndrs subst us ids = (subst', ids') where (subst', ids') = mapAccumL (clone_id subst') subst (ids `zip` uniqsFromSupply us) -- Just like substIdBndr, except that it always makes a new unique -- It is given the unique to use clone_id :: Subst -- Substitution for the IdInfo -> Subst -> (Id, Unique) -- Substitution and Id to transform -> (Subst, Id) -- Transformed pair clone_id rec_subst subst@(Subst in_scope idvs tvs cvs) (old_id, uniq) = (Subst (in_scope `extendInScopeSet` new_id) new_idvs tvs new_cvs, new_id) where id1 = setVarUnique old_id uniq id2 = substIdType subst id1 new_id = maybeModifyIdInfo (substIdInfo rec_subst id2 (idInfo old_id)) id2 (new_idvs, new_cvs) | isCoVar old_id = (idvs, extendVarEnv cvs old_id (mkCoVarCo new_id)) | otherwise = (extendVarEnv idvs old_id (Var new_id), cvs) {- ************************************************************************ * * Types and Coercions * * ************************************************************************ For types and coercions we just call the corresponding functions in Type and Coercion, but we have to repackage the substitution, from a Subst to a TCvSubst. -} substTyVarBndr :: Subst -> TyVar -> (Subst, TyVar) substTyVarBndr (Subst in_scope id_env tv_env cv_env) tv = case Type.substTyVarBndr (TCvSubst in_scope tv_env cv_env) tv of (TCvSubst in_scope' tv_env' cv_env', tv') -> (Subst in_scope' id_env tv_env' cv_env', tv') cloneTyVarBndr :: Subst -> TyVar -> Unique -> (Subst, TyVar) cloneTyVarBndr (Subst in_scope id_env tv_env cv_env) tv uniq = case Type.cloneTyVarBndr (TCvSubst in_scope tv_env cv_env) tv uniq of (TCvSubst in_scope' tv_env' cv_env', tv') -> (Subst in_scope' id_env tv_env' cv_env', tv') substCoVarBndr :: Subst -> TyVar -> (Subst, TyVar) substCoVarBndr (Subst in_scope id_env tv_env cv_env) cv = case Coercion.substCoVarBndr (TCvSubst in_scope tv_env cv_env) cv of (TCvSubst in_scope' tv_env' cv_env', cv') -> (Subst in_scope' id_env tv_env' cv_env', cv') -- | See 'Type.substTy' substTy :: Subst -> Type -> Type substTy subst ty = Type.substTyUnchecked (getTCvSubst subst) ty getTCvSubst :: Subst -> TCvSubst getTCvSubst (Subst in_scope _ tenv cenv) = TCvSubst in_scope tenv cenv -- | See 'Coercion.substCo' substCo :: Subst -> Coercion -> Coercion substCo subst co = Coercion.substCo (getTCvSubst subst) co {- ************************************************************************ * * \section{IdInfo substitution} * * ************************************************************************ -} substIdType :: Subst -> Id -> Id substIdType subst@(Subst _ _ tv_env cv_env) id | (isEmptyVarEnv tv_env && isEmptyVarEnv cv_env) || isEmptyVarSet (tyCoVarsOfType old_ty) = id | otherwise = setIdType id (substTy subst old_ty) -- The tyCoVarsOfType is cheaper than it looks -- because we cache the free tyvars of the type -- in a Note in the id's type itself where old_ty = idType id ------------------ -- | Substitute into some 'IdInfo' with regard to the supplied new 'Id'. substIdInfo :: Subst -> Id -> IdInfo -> Maybe IdInfo substIdInfo subst new_id info | nothing_to_do = Nothing | otherwise = Just (info `setRuleInfo` substSpec subst new_id old_rules `setUnfoldingInfo` substUnfolding subst old_unf) where old_rules = ruleInfo info old_unf = unfoldingInfo info nothing_to_do = isEmptyRuleInfo old_rules && isClosedUnfolding old_unf ------------------ -- | Substitutes for the 'Id's within an unfolding substUnfolding, substUnfoldingSC :: Subst -> Unfolding -> Unfolding -- Seq'ing on the returned Unfolding is enough to cause -- all the substitutions to happen completely substUnfoldingSC subst unf -- Short-cut version | isEmptySubst subst = unf | otherwise = substUnfolding subst unf substUnfolding subst df@(DFunUnfolding { df_bndrs = bndrs, df_args = args }) = df { df_bndrs = bndrs', df_args = args' } where (subst',bndrs') = substBndrs subst bndrs args' = map (substExpr (text "subst-unf:dfun") subst') args substUnfolding subst unf@(CoreUnfolding { uf_tmpl = tmpl, uf_src = src }) -- Retain an InlineRule! | not (isStableSource src) -- Zap an unstable unfolding, to save substitution work = NoUnfolding | otherwise -- But keep a stable one! = seqExpr new_tmpl `seq` unf { uf_tmpl = new_tmpl } where new_tmpl = substExpr (text "subst-unf") subst tmpl substUnfolding _ unf = unf -- NoUnfolding, OtherCon ------------------ substIdOcc :: Subst -> Id -> Id -- These Ids should not be substituted to non-Ids substIdOcc subst v = case lookupIdSubst (text "substIdOcc") subst v of Var v' -> v' other -> pprPanic "substIdOcc" (vcat [ppr v <+> ppr other, ppr subst]) ------------------ -- | Substitutes for the 'Id's within the 'WorkerInfo' given the new function 'Id' substSpec :: Subst -> Id -> RuleInfo -> RuleInfo substSpec subst new_id (RuleInfo rules rhs_fvs) = seqRuleInfo new_spec `seq` new_spec where subst_ru_fn = const (idName new_id) new_spec = RuleInfo (map (substRule subst subst_ru_fn) rules) (substDVarSet subst rhs_fvs) ------------------ substRulesForImportedIds :: Subst -> [CoreRule] -> [CoreRule] substRulesForImportedIds subst rules = map (substRule subst not_needed) rules where not_needed name = pprPanic "substRulesForImportedIds" (ppr name) ------------------ substRule :: Subst -> (Name -> Name) -> CoreRule -> CoreRule -- The subst_ru_fn argument is applied to substitute the ru_fn field -- of the rule: -- - Rules for *imported* Ids never change ru_fn -- - Rules for *local* Ids are in the IdInfo for that Id, -- and the ru_fn field is simply replaced by the new name -- of the Id substRule _ _ rule@(BuiltinRule {}) = rule substRule subst subst_ru_fn rule@(Rule { ru_bndrs = bndrs, ru_args = args , ru_fn = fn_name, ru_rhs = rhs , ru_local = is_local }) = rule { ru_bndrs = bndrs' , ru_fn = if is_local then subst_ru_fn fn_name else fn_name , ru_args = map (substExpr doc subst') args , ru_rhs = substExpr (text "foo") subst' rhs } -- Do NOT optimise the RHS (previously we did simplOptExpr here) -- See Note [Substitute lazily] where doc = text "subst-rule" <+> ppr fn_name (subst', bndrs') = substBndrs subst bndrs ------------------ substVects :: Subst -> [CoreVect] -> [CoreVect] substVects subst = map (substVect subst) ------------------ substVect :: Subst -> CoreVect -> CoreVect substVect subst (Vect v rhs) = Vect v (simpleOptExprWith subst rhs) substVect _subst vd@(NoVect _) = vd substVect _subst vd@(VectType _ _ _) = vd substVect _subst vd@(VectClass _) = vd substVect _subst vd@(VectInst _) = vd ------------------ substDVarSet :: Subst -> DVarSet -> DVarSet substDVarSet subst fvs = mkDVarSet $ fst $ foldr (subst_fv subst) ([], emptyVarSet) $ dVarSetElems fvs where subst_fv subst fv acc | isId fv = expr_fvs (lookupIdSubst (text "substDVarSet") subst fv) isLocalVar emptyVarSet $! acc | otherwise = tyCoFVsOfType (lookupTCvSubst subst fv) (const True) emptyVarSet $! acc ------------------ substTickish :: Subst -> Tickish Id -> Tickish Id substTickish subst (Breakpoint n ids) = Breakpoint n (map do_one ids) where do_one = getIdFromTrivialExpr . lookupIdSubst (text "subst_tickish") subst substTickish _subst other = other {- Note [Substitute lazily] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The functions that substitute over IdInfo must be pretty lazy, because they are knot-tied by substRecBndrs. One case in point was Trac #10627 in which a rule for a function 'f' referred to 'f' (at a differnet type) on the RHS. But instead of just substituting in the rhs of the rule, we were calling simpleOptExpr, which looked at the idInfo for 'f'; result <<loop>>. In any case we don't need to optimise the RHS of rules, or unfoldings, because the simplifier will do that. Note [substTickish] ~~~~~~~~~~~~~~~~~~~~~~ A Breakpoint contains a list of Ids. What happens if we ever want to substitute an expression for one of these Ids? First, we ensure that we only ever substitute trivial expressions for these Ids, by marking them as NoOccInfo in the occurrence analyser. Then, when substituting for the Id, we unwrap any type applications and abstractions to get back to an Id, with getIdFromTrivialExpr. Second, we have to ensure that we never try to substitute a literal for an Id in a breakpoint. We ensure this by never storing an Id with an unlifted type in a Breakpoint - see Coverage.mkTickish. Breakpoints can't handle free variables with unlifted types anyway. -} {- Note [Worker inlining] ~~~~~~~~~~~~~~~~~~~~~~ A worker can get sustituted away entirely. - it might be trivial - it might simply be very small We do not treat an InlWrapper as an 'occurrence' in the occurrence analyser, so it's possible that the worker is not even in scope any more. In all all these cases we simply drop the special case, returning to InlVanilla. The WARN is just so I can see if it happens a lot. ************************************************************************ * * The Very Simple Optimiser * * ************************************************************************ Note [Getting the map/coerce RULE to work] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We wish to allow the "map/coerce" RULE to fire: {-# RULES "map/coerce" map coerce = coerce #-} The naive core produced for this is forall a b (dict :: Coercible * a b). map @a @b (coerce @a @b @dict) = coerce @[a] @[b] @dict' where dict' :: Coercible [a] [b] dict' = ... This matches literal uses of `map coerce` in code, but that's not what we want. We want it to match, say, `map MkAge` (where newtype Age = MkAge Int) too. Some of this is addressed by compulsorily unfolding coerce on the LHS, yielding forall a b (dict :: Coercible * a b). map @a @b (\(x :: a) -> case dict of MkCoercible (co :: a ~R# b) -> x |> co) = ... Getting better. But this isn't exactly what gets produced. This is because Coercible essentially has ~R# as a superclass, and superclasses get eagerly extracted during solving. So we get this: forall a b (dict :: Coercible * a b). case Coercible_SCSel @* @a @b dict of _ [Dead] -> map @a @b (\(x :: a) -> case dict of MkCoercible (co :: a ~R# b) -> x |> co) = ... Unfortunately, this still abstracts over a Coercible dictionary. We really want it to abstract over the ~R# evidence. So, we have Desugar.unfold_coerce, which transforms the above to (see also Note [Desugaring coerce as cast] in Desugar) forall a b (co :: a ~R# b). let dict = MkCoercible @* @a @b co in case Coercible_SCSel @* @a @b dict of _ [Dead] -> map @a @b (\(x :: a) -> case dict of MkCoercible (co :: a ~R# b) -> x |> co) = let dict = ... in ... Now, we need simpleOptExpr to fix this up. It does so by taking three separate actions: 1. Inline certain non-recursive bindings. The choice whether to inline is made in maybe_substitute. Note the rather specific check for MkCoercible in there. 2. Stripping case expressions like the Coercible_SCSel one. See the `Case` case of simple_opt_expr's `go` function. 3. Look for case expressions that unpack something that was just packed and inline them. This is also done in simple_opt_expr's `go` function. This is all a fair amount of special-purpose hackery, but it's for a good cause. And it won't hurt other RULES and such that it comes across. -} simpleOptExpr :: CoreExpr -> CoreExpr -- Do simple optimisation on an expression -- The optimisation is very straightforward: just -- inline non-recursive bindings that are used only once, -- or where the RHS is trivial -- -- We also inline bindings that bind a Eq# box: see -- See Note [Getting the map/coerce RULE to work]. -- -- The result is NOT guaranteed occurrence-analysed, because -- in (let x = y in ....) we substitute for x; so y's occ-info -- may change radically simpleOptExpr expr = -- pprTrace "simpleOptExpr" (ppr init_subst $$ ppr expr) simpleOptExprWith init_subst expr where init_subst = mkEmptySubst (mkInScopeSet (exprFreeVars expr)) -- It's potentially important to make a proper in-scope set -- Consider let x = ..y.. in \y. ...x... -- Then we should remember to clone y before substituting -- for x. It's very unlikely to occur, because we probably -- won't *be* substituting for x if it occurs inside a -- lambda. -- -- It's a bit painful to call exprFreeVars, because it makes -- three passes instead of two (occ-anal, and go) simpleOptExprWith :: Subst -> InExpr -> OutExpr simpleOptExprWith subst expr = simple_opt_expr subst (occurAnalyseExpr expr) ---------------------- simpleOptPgm :: DynFlags -> Module -> CoreProgram -> [CoreRule] -> [CoreVect] -> IO (CoreProgram, [CoreRule], [CoreVect]) simpleOptPgm dflags this_mod binds rules vects = do { dumpIfSet_dyn dflags Opt_D_dump_occur_anal "Occurrence analysis" (pprCoreBindings occ_anald_binds $$ pprRules rules ); ; return (reverse binds', substRulesForImportedIds subst' rules, substVects subst' vects) } where occ_anald_binds = occurAnalysePgm this_mod (\_ -> False) {- No rules active -} rules vects emptyVarEnv binds (subst', binds') = foldl do_one (emptySubst, []) occ_anald_binds do_one (subst, binds') bind = case simple_opt_bind subst bind of (subst', Nothing) -> (subst', binds') (subst', Just bind') -> (subst', bind':binds') -- In these functions the substitution maps InVar -> OutExpr ---------------------- simple_opt_expr :: Subst -> InExpr -> OutExpr simple_opt_expr subst expr = go expr where in_scope_env = (substInScope subst, simpleUnfoldingFun) go (Var v) = lookupIdSubst (text "simpleOptExpr") subst v go (App e1 e2) = simple_app subst e1 [go e2] go (Type ty) = Type (substTy subst ty) go (Coercion co) = Coercion (optCoercion (getTCvSubst subst) co) go (Lit lit) = Lit lit go (Tick tickish e) = mkTick (substTickish subst tickish) (go e) go (Cast e co) | isReflCo co' = go e | otherwise = Cast (go e) co' where co' = optCoercion (getTCvSubst subst) co go (Let bind body) = case simple_opt_bind subst bind of (subst', Nothing) -> simple_opt_expr subst' body (subst', Just bind) -> Let bind (simple_opt_expr subst' body) go lam@(Lam {}) = go_lam [] subst lam go (Case e b ty as) -- See Note [Getting the map/coerce RULE to work] | isDeadBinder b , Just (con, _tys, es) <- exprIsConApp_maybe in_scope_env e' , Just (altcon, bs, rhs) <- findAlt (DataAlt con) as = case altcon of DEFAULT -> go rhs _ -> mkLets (catMaybes mb_binds) $ simple_opt_expr subst' rhs where (subst', mb_binds) = mapAccumL simple_opt_out_bind subst (zipEqual "simpleOptExpr" bs es) -- Note [Getting the map/coerce RULE to work] | isDeadBinder b , [(DEFAULT, _, rhs)] <- as , isCoercionType (varType b) , (Var fun, _args) <- collectArgs e , fun `hasKey` coercibleSCSelIdKey -- without this last check, we get #11230 = go rhs | otherwise = Case e' b' (substTy subst ty) (map (go_alt subst') as) where e' = go e (subst', b') = subst_opt_bndr subst b ---------------------- go_alt subst (con, bndrs, rhs) = (con, bndrs', simple_opt_expr subst' rhs) where (subst', bndrs') = subst_opt_bndrs subst bndrs ---------------------- -- go_lam tries eta reduction go_lam bs' subst (Lam b e) = go_lam (b':bs') subst' e where (subst', b') = subst_opt_bndr subst b go_lam bs' subst e | Just etad_e <- tryEtaReduce bs e' = etad_e | otherwise = mkLams bs e' where bs = reverse bs' e' = simple_opt_expr subst e ---------------------- -- simple_app collects arguments for beta reduction simple_app :: Subst -> InExpr -> [OutExpr] -> CoreExpr simple_app subst (App e1 e2) as = simple_app subst e1 (simple_opt_expr subst e2 : as) simple_app subst (Lam b e) (a:as) = case maybe_substitute subst b a of Just ext_subst -> simple_app ext_subst e as Nothing -> Let (NonRec b2 a) (simple_app subst' e as) where (subst', b') = subst_opt_bndr subst b b2 = add_info subst' b b' simple_app subst (Var v) as | isCompulsoryUnfolding (idUnfolding v) , isAlwaysActive (idInlineActivation v) -- See Note [Unfold compulsory unfoldings in LHSs] = simple_app subst (unfoldingTemplate (idUnfolding v)) as simple_app subst (Tick t e) as -- Okay to do "(Tick t e) x ==> Tick t (e x)"? | t `tickishScopesLike` SoftScope = mkTick t $ simple_app subst e as simple_app subst e as = foldl App (simple_opt_expr subst e) as ---------------------- simple_opt_bind,simple_opt_bind' :: Subst -> CoreBind -> (Subst, Maybe CoreBind) simple_opt_bind s b -- Can add trace stuff here = simple_opt_bind' s b simple_opt_bind' subst (Rec prs) = (subst'', res_bind) where res_bind = Just (Rec (reverse rev_prs')) (subst', bndrs') = subst_opt_bndrs subst (map fst prs) (subst'', rev_prs') = foldl do_pr (subst', []) (prs `zip` bndrs') do_pr (subst, prs) ((b,r), b') = case maybe_substitute subst b r2 of Just subst' -> (subst', prs) Nothing -> (subst, (b2,r2):prs) where b2 = add_info subst b b' r2 = simple_opt_expr subst r simple_opt_bind' subst (NonRec b r) = simple_opt_out_bind subst (b, simple_opt_expr subst r) ---------------------- simple_opt_out_bind :: Subst -> (InVar, OutExpr) -> (Subst, Maybe CoreBind) simple_opt_out_bind subst (b, r') | Just ext_subst <- maybe_substitute subst b r' = (ext_subst, Nothing) | otherwise = (subst', Just (NonRec b2 r')) where (subst', b') = subst_opt_bndr subst b b2 = add_info subst' b b' ---------------------- maybe_substitute :: Subst -> InVar -> OutExpr -> Maybe Subst -- (maybe_substitute subst in_var out_rhs) -- either extends subst with (in_var -> out_rhs) -- or returns Nothing maybe_substitute subst b r | Type ty <- r -- let a::* = TYPE ty in <body> = ASSERT( isTyVar b ) Just (extendTvSubst subst b ty) | Coercion co <- r = ASSERT( isCoVar b ) Just (extendCvSubst subst b co) | isId b -- let x = e in <body> , not (isCoVar b) -- See Note [Do not inline CoVars unconditionally] -- in SimplUtils , safe_to_inline (idOccInfo b) , isAlwaysActive (idInlineActivation b) -- Note [Inline prag in simplOpt] , not (isStableUnfolding (idUnfolding b)) , not (isExportedId b) , not (isUnliftedType (idType b)) || exprOkForSpeculation r = Just (extendIdSubst subst b r) | otherwise = Nothing where -- Unconditionally safe to inline safe_to_inline :: OccInfo -> Bool safe_to_inline (IAmALoopBreaker {}) = False safe_to_inline IAmDead = True safe_to_inline (OneOcc in_lam one_br _) = (not in_lam && one_br) || trivial safe_to_inline NoOccInfo = trivial trivial | exprIsTrivial r = True | (Var fun, args) <- collectArgs r , Just dc <- isDataConWorkId_maybe fun , dc `hasKey` heqDataConKey || dc `hasKey` coercibleDataConKey , all exprIsTrivial args = True -- See Note [Getting the map/coerce RULE to work] | otherwise = False ---------------------- subst_opt_bndr :: Subst -> InVar -> (Subst, OutVar) subst_opt_bndr subst bndr | isTyVar bndr = substTyVarBndr subst bndr | isCoVar bndr = substCoVarBndr subst bndr | otherwise = subst_opt_id_bndr subst bndr subst_opt_id_bndr :: Subst -> InId -> (Subst, OutId) -- Nuke all fragile IdInfo, unfolding, and RULES; -- it gets added back later by add_info -- Rather like SimplEnv.substIdBndr -- -- It's important to zap fragile OccInfo (which CoreSubst.substIdBndr -- carefully does not do) because simplOptExpr invalidates it subst_opt_id_bndr subst@(Subst in_scope id_subst tv_subst cv_subst) old_id = (Subst new_in_scope new_id_subst tv_subst cv_subst, new_id) where id1 = uniqAway in_scope old_id id2 = setIdType id1 (substTy subst (idType old_id)) new_id = zapFragileIdInfo id2 -- Zaps rules, worker-info, unfolding -- and fragile OccInfo new_in_scope = in_scope `extendInScopeSet` new_id -- Extend the substitution if the unique has changed, -- or there's some useful occurrence information -- See the notes with substTyVarBndr for the delSubstEnv new_id_subst | new_id /= old_id = extendVarEnv id_subst old_id (Var new_id) | otherwise = delVarEnv id_subst old_id ---------------------- subst_opt_bndrs :: Subst -> [InVar] -> (Subst, [OutVar]) subst_opt_bndrs subst bndrs = mapAccumL subst_opt_bndr subst bndrs ---------------------- add_info :: Subst -> InVar -> OutVar -> OutVar add_info subst old_bndr new_bndr | isTyVar old_bndr = new_bndr | otherwise = maybeModifyIdInfo mb_new_info new_bndr where mb_new_info = substIdInfo subst new_bndr (idInfo old_bndr) simpleUnfoldingFun :: IdUnfoldingFun simpleUnfoldingFun id | isAlwaysActive (idInlineActivation id) = idUnfolding id | otherwise = noUnfolding {- Note [Inline prag in simplOpt] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If there's an INLINE/NOINLINE pragma that restricts the phase in which the binder can be inlined, we don't inline here; after all, we don't know what phase we're in. Here's an example foo :: Int -> Int -> Int {-# INLINE foo #-} foo m n = inner m where {-# INLINE [1] inner #-} inner m = m+n bar :: Int -> Int bar n = foo n 1 When inlining 'foo' in 'bar' we want the let-binding for 'inner' to remain visible until Phase 1 Note [Unfold compulsory unfoldings in LHSs] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When the user writes `RULES map coerce = coerce` as a rule, the rule will only ever match if simpleOptExpr replaces coerce by its unfolding on the LHS, because that is the core that the rule matching engine will find. So do that for everything that has a compulsory unfolding. Also see Note [Desugaring coerce as cast] in Desugar. However, we don't want to inline 'seq', which happens to also have a compulsory unfolding, so we only do this unfolding only for things that are always-active. See Note [User-defined RULES for seq] in MkId. ************************************************************************ * * exprIsConApp_maybe * * ************************************************************************ Note [exprIsConApp_maybe] ~~~~~~~~~~~~~~~~~~~~~~~~~ exprIsConApp_maybe is a very important function. There are two principal uses: * case e of { .... } * cls_op e, where cls_op is a class operation In both cases you want to know if e is of form (C e1..en) where C is a data constructor. However e might not *look* as if Note [exprIsConApp_maybe on literal strings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See #9400. Conceptually, a string literal "abc" is just ('a':'b':'c':[]), but in Core they are represented as unpackCString# "abc"# by MkCore.mkStringExprFS, or unpackCStringUtf8# when the literal contains multi-byte UTF8 characters. For optimizations we want to be able to treat it as a list, so they can be decomposed when used in a case-statement. exprIsConApp_maybe detects those calls to unpackCString# and returns: Just (':', [Char], ['a', unpackCString# "bc"]). We need to be careful about UTF8 strings here. ""# contains a ByteString, so we must parse it back into a FastString to split off the first character. That way we can treat unpackCString# and unpackCStringUtf8# in the same way. Note [Push coercions in exprIsConApp_maybe] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In Trac #13025 I found a case where we had op (df @t1 @t2) -- op is a ClassOp where df = (/\a b. K e1 e2) |> g To get this to come out we need to simplify on the fly ((/\a b. K e1 e2) |> g) @t1 @t2 Hence the use of pushCoArgs. -} data ConCont = CC [CoreExpr] Coercion -- Substitution already applied -- | Returns @Just (dc, [t1..tk], [x1..xn])@ if the argument expression is -- a *saturated* constructor application of the form @dc t1..tk x1 .. xn@, -- where t1..tk are the *universally-qantified* type args of 'dc' exprIsConApp_maybe :: InScopeEnv -> CoreExpr -> Maybe (DataCon, [Type], [CoreExpr]) exprIsConApp_maybe (in_scope, id_unf) expr = go (Left in_scope) expr (CC [] (mkRepReflCo (exprType expr))) where go :: Either InScopeSet Subst -- Left in-scope means "empty substitution" -- Right subst means "apply this substitution to the CoreExpr" -> CoreExpr -> ConCont -> Maybe (DataCon, [Type], [CoreExpr]) go subst (Tick t expr) cont | not (tickishIsCode t) = go subst expr cont go subst (Cast expr co1) (CC args co2) | Just (args', co1') <- pushCoArgs (subst_co subst co1) args -- See Note [Push coercions in exprIsConApp_maybe] = go subst expr (CC args' (co1' `mkTransCo` co2)) go subst (App fun arg) (CC args co) = go subst fun (CC (subst_arg subst arg : args) co) go subst (Lam var body) (CC (arg:args) co) | exprIsTrivial arg -- Don't duplicate stuff! = go (extend subst var arg) body (CC args co) go (Right sub) (Var v) cont = go (Left (substInScope sub)) (lookupIdSubst (text "exprIsConApp" <+> ppr expr) sub v) cont go (Left in_scope) (Var fun) cont@(CC args co) | Just con <- isDataConWorkId_maybe fun , count isValArg args == idArity fun = dealWithCoercion co con args -- Look through dictionary functions; see Note [Unfolding DFuns] | DFunUnfolding { df_bndrs = bndrs, df_con = con, df_args = dfun_args } <- unfolding , bndrs `equalLength` args -- See Note [DFun arity check] , let subst = mkOpenSubst in_scope (bndrs `zip` args) = dealWithCoercion co con (map (substExpr (text "exprIsConApp1") subst) dfun_args) -- Look through unfoldings, but only arity-zero one; -- if arity > 0 we are effectively inlining a function call, -- and that is the business of callSiteInline. -- In practice, without this test, most of the "hits" were -- CPR'd workers getting inlined back into their wrappers, | idArity fun == 0 , Just rhs <- expandUnfolding_maybe unfolding , let in_scope' = extendInScopeSetSet in_scope (exprFreeVars rhs) = go (Left in_scope') rhs cont | (fun `hasKey` unpackCStringIdKey) || (fun `hasKey` unpackCStringUtf8IdKey) , [Lit (MachStr str)] <- args = dealWithStringLiteral fun str co where unfolding = id_unf fun go _ _ _ = Nothing ---------------------------- -- Operations on the (Either InScopeSet CoreSubst) -- The Left case is wildly dominant subst_co (Left {}) co = co subst_co (Right s) co = CoreSubst.substCo s co subst_arg (Left {}) e = e subst_arg (Right s) e = substExpr (text "exprIsConApp2") s e extend (Left in_scope) v e = Right (extendSubst (mkEmptySubst in_scope) v e) extend (Right s) v e = Right (extendSubst s v e) pushCoArgs :: Coercion -> [CoreArg] -> Maybe ([CoreArg], Coercion) pushCoArgs co [] = return ([], co) pushCoArgs co (arg:args) = do { (arg', co1) <- pushCoArg co arg ; (args', co2) <- pushCoArgs co1 args ; return (arg':args', co2) } pushCoArg :: Coercion -> CoreArg -> Maybe (CoreArg, Coercion) -- We have (fun |> co) arg, and we want to transform it to -- (fun arg) |> co -- This may fail, e.g. if (fun :: N) where N is a newtype -- C.f. simplCast in Simplify.hs pushCoArg co arg = case arg of Type ty | isForAllTy tyL -> ASSERT2( isForAllTy tyR, ppr co $$ ppr ty ) Just (Type ty, mkInstCo co (mkNomReflCo ty)) _ | isFunTy tyL , [co1, co2] <- decomposeCo 2 co -- If co :: (tyL1 -> tyL2) ~ (tyR1 -> tyR2) -- then co1 :: tyL1 ~ tyR1 -- co2 :: tyL2 ~ tyR2 -> ASSERT2( isFunTy tyR, ppr co $$ ppr arg ) Just (mkCast arg (mkSymCo co1), co2) _ -> Nothing where Pair tyL tyR = coercionKind co -- See Note [exprIsConApp_maybe on literal strings] dealWithStringLiteral :: Var -> BS.ByteString -> Coercion -> Maybe (DataCon, [Type], [CoreExpr]) -- This is not possible with user-supplied empty literals, MkCore.mkStringExprFS -- turns those into [] automatically, but just in case something else in GHC -- generates a string literal directly. dealWithStringLiteral _ str co | BS.null str = dealWithCoercion co nilDataCon [Type charTy] dealWithStringLiteral fun str co = let strFS = mkFastStringByteString str char = mkConApp charDataCon [mkCharLit (headFS strFS)] charTail = fastStringToByteString (tailFS strFS) -- In singleton strings, just add [] instead of unpackCstring# ""#. rest = if BS.null charTail then mkConApp nilDataCon [Type charTy] else App (Var fun) (Lit (MachStr charTail)) in dealWithCoercion co consDataCon [Type charTy, char, rest] dealWithCoercion :: Coercion -> DataCon -> [CoreExpr] -> Maybe (DataCon, [Type], [CoreExpr]) dealWithCoercion co dc dc_args | isReflCo co || from_ty `eqType` to_ty -- try cheap test first , let (univ_ty_args, rest_args) = splitAtList (dataConUnivTyVars dc) dc_args = Just (dc, map exprToType univ_ty_args, rest_args) | Just (to_tc, to_tc_arg_tys) <- splitTyConApp_maybe to_ty , to_tc == dataConTyCon dc -- These two tests can fail; we might see -- (C x y) `cast` (g :: T a ~ S [a]), -- where S is a type function. In fact, exprIsConApp -- will probably not be called in such circumstances, -- but there't nothing wrong with it = -- Here we do the KPush reduction rule as described in "Down with kinds" -- The transformation applies iff we have -- (C e1 ... en) `cast` co -- where co :: (T t1 .. tn) ~ to_ty -- The left-hand one must be a T, because exprIsConApp returned True -- but the right-hand one might not be. (Though it usually will.) let tc_arity = tyConArity to_tc dc_univ_tyvars = dataConUnivTyVars dc dc_ex_tyvars = dataConExTyVars dc arg_tys = dataConRepArgTys dc non_univ_args = dropList dc_univ_tyvars dc_args (ex_args, val_args) = splitAtList dc_ex_tyvars non_univ_args -- Make the "Psi" from the paper omegas = decomposeCo tc_arity co (psi_subst, to_ex_arg_tys) = liftCoSubstWithEx Representational dc_univ_tyvars omegas dc_ex_tyvars (map exprToType ex_args) -- Cast the value arguments (which include dictionaries) new_val_args = zipWith cast_arg arg_tys val_args cast_arg arg_ty arg = mkCast arg (psi_subst arg_ty) to_ex_args = map Type to_ex_arg_tys dump_doc = vcat [ppr dc, ppr dc_univ_tyvars, ppr dc_ex_tyvars, ppr arg_tys, ppr dc_args, ppr ex_args, ppr val_args, ppr co, ppr from_ty, ppr to_ty, ppr to_tc ] in ASSERT2( eqType from_ty (mkTyConApp to_tc (map exprToType $ takeList dc_univ_tyvars dc_args)), dump_doc ) ASSERT2( equalLength val_args arg_tys, dump_doc ) Just (dc, to_tc_arg_tys, to_ex_args ++ new_val_args) | otherwise = Nothing where Pair from_ty to_ty = coercionKind co {- Note [Unfolding DFuns] ~~~~~~~~~~~~~~~~~~~~~~ DFuns look like df :: forall a b. (Eq a, Eq b) -> Eq (a,b) df a b d_a d_b = MkEqD (a,b) ($c1 a b d_a d_b) ($c2 a b d_a d_b) So to split it up we just need to apply the ops $c1, $c2 etc to the very same args as the dfun. It takes a little more work to compute the type arguments to the dictionary constructor. Note [DFun arity check] ~~~~~~~~~~~~~~~~~~~~~~~ Here we check that the total number of supplied arguments (inclding type args) matches what the dfun is expecting. This may be *less* than the ordinary arity of the dfun: see Note [DFun unfoldings] in CoreSyn -} exprIsLiteral_maybe :: InScopeEnv -> CoreExpr -> Maybe Literal -- Same deal as exprIsConApp_maybe, but much simpler -- Nevertheless we do need to look through unfoldings for -- Integer literals, which are vigorously hoisted to top level -- and not subsequently inlined exprIsLiteral_maybe env@(_, id_unf) e = case e of Lit l -> Just l Tick _ e' -> exprIsLiteral_maybe env e' -- dubious? Var v | Just rhs <- expandUnfolding_maybe (id_unf v) -> exprIsLiteral_maybe env rhs _ -> Nothing {- Note [exprIsLambda_maybe] ~~~~~~~~~~~~~~~~~~~~~~~~~~ exprIsLambda_maybe will, given an expression `e`, try to turn it into the form `Lam v e'` (returned as `Just (v,e')`). Besides using lambdas, it looks through casts (using the Push rule), and it unfolds function calls if the unfolding has a greater arity than arguments are present. Currently, it is used in Rules.match, and is required to make "map coerce = coerce" match. -} exprIsLambda_maybe :: InScopeEnv -> CoreExpr -> Maybe (Var, CoreExpr,[Tickish Id]) -- See Note [exprIsLambda_maybe] -- The simple case: It is a lambda already exprIsLambda_maybe _ (Lam x e) = Just (x, e, []) -- Still straightforward: Ticks that we can float out of the way exprIsLambda_maybe (in_scope_set, id_unf) (Tick t e) | tickishFloatable t , Just (x, e, ts) <- exprIsLambda_maybe (in_scope_set, id_unf) e = Just (x, e, t:ts) -- Also possible: A casted lambda. Push the coercion inside exprIsLambda_maybe (in_scope_set, id_unf) (Cast casted_e co) | Just (x, e,ts) <- exprIsLambda_maybe (in_scope_set, id_unf) casted_e -- Only do value lambdas. -- this implies that x is not in scope in gamma (makes this code simpler) , not (isTyVar x) && not (isCoVar x) , ASSERT( not $ x `elemVarSet` tyCoVarsOfCo co) True , Just (x',e') <- pushCoercionIntoLambda in_scope_set x e co , let res = Just (x',e',ts) = --pprTrace "exprIsLambda_maybe:Cast" (vcat [ppr casted_e,ppr co,ppr res)]) res -- Another attempt: See if we find a partial unfolding exprIsLambda_maybe (in_scope_set, id_unf) e | (Var f, as, ts) <- collectArgsTicks tickishFloatable e , idArity f > count isValArg as -- Make sure there is hope to get a lambda , Just rhs <- expandUnfolding_maybe (id_unf f) -- Optimize, for beta-reduction , let e' = simpleOptExprWith (mkEmptySubst in_scope_set) (rhs `mkApps` as) -- Recurse, because of possible casts , Just (x', e'', ts') <- exprIsLambda_maybe (in_scope_set, id_unf) e' , let res = Just (x', e'', ts++ts') = -- pprTrace "exprIsLambda_maybe:Unfold" (vcat [ppr e, ppr (x',e'')]) res exprIsLambda_maybe _ _e = -- pprTrace "exprIsLambda_maybe:Fail" (vcat [ppr _e]) Nothing pushCoercionIntoLambda :: InScopeSet -> Var -> CoreExpr -> Coercion -> Maybe (Var, CoreExpr) pushCoercionIntoLambda in_scope x e co -- This implements the Push rule from the paper on coercions -- Compare with simplCast in Simplify | ASSERT(not (isTyVar x) && not (isCoVar x)) True , Pair s1s2 t1t2 <- coercionKind co , Just (_s1,_s2) <- splitFunTy_maybe s1s2 , Just (t1,_t2) <- splitFunTy_maybe t1t2 = let [co1, co2] = decomposeCo 2 co -- Should we optimize the coercions here? -- Otherwise they might not match too well x' = x `setIdType` t1 in_scope' = in_scope `extendInScopeSet` x' subst = extendIdSubst (mkEmptySubst in_scope') x (mkCast (Var x') co1) in Just (x', subst_expr (text "pushCoercionIntoLambda") subst e `mkCast` co2) | otherwise = pprTrace "exprIsLambda_maybe: Unexpected lambda in case" (ppr (Lam x e)) Nothing
olsner/ghc
compiler/coreSyn/CoreSubst.hs
bsd-3-clause
60,824
1
16
15,584
11,701
6,135
5,566
694
13
module Ch3 ( myTail, setHead, myDrop, myDropWhile, myInit, foldRight, sum2, product2, myLength, foldLeft, sum3, product3, myReverse, append2, succAll, toStringAll, myFilter, flatMap, filter2, sumList, myZipWith, allSubList, hasSubsequence, Tree(Leaf, Branch), nodeCount, maxValue, treeDepth, treeMap, nodeCount2, maxValue2, treeDepth2 ) where myTail :: [a] -> [a] myTail (_:xs) = xs setHead :: [a] -> a -> [a] setHead (_:xs) x = x : xs myDrop :: [a] -> Integer -> [a] myDrop xs n | n == 0 = xs | otherwise = myDrop (myTail xs) (pred n) myDropWhile :: [a] -> (a -> Bool) -> [a] myDropWhile xs f | f (head xs) = xs | otherwise = myDropWhile (myTail xs) f myInit :: [a] -> [a] myInit [_] = [] myInit (x:xs) = x : myInit xs foldRight :: [a] -> b -> (a -> b -> b) -> b foldRight [] b _ = b foldRight (x:xs) b f = f x (foldRight xs b f) sum2 :: [Integer] -> Integer sum2 xs = foldRight xs 0 (+) product2 :: [Integer] -> Integer product2 xs = foldRight xs 1 (*) myLength :: [a] -> Integer myLength xs = foldRight xs 0 (\_ y -> y + 1) foldLeft :: [a] -> b -> (a -> b -> b) -> b foldLeft [] b _ = b foldLeft (x:xs) b f = foldLeft xs (f x b) f sum3 :: [Integer] -> Integer sum3 xs = foldLeft xs 0 (+) product3 :: [Integer] -> Integer product3 xs = foldLeft xs 1 (*) myReverse :: [a] -> [a] myReverse xs = foldLeft xs [] (:) append2 :: [a] -> [a] -> [a] append2 xs ys = foldLeft (myReverse xs) ys (:) myMap :: [a] -> (a -> b) -> [b] myMap xs f = myReverse (foldLeft xs [] (\x y -> f x : y)) succAll :: [Integer] -> [Integer] succAll xs = myMap xs succ toStringAll :: [Double] -> [String] toStringAll xs = myMap xs show myFilter :: [a] -> (a -> Bool) -> [a] myFilter xs f = myReverse (foldLeft xs [] (\x y -> if f x then x : y else y)) flatMap :: [a] -> (a -> [b]) -> [b] flatMap xs f = foldLeft xs [] (\x y -> append2 y (f x)) filter2 :: [a] -> (a -> Bool) -> [a] filter2 xs f = flatMap xs (\x -> [x | f x]) sumList :: [Integer] -> [Integer] -> [Integer] sumList [] [] = [] sumList (x:xs) (y:ys) = append2 [(x + y)] (sumList xs ys) myZipWith :: (a -> a -> a) -> [a] -> [a] -> [a] myZipWith _ [] [] = [] myZipWith f (x:xs) (y:ys) = append2 [f x y] (myZipWith f xs ys) myInits :: [a] -> [[a]] myInits [] = [] myInits xs = append2 [xs] (myInits (myInit xs)) allSubList :: [a] -> [[a]] allSubList [] = [] allSubList xs = append2 (myInits xs) (allSubList (myTail xs)) hasSubsequence :: Eq a => [a] -> [a] -> Bool hasSubsequence xs ys = foldLeft (allSubList xs) False (\x result -> if result then result else x == ys) data Tree a = Leaf a | Branch (Tree a) (Tree a) nodeCount :: Tree a -> Int nodeCount (Leaf x) = 1 nodeCount (Branch left right) = (nodeCount left) + (nodeCount right) maxValue :: (Ord a) => Tree a -> a maxValue (Leaf x) = x maxValue (Branch left right) = max (maxValue left) (maxValue right) treeDepth :: Tree a -> Int treeDepth (Leaf x) = 0 treeDepth (Branch left right) = (max (treeDepth left) (treeDepth right)) + 1 treeMap :: (b -> b -> b) -> (a -> b) -> Tree a -> b treeMap bf lf (Leaf x) = lf x treeMap bf lf (Branch left right) = bf (treeMap bf lf left) (treeMap bf lf right) nodeCount2 :: Tree a -> Int nodeCount2 tree = treeMap (\x y -> x + y) (\x -> 1) tree maxValue2 :: (Ord a) => Tree a -> a maxValue2 tree = treeMap (\x y -> max x y) (\x -> x) tree treeDepth2 :: Tree a -> Int treeDepth2 tree = treeMap (\x y -> (max x y) + 1) (\x -> 0) tree
eunmin/fpis-hs
src/Ch3.hs
bsd-3-clause
3,797
0
11
1,142
1,954
1,046
908
117
2
{-# LANGUAGE TemplateHaskell #-} module EFA.Test.Sequence where import qualified EFA.Signal.Sequence as Sequ import qualified EFA.Signal.Chop as Chop import qualified EFA.Signal.Signal as Signal import EFA.Signal.Record (PowerRecord, Record(Record)) import qualified EFA.Graph.Topology.Node as Node import qualified Data.Foldable as Fold import qualified Data.List.HT as ListHT -- import Test.QuickCheck (Property, (==>)) import Test.QuickCheck.All (quickCheckAll) type Node = Node.Int prop_genSequ :: PowerRecord Node [] Double -> Bool prop_genSequ prec = Chop.approxSequPwrRecord (1e-8) (Chop.genSequ $ Chop.addZeroCrossings prec) -- (Chop.chopAtZeroCrossingsPowerRecord prec) (Chop.chopAtZeroCrossingsPowerRecord False prec) prop_chopMatchingCutsApprox :: Bool -> PowerRecord Node [] Double -> Bool prop_chopMatchingCutsApprox duplicates prec = eqAdjacent (\(Record xt xm) (Record yt ym) -> fmap snd (Signal.viewR xt) == fmap fst (Signal.viewL yt) && fmap (fmap snd . Signal.viewR) xm == fmap (fmap fst . Signal.viewL) ym) (Chop.chopAtZeroCrossingsPowerRecord duplicates prec :: Sequ.List (PowerRecord Node [] Double)) prop_chopProjectiveApprox :: PowerRecord Node [] Double -> Bool prop_chopProjectiveApprox prec = let secs :: Sequ.List (PowerRecord Node [] Double) secs = Chop.chopAtZeroCrossingsPowerRecord False prec in Chop.approxSequPwrRecord (1e-8) secs (Chop.chopAtZeroCrossingsPowerRecord False $ Chop.concatPowerRecords secs) prop_chopMatchingCutsExact :: Bool -> PowerRecord Node [] Rational -> Bool prop_chopMatchingCutsExact duplicates prec = eqAdjacent (\(Record xt xm) (Record yt ym) -> fmap snd (Signal.viewR xt) == fmap fst (Signal.viewL yt) && fmap (fmap snd . Signal.viewR) xm == fmap (fmap fst . Signal.viewL) ym) (Chop.chopAtZeroCrossingsPowerRecord duplicates prec :: Sequ.List (PowerRecord Node [] Rational)) prop_chopProjectiveExact :: PowerRecord Node [] Rational -> Bool prop_chopProjectiveExact prec = let secs :: Sequ.List (PowerRecord Node [] Rational) secs = Chop.chopAtZeroCrossingsPowerRecord False prec in secs == (Chop.chopAtZeroCrossingsPowerRecord False $ Chop.concatPowerRecords secs) eqAdjacent :: (a -> a -> Bool) -> Sequ.List a -> Bool eqAdjacent f = and . ListHT.mapAdjacent f . Fold.toList runTests :: IO Bool runTests = $quickCheckAll
energyflowanalysis/efa-2.1
test/EFA/Test/Sequence.hs
bsd-3-clause
2,538
0
14
534
741
388
353
61
1
{-# LANGUAGE NoMonomorphismRestriction #-} module Main where import Graphics.UI.Gtk as Gtk import Data.IORef import Diagrams.Prelude import Diagrams.Backend.Gtk import Control.Monad.IO.Class (liftIO) import Types import Graphics import Game createMainWindow :: IORef GameState -> IO Window createMainWindow gameStateRef = do let winW = 640 winH = 640 win <- windowNew Gtk.set win [windowDefaultWidth := winW, windowDefaultHeight := winH] _ <- onSizeRequest win $ return (Requisition winW winH) _ <- onDestroy win mainQuit drawArea <- drawingAreaNew _ <- drawArea `onExpose` \_dirtyRect -> do gameState <- readIORef gameStateRef windowSetTitle win (gameScore gameState) (canvasX,canvasY) <- widgetGetSize drawArea let dia = gameDiagram gameState spec = dims $ V2 (fromIntegral canvasX) (fromIntegral canvasY) scaledDia = toGtkCoords $ transform (requiredScaling spec (size dia)) dia drawWindow <- widgetGetDrawWindow drawArea renderToGtk drawWindow scaledDia return True _ <- drawArea `on` buttonPressEvent $ tryEvent $ do (x, y) <- eventCoordinates let mousePos = floor <$> V2 (x / winW) ((winH - y) / winH) * 8 liftIO $ do updateGameState gameStateRef mousePos widgetQueueDraw drawArea containerAdd win drawArea return win main :: IO () main = do _ <- initGUI gameState <- newIORef initialGameState win <- createMainWindow gameState widgetShowAll win mainGUI
korrix/Warcaby
Main.hs
bsd-3-clause
1,479
0
20
306
473
230
243
44
1
-- just variants, records, functions module Day4 where type RecordDesc = [ ( String -- name , Desc -- what it points to ) ] -- wow it looks the same as RecordDesc :P type VariantDesc = [(String, Desc)] data FunDesc = Arrow Desc Desc deriving (Show, Eq) data Desc = DescRecord RecordDesc | DescVariant VariantDesc | DescFun FunDesc | Param Int deriving (Show, Eq) list :: Desc list = DescVariant [ ("listNil", DescRecord []) -- v- `a` v- `self` , ("listCons", DescRecord [("listHead", Param 0), ("listTail", Param 1)]) ] -- that gives us sums, products, and exponentials -- -- now, to instantiate, typecheck, and eliminate (pattern match / execute) them -- Match against the alternatives in a sum type VariantMatch = [(String, Match, Data)] -- Match a product (whoa, we just pairwise match) type RecordPattern = [Match] data Match = MatchVariant VariantMatch | MatchRecord RecordPattern | MatchWildcard | MatchVariable -- type Record = [(String, Data)] type Variant = (String, Data) -- we need pattern match the argument and emit Data data Fun = Fun Match Data data Data = DataRecord Record | DataVariant Variant | DataFun Fun data tm :<: ty = tm :<: ty deriving (Show, Eq) infix 4 :<: -- TODO typechecking check :: Data :<: Desc -> Bool check (DataRecord r :<: DescRecord rd) = undefined check (DataVariant v :<: DescVariant vd) = undefined check (DataFun f :<: DescFun fd) = undefined check (_ :<: Param _) = undefined check _ = False -- TODO eliminators are significantly more work
joelburget/daily-typecheckers
src/Day4.hs
bsd-3-clause
1,596
0
11
366
403
237
166
-1
-1
module Language.TheExperiment.Parser.Lexer where import Data.Char import Text.Parsec import Text.Parsec.Expr import qualified Text.Parsec.Token as T import Control.Monad import qualified Control.Monad.Trans.State as S import Language.TheExperiment.AST.Expression type ParserOperator = Operator String Operators (S.State SourcePos) (Expr ()) newtype Operators = Operators [(ParserOperator, Rational)] type EParser a = ParsecT String Operators (S.State SourcePos) a opChars :: Monad m => ParsecT String u m Char opChars = oneOf ":!#$%&*+./<=>?@\\^|-~" upperIdent :: EParser String upperIdent = T.identifier $ T.makeTokenParser $ eLanguageDef { T.identStart = oneOf ['A'..'Z'] } lowerIdent :: EParser String lowerIdent = T.identifier $ T.makeTokenParser $ eLanguageDef { T.identStart = oneOf ['a'..'z'] } liftMp :: (SourcePos -> () -> a -> b) -> EParser a -> EParser b liftMp f = liftM3 f getPosition (return ()) liftM2p :: (SourcePos -> () -> a -> b -> c) -> EParser a -> EParser b -> EParser c liftM2p f = liftM4 f getPosition (return ()) liftM3p :: (SourcePos -> () -> a -> b -> c -> d) -> EParser a -> EParser b -> EParser c -> EParser d liftM3p f = liftM5 f getPosition (return ()) liftM6 :: (Monad m) => (a1 -> a2 -> a3 -> a4 -> a5 -> a6 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m a6 -> m r liftM6 f m1 m2 m3 m4 m5 m6 = do { x1 <- m1; x2 <- m2; x3 <- m3; x4 <- m4; x5 <- m5; x6 <- m6; return (f x1 x2 x3 x4 x5 x6) } liftM4p :: (SourcePos -> () -> a -> b -> c -> d -> e) -> EParser a -> EParser b -> EParser c -> EParser d -> EParser e liftM4p f = liftM6 f getPosition (return ()) eLanguageDef :: Monad m => T.GenLanguageDef String u m eLanguageDef = T.LanguageDef { T.commentStart = "/*" , T.commentEnd = "*/" , T.commentLine = "//" , T.nestedComments = True , T.identStart = letter <|> char '_' , T.identLetter = alphaNum <|> char '_' , T.opStart = opChars , T.opLetter = opChars , T.reservedOpNames = [] , T.reservedNames = ["block", "def", "if", "else", "elif", "type", "var", "while", "foreign", "return"] , T.caseSensitive = True } lexer :: Monad m => T.GenTokenParser String u m lexer = T.makeTokenParser eLanguageDef parens :: EParser a -> EParser a parens = T.parens lexer operator :: EParser String operator = T.operator lexer identifier :: EParser String identifier = T.identifier lexer lexeme :: EParser a -> EParser a lexeme = T.lexeme lexer comma :: EParser String comma = T.comma lexer whiteSpace :: EParser () whiteSpace = T.whiteSpace lexer commaSep1 :: EParser a -> EParser [a] commaSep1 = T.commaSep1 lexer commaSep :: EParser a -> EParser [a] commaSep = T.commaSep lexer symbol :: String -> EParser String symbol = T.symbol lexer reserved :: String -> EParser () reserved = T.reserved lexer reservedOp :: String -> EParser () reservedOp = T.reservedOp lexer stringLiteral :: EParser String stringLiteral = T.stringLiteral lexer charLiteral :: EParser Char charLiteral = T.charLiteral lexer rational :: EParser Rational rational = liftM (either toRational toRational) (T.naturalOrFloat lexer) number :: Integer -> EParser Char -> EParser Integer number base baseDigit = do{ digits <- many1 baseDigit ; let n = foldl (\x d -> base*x + toInteger (digitToInt d)) 0 digits ; seq n (return n) } float :: EParser Double float = T.float lexer decimal :: EParser Integer decimal = T.decimal lexer octal :: EParser Integer octal = T.octal lexer hexadecimal :: EParser Integer hexadecimal = T.hexadecimal lexer parseLex :: EParser a -> EParser a parseLex p = do whiteSpace x <- p eof return x
jvranish/TheExperiment
src/Language/TheExperiment/Parser/Lexer.hs
bsd-3-clause
3,700
0
16
792
1,455
748
707
91
1
import Test.DocTest main :: IO () main = doctest [ "-isrc" , "-ignore-package", "monads-tf" , "Database.Monarch.Utils" ]
notogawa/monarch
test/doctests.hs
bsd-3-clause
167
0
6
63
36
20
16
5
1
--------------------------------------------------------------- -- | -- Module : Data.Minecraft.Release18.Version -- Copyright : (c) 2016 Michael Carpenter -- License : BSD3 -- Maintainer : Michael Carpenter <[email protected]> -- Stability : experimental -- Portability : portable -- --------------------------------------------------------------- module Data.Minecraft.Release18.Version ( version , minecraftVersion , majorVersion ) where version :: Int version = 47 minecraftVersion :: String minecraftVersion = "1.8.8" majorVersion :: String majorVersion = "1.8"
oldmanmike/hs-minecraft-protocol
src/Data/Minecraft/Release18/Version.hs
bsd-3-clause
613
0
4
101
59
41
18
10
1
{-# LANGUAGE TypeFamilies#-} {-# OPTIONS -Wall #-} module FiniteStateMachine.Programs.FSM2 ( mach ) where import Basic.MemoryImpl (ListMem, fillMem) import FiniteStateMachine.Machine2 -------------------------------------------------------------------------- --------------------------specilized model operations & models -------------------------------------------------------------------------- data CState = Lock | Open deriving (Show, Eq) data InpAlp = Coin | Push deriving Show trans :: InpAlp -> CState -> CState trans Coin Lock = Open trans Push Lock = Lock trans Coin Open = Open trans Push Open = Lock initialState :: CState initialState = Open finalState :: ListMem CState finalState = fillMem [Lock] input :: ListMem InpAlp input = fillMem [Coin, Coin, Coin, Push] mach :: FSM1 CState InpAlp ListMem mach = FSM initialState finalState (compile trans) input
davidzhulijun/TAM
FiniteStateMachine/Programs/FSM2.hs
bsd-3-clause
883
0
7
124
211
119
92
21
1
{-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE UndecidableInstances #-} {-| Module : Text.PrettyPrint.Final.Extensions.Environment Description : Lexical scope tracking for final pretty printers Copyright : (c) David Darais, David Christiansen, and Weixi Ma 2016-2017 License : MIT Maintainer : [email protected] Stability : experimental Portability : Portable 'EnvT' extends a pretty printer to track a lexical environment. -} module Text.PrettyPrint.Final.Extensions.Environment ( MonadPrettyEnv(..) , MonadReaderEnv(..) -- * The transformer , EnvT(..) , runEnvT , mapEnvT ) where import Control.Applicative import Control.Monad.Reader import Control.Monad.State import Control.Monad.Writer import Text.PrettyPrint.Final as Final import Text.PrettyPrint.Final.Extensions.Precedence -- | A reader of environments class MonadReaderEnv env m | m -> env where -- | See 'ask' askEnv :: m env -- | See 'local' localEnv :: (env -> env) -> m a -> m a -- | Pretty monads that can read environments. Use this to implement -- lexical scope in your pretty printer, because the dynamic extent of -- pretty monad computations typically corresponds to the scope of a -- binder. class ( MonadPretty w ann fmt m , MonadReaderEnv env m ) => MonadPrettyEnv env w ann fmt m | m -> w, m -> ann, m -> fmt, m -> env where -- | A transformer that adds a reader effect, distinguished by the newtype tag. newtype EnvT env m a = EnvT { unEnvT :: ReaderT env m a } deriving ( Functor, Monad, Applicative, Alternative, MonadTrans , MonadState s, MonadWriter o ) -- | Run a pretty printer in an initial environment runEnvT :: env -> EnvT env m a -> m a runEnvT e xM = runReaderT (unEnvT xM) e -- | Transform the result of a pretty printer mapEnvT :: (m a -> n b) -> EnvT env m a -> EnvT env n b mapEnvT f = EnvT . mapReaderT f . unEnvT instance MonadReader r m => MonadReader r (EnvT env m) where ask = EnvT $ lift ask local f = mapEnvT (local f) instance (Monad m, Measure w fmt m) => Measure w fmt (EnvT env m) where measure = lift . measure instance MonadPretty w ann fmt m => MonadPretty w ann fmt (EnvT env m) where instance Monad m => MonadReaderEnv env (EnvT env m) where askEnv = EnvT ask localEnv f = EnvT . local f . unEnvT instance (Monad m, MonadReaderPrec ann m) => MonadReaderPrec ann (EnvT env m) where askPrecEnv = lift askPrecEnv localPrecEnv f (EnvT (ReaderT x)) = EnvT (ReaderT (\env -> localPrecEnv f (x env)))
davdar/pretty-monadic-printer
Text/PrettyPrint/Final/Extensions/Environment.hs
mit
2,836
0
13
547
657
362
295
-1
-1
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} module Tests.Readers.RST (tests) where import Text.Pandoc.Definition import Test.Framework import Tests.Helpers import Tests.Arbitrary() import Text.Pandoc.Builder import Text.Pandoc import Data.Monoid (mempty) rst :: String -> Pandoc rst = readRST def{ readerStandalone = True } infix 4 =: (=:) :: ToString c => String -> (String, c) -> Test (=:) = test rst tests :: [Test] tests = [ "line block with blank line" =: "| a\n|\n| b" =?> para (str "a") <> para (str "\160b") , "field list" =: unlines [ "para" , "" , ":Hostname: media08" , ":IP address: 10.0.0.19" , ":Size: 3ru" , ":Version: 1" , ":Indentation: Since the field marker may be quite long, the second" , " and subsequent lines of the field body do not have to line up" , " with the first line, but they must be indented relative to the" , " field name marker, and they must line up with each other." , ":Parameter i: integer" , ":Final: item" , " on two lines" ] =?> ( doc $ para "para" <> definitionList [ (str "Hostname", [para "media08"]) , (str "IP address", [para "10.0.0.19"]) , (str "Size", [para "3ru"]) , (str "Version", [para "1"]) , (str "Indentation", [para "Since the field marker may be quite long, the second and subsequent lines of the field body do not have to line up with the first line, but they must be indented relative to the field name marker, and they must line up with each other."]) , (str "Parameter i", [para "integer"]) , (str "Final", [para "item on two lines"]) ]) , "initial field list" =: unlines [ "=====" , "Title" , "=====" , "--------" , "Subtitle" , "--------" , "" , ":Version: 1" ] =?> ( setMeta "version" (para "1") $ setMeta "title" ("Title" :: Inlines) $ setMeta "subtitle" ("Subtitle" :: Inlines) $ doc mempty ) , "URLs with following punctuation" =: ("http://google.com, http://yahoo.com; http://foo.bar.baz.\n" ++ "http://foo.bar/baz_(bam) (http://foo.bar)") =?> para (link "http://google.com" "" "http://google.com" <> ", " <> link "http://yahoo.com" "" "http://yahoo.com" <> "; " <> link "http://foo.bar.baz" "" "http://foo.bar.baz" <> ". " <> link "http://foo.bar/baz_(bam)" "" "http://foo.bar/baz_(bam)" <> " (" <> link "http://foo.bar" "" "http://foo.bar" <> ")") ]
bgamari/pandoc
tests/Tests/Readers/RST.hs
gpl-2.0
3,027
0
18
1,151
552
306
246
63
1
-- | -- Copyright : (c) 2019 Robert Künnemann -- License : GPL v3 (see LICENSE) -- -- Maintainer : Robert Künnemann <[email protected]> -- Portability : GHC only -- -- Compute annotations for locks. module Sapic.Locks ( annotateLocks ) where import Control.Exception import Control.Monad.Catch import Control.Monad.Fresh -- import qualified Data.Traversable as T import Sapic.Annotation import Sapic.Exceptions import Theory import Theory.Sapic -- This exceptions is thrown im annotateEachClosestUnlock finds -- a parallel or replications below the locks. The calling function -- annotate_locks catches it and outputs the proper exception with the -- complete process. newtype LocalException = LocalException WFLockTag deriving (Show) instance Exception LocalException -- | Annotate the closes occurence of unlock that has term t with the -- variable v output the exception above if we encounter rep or parallel annotateEachClosestUnlock :: MonadThrow m => Theory.Sapic.SapicTerm -> AnLVar -> AnProcess ProcessAnnotation -> m( AnProcess ProcessAnnotation) annotateEachClosestUnlock _ _ (ProcessNull a') = return $ ProcessNull a' annotateEachClosestUnlock t v (ProcessAction (Unlock t') a' p) = if t == t' then return $ ProcessAction (Unlock t') (a' `mappend` annUnlock v) p else do p' <- annotateEachClosestUnlock t v p return $ProcessAction (Unlock t') a' p' annotateEachClosestUnlock _ _ (ProcessAction Rep _ _) = throwM $ LocalException WFRep annotateEachClosestUnlock _ _ (ProcessComb Parallel _ _ _) = throwM $ LocalException WFPar annotateEachClosestUnlock t v (ProcessAction ac a' p) = do p' <- annotateEachClosestUnlock t v p return $ ProcessAction ac a' p' annotateEachClosestUnlock t v (ProcessComb c a' pl pr ) = do pl' <- annotateEachClosestUnlock t v pl pr' <- annotateEachClosestUnlock t v pr return $ ProcessComb c a' pl' pr' -- | Annotate locks in a process: chose fresh lock variable and -- annotateEachClosestUnlock. annotateLocks :: ( MonadThrow m, MonadFresh m -- , Monoid (m (AnProcess ProcessAnnotation)) -- ,Foldable (AnProcess ProcessAnnotation) ) => AnProcess ProcessAnnotation -> m (AnProcess ProcessAnnotation) annotateLocks (ProcessAction (Lock t) a p) = do v <- freshLVar "lock" LSortMsg p' <- annotateEachClosestUnlock t (AnLVar v) p p'' <- annotateLocks p' return (ProcessAction (Lock t) (a `mappend` annLock (AnLVar v)) p'') -- return (ProcessAction (Lock t) (annLock (AnLVar v)) p'') annotateLocks (ProcessAction ac an p) = do p' <- annotateLocks p return (ProcessAction ac an p') annotateLocks (ProcessNull an ) = return (ProcessNull an) annotateLocks (ProcessComb comb an pl pr ) = do pl' <- annotateLocks pl pr' <- annotateLocks pr return (ProcessComb comb an pl' pr')
kmilner/tamarin-prover
lib/sapic/src/Sapic/Locks.hs
gpl-3.0
3,389
0
14
1,078
700
351
349
47
2
{-# LANGUAGE StrictData #-} {-# LANGUAGE Trustworthy #-} module Network.Tox.DHT.NodesRequestSpec where import Test.Hspec import Data.Proxy (Proxy (..)) import qualified Network.Tox.Crypto.KeyPair as KeyPair import Network.Tox.DHT.NodesRequest (NodesRequest (..)) import Network.Tox.EncodingSpec spec :: Spec spec = do rpcSpec (Proxy :: Proxy NodesRequest) binarySpec (Proxy :: Proxy NodesRequest) readShowSpec (Proxy :: Proxy NodesRequest) it "has a public key" $ do kp <- KeyPair.newKeyPair let req = NodesRequest (KeyPair.publicKey kp) requestedKey req `shouldBe` KeyPair.publicKey kp
iphydf/hs-toxcore
test/Network/Tox/DHT/NodesRequestSpec.hs
gpl-3.0
673
0
16
156
172
95
77
17
1
module Play.Events ( handlePlayEvent ) where import Graphics.Gloss.Interface.Pure.Game import Level.Level import Play.PlayState handlePlayEvent :: Event -> PlayState -> PlayState handlePlayEvent event pl@(PlayState { drawing = dwg , drawnWalls = ws , future = ft , paused = pd }) = case event of EventKey (MouseButton LeftButton) Down _ mPos -> case dwg of NotDrawing -> pl { drawing = Drawing $ Wall mPos mPos } Drawing _ -> pl EventKey (MouseButton LeftButton) Up _ _ -> case dwg of NotDrawing -> pl Drawing w@(Wall start end) -> pl { drawnWalls = if (end - start) /= 0 then w:ws else ws , drawing = NotDrawing } EventMotion mPos -> case dwg of NotDrawing -> pl Drawing (Wall start _) -> pl { drawing = Drawing $ Wall start mPos } EventKey (Char 'u') Up _ _ -> -- undraw the latest line pl { drawnWalls = tail ws } EventKey (Char 'f') Up _ _ -> -- see/unsee the future pl { future = not ft } EventKey (Char 'p') Up _ _ -> -- pause pl { paused = not pd } EventKey (Char 'r') Up _ _ -> -- restart pl { balls = [initBall (level pl)], drawnWalls = [] } _ -> pl
beni55/pinhole
Pinhole/Play/Events.hs
gpl-3.0
1,478
0
16
625
442
236
206
36
12
module Config ( serverHost, serverPort, autoJoin, botNick, markovOrder, opList ) where import Prelude hiding () --import Main (imitate, imitateall) import qualified Data.List as List (concat, map, concatMap) import qualified Data.Map as Map (Map(..), fromList) type Map = Map.Map imitate = undefined imitateall = undefined serverHost :: String serverHost = "irc.sublumin.al" serverPort :: Int serverPort = 6667 autoJoin :: [String] autoJoin = ["#spam"] botNick :: String botNick = "mako" markovOrder :: Int markovOrder = 2 opList :: Map String f opList = Map.fromList . List.concatMap ( \(a,b) -> -- Didn't happen >_< List.map (flip (,) b . (:a)) ".!@" ) $ [("imitate", imitate), ("im", imitate), ("speak", imitateall), ("imitateall", imitateall)]
tonyolag/mako
Config.hs
mpl-2.0
1,027
0
14
387
252
157
95
30
1
module Examples.LexProd ( lpbwspExample ) where import Algebra.Constructs.Lexico import Examples.ShortestPath import Examples.WidestPath lpbwspExample 0 = lexico (wpExamples 1) (spExamples 4) lpbwspExample 1 = lexico (wpExamples 2) (spExamples 5) lpbwspExample 2 = lexico (wpExamples 3) (spExamples 8)
sdynerow/Semirings-Library
haskell/Examples/LexProd.hs
apache-2.0
305
0
7
39
102
53
49
8
1
module Resize where import CLaSH.Prelude topEntity :: Signed 4 -> Signed 3 topEntity = resize testInput :: Signal (Signed 4) testInput = stimuliGenerator $(v ([minBound .. maxBound]::[Signed 4])) expectedOutput :: Signal (Signed 3) -> Signal Bool expectedOutput = outputVerifier $(v ([-4,-3,-2,-1,-4,-3,-2,-1,0,1,2,3,0,1,2,3]::[Signed 3]))
christiaanb/clash-compiler
tests/shouldwork/Numbers/Resize.hs
bsd-2-clause
344
0
11
46
188
105
83
-1
-1
-- This program compares the sizes of corresponding files in two tress -- $ ./compareSizes --hi ~/ghc/darcs/ghc ~/ghc/6.12-branch/ghc -- Size | Change | Filename -- 25644 | -0.99% | compiler/stage1/build/Demand.hi -- 21103 | -0.98% | compiler/stage2/build/Demand.hi -- 180044 | -0.98% | libraries/base/dist-install/build/GHC/Classes.hi -- 6415 | -0.58% | .../Data/Array/Parallel/Prelude/Base/Tuple.hi -- 6507 | -0.57% | .../Data/Array/Parallel/Prelude/Base/Tuple.hi -- [...] -- 3264 | 3.16% | .../Parallel/Unlifted/Sequential/Flat/Enum.hi -- 51389 | 3.30% | .../build/Language/Haskell/Extension.hi -- 1415 | 72.18% | libraries/base/dist-install/build/Data/Tuple.hi -- 28752162 | -0.00% | TOTAL -- Flags: -- --o to compare object files. -- --hi to compare interface files [DEFAULT] -- There's a hack to avoid descending into '*_split' directories module Main (main) where import Control.Exception import Control.Monad import Data.List import Data.Maybe import Numeric import Prelude hiding (catch) import System.Directory import System.Environment import System.FilePath import System.IO main :: IO () main = do hSetBuffering stdout LineBuffering args <- getArgs case args of ["--hi", dir1, dir2] -> doit isHiFile dir1 dir2 ["--o", dir1, dir2] -> doit isOFile dir1 dir2 [dir1, dir2] -> doit isHiFile dir1 dir2 _ -> error "Bad arguments" isHiFile :: FilePath -> Bool isHiFile = (".hi" `isSuffixOf`) isOFile :: FilePath -> Bool isOFile = (".o" `isSuffixOf`) doit :: (FilePath -> Bool) -> FilePath -> FilePath -> IO () doit isFileInteresting dir1 dir2 = do when verbose $ putStrLn "Reading tree 1" tree1 <- getTree isFileInteresting dir1 "." "." when verbose $ putStrLn "Reading tree 2" tree2 <- getTree isFileInteresting dir2 "." "." when verbose $ putStrLn "Comparing trees" let ds = compareTree tree1 tree2 ds' = sortBy comparingPercentage ds total = mkTotalDifference ds' mapM_ putStrLn $ showDifferences (ds' ++ [total]) verbose :: Bool verbose = False ---------------------------------------------------------------------- -- Reading the trees data Tree = Directory { nodeName :: FilePath, _subTrees :: [Tree] } | File { nodeName :: FilePath, _filePath :: FilePath, _size :: Size } deriving Show type Size = Integer type Percentage = Double getTree :: (FilePath -> Bool) -> FilePath -> FilePath -> FilePath -> IO Tree getTree isFileInteresting root dir subdir = do entries <- getDirectoryContents (root </> dir </> subdir) mSubtrees <- mapM doEntry $ sort $ filter interesting entries return $ Directory subdir $ catMaybes mSubtrees where interesting "." = False interesting ".." = False -- We don't want to descend into object-splitting directories, -- and compare the hundreds of split object files. Instead we -- just compare the combined object file outside of the _split -- directory. interesting d = not ("_split" `isSuffixOf` d) dir' = dir <//> subdir doEntry :: FilePath -> IO (Maybe Tree) doEntry e = liftM Just (getTree isFileInteresting root dir' e) `catchIO` \_ -> -- XXX We ought to check this is a -- "not a directory" exception really if isFileInteresting e then do let fn = dir' <//> e h <- openFile (root </> fn) ReadMode size <- hFileSize h hClose h return $ Just $ File e fn size else return Nothing catchIO :: IO a -> (IOError -> IO a) -> IO a catchIO = catch ---------------------------------------------------------------------- -- Comparing the trees data Difference = Difference FilePath Size Size Percentage deriving Show compareTree :: Tree -> Tree -> [Difference] compareTree (Directory _ ts1) (Directory _ ts2) = compareTrees ts1 ts2 compareTree (File _ fn s1) (File _ _ s2) = [Difference fn s1 s2 (mkPercentage s1 s2)] compareTree _ _ = [] mkPercentage :: Size -> Size -> Percentage mkPercentage s1 s2 = fromIntegral (s2 - s1) / fromIntegral s1 compareTrees :: [Tree] -> [Tree] -> [Difference] compareTrees t1s@(t1 : t1s') t2s@(t2 : t2s') = case nodeName t1 `compare` nodeName t2 of LT -> compareTrees t1s' t2s EQ -> compareTree t1 t2 ++ compareTrees t1s' t2s' GT -> compareTrees t1s t2s' compareTrees _ _ = [] showDifferences :: [Difference] -> [String] showDifferences ds = showTable [lpad, lpad, rpad] (["Size", "Change", "Filename"] : map showDifference ds) showDifference :: Difference -> [String] showDifference (Difference fp s1 _ percentage) = [show s1, showFFloat (Just 2) percentage "%", shorten fp] shorten :: FilePath -> FilePath shorten fp = let xs = map joinPath $ tails $ splitDirectories fp in case xs of x : _ | length x <= allowed -> x _ -> case dropWhile ((> allowed - 4) . length) xs of x : _ -> "..." </> x [] -> take (allowed - 3) (takeFileName fp) ++ "..." where allowed = 50 comparingPercentage :: Difference -> Difference -> Ordering comparingPercentage (Difference _ _ _ p1) (Difference _ _ _ p2) = compare p1 p2 mkTotalDifference :: [Difference] -> Difference mkTotalDifference ds = let s1 = sum [ x | Difference _ x _ _ <- ds ] s2 = sum [ x | Difference _ _ x _ <- ds ] percentage = mkPercentage s1 s2 in Difference "TOTAL" s1 s2 percentage ---------------------------------------------------------------------- -- Utils (<//>) :: FilePath -> FilePath -> FilePath "." <//> fp = fp dir <//> fn = dir </> fn showTable :: [Int -> String -> String] -> [[String]] -> [String] showTable padders xss = let lengths = map (maximum . map length) $ transpose xss in map (concat . intersperse " | " . zipWith3 id padders lengths) xss lpad :: Int -> String -> String lpad n s = replicate (n - length s) ' ' ++ s rpad :: Int -> String -> String rpad n s = s ++ replicate (n - length s) ' '
mcmaniac/ghc
utils/compare_sizes/Main.hs
bsd-3-clause
6,600
0
16
1,959
1,734
901
833
117
4
{-# LANGUAGE DataKinds,EmptyDataDecls #-} module HLearn.Metrics.Mahalanobis.Mega where import Control.DeepSeq import Control.Monad import Control.Monad.ST import Data.STRef import Data.List import qualified Data.Semigroup as SG import qualified Data.Foldable as F import qualified Data.Vector as V import qualified Data.Vector.Mutable as VM import qualified Data.Vector.Storable as VS import qualified Data.Vector.Storable.Mutable as VSM import qualified Data.Vector.Generic as VG import qualified Data.Vector.Generic.Mutable as VGM import qualified Data.Vector.Algorithms.Intro as Intro import Debug.Trace import Unsafe.Coerce import Foreign.Storable import Numeric.LinearAlgebra hiding ((<>)) import qualified Numeric.LinearAlgebra as LA import HLearn.Algebra import HLearn.Metrics.Mahalanobis import HLearn.Metrics.Mahalanobis.Normal import HLearn.Metrics.Mahalanobis.LegoPaper import HLearn.Metrics.Mahalanobis.ITML hiding (_x) import HLearn.Models.Distributions.Multivariate.MultiNormalFast import qualified HLearn.Optimization.Conic as Recipe import qualified HLearn.Optimization.Common as Recipe import qualified HLearn.Optimization.GradientDescent as Recipe import qualified HLearn.Optimization.Amoeba as Recipe import qualified HLearn.Optimization.NewtonRaphson as Recipe ------------------------------------------------------------------------------- -- data types newtype Mega (eta::Frac) dp = Mega { _x :: Matrix (Scalar dp) } deriving instance (Element (Scalar dp), Show (Scalar dp)) => Show (Mega eta dp) instance (Storable (Scalar dp), NFData (Scalar dp), NFData dp) => NFData (Mega eta dp) where rnf mega = rnf $ _x mega instance MahalanobisMetric (Mega eta dp) where getMatrix mega = _x mega ------------------------------------------------------------------------------- -- algebra type instance Scalar (Mega eta dp) = Scalar dp type instance Scalar (Matrix r) = r ------------------------------------------------------------------------------- -- training mkMega :: forall container eta. ( Scalar (container Double) ~ Double , VG.Vector container Double , KnownFrac eta ) => Double -> Double -> [(Double,container Double)] -> Mega eta (container Double) mkMega etaraw eta2 !xs = Mega $ _x $ (mkMega' etaraw eta2 xs'::Mega eta (Vector Double)) where xs' = map (\(y,x) -> (y, fromList $ VG.toList x)) xs -- mkMega' :: forall eta. KnownFrac eta => Double -> [(Double,Vector Double)] -> Mega eta (Vector Double) -- -- mkMega' etaraw !xs = Mega $ findMinAmoeba f init -- mkMega' etaraw !xs = Mega $ findzero a b init -- where -- -- (ITML init) = train_ITML 10 xs -- -- (LegoPaper init) = train_LegoPaper eta xs -- init = identity -- -- identity = ident (LA.dim $ snd $ head xs) -- xxt x = asColumn x LA.<> asRow x -- a = foldl1' LA.add $ map (\(_,x) -> eta `scale` kronecker (xxt x) (xxt x)) xs -- b = foldl' LA.add (vec identity) $ map (\(y,x) -> vec $ (eta*y) `scale` xxt x) xs -- -- eta = etaraw mkMega' :: forall eta. KnownFrac eta => Double -> Double -> [(Double,Vector Double)] -> Mega eta (Vector Double) mkMega' etaraw eta2 !xs = {-trace ("megamatrix="++show res) $ -} deepseq lego $ deepseq itml $ deepseq res $ trace ("rank q_zz="++show (LA.rank (q_zz :: Matrix Double))++"; rank a="++show (LA.rank a)) $ trace ("lego score="++show (f lego)) $ trace ("itml score="++show (f itml)) $ trace ("mega score="++show (f res)) $ trace ("trace = "++show (tr $ res)) $ trace ("logdet = "++show (log $ det res)) $ trace ("zAzzAz = "++show (0.5*eta*(sumElements $ (trans $ vec res) LA.<> q_zz LA.<> (vec res)))) $ trace ("yzAz = "++show (0.5*eta*(sumElements $ scale (-2) $ q_yz * res))) $ trace ("yy = "++show (0.5*eta*q_yy)) $ trace ("sum = "++show (0.5*eta*((sumElements $ (trans $ vec res) LA.<> q_zz LA.<> (vec res)) +(sumElements $ scale (-2) $ q_yz * res) +q_yy))) $ -- trace ("eigenvalues q_zz="++show (eigenvalues q_zz)) $ -- deepseq res $ deepseq res2 $ deepseq res3 $ -- trace ("res="++show res++"\n\nres2="++show res2++"\n\nres3="++show res3) $ Mega $ res where magicJumble2 0 x = x magicJumble2 i x = magicJumble2 (i-1) -- $ trace "---------------\nunderscore" $ Recipe.newtonRaphson_constrained f_ f'_ f''_ -- $ trace "---------------\nplain" $ Recipe.newtonRaphson_constrained f f'c f'' -- $ Recipe.runOptimization (Recipe.conjugateGradientDescent f f') -- $ Recipe.newtonRaphson_constrained f f'c f'' $ x magicJumble 0 x = x magicJumble i x = magicJumble (i-1) x' where x_proj = Recipe.conicProjection f -- $ Recipe.newtonRaphson_constrained f f'c f'' $ x fx = f x fx_proj = f x_proj x' = Recipe.randomConicPersuit f $ if fx_proj < fx then x_proj else x res = -- Recipe.newtonRaphson_constrained f f'c f'' -- $ Recipe.runOptimization (Recipe.conjugateGradientDescent f f') -- $ x0 x0 res1 = findzero a b x0 -- res2 = findzero a b $ Recipe.runOptimization (Recipe.conjugateGradientDescent f f' x0) res3 = findzero a b itml -- x0 = identity x0 = mahalanobis mahalanobis = getMatrix $ (train $ map snd xs :: MahalanobisParams (Vector Double)) (ITML itml) = train_ITML 10 xs -- :: ITML (Double,Vector Double) (LegoPaper lego _ _) = train_LegoPaper 1 0.01 xs -- :: LegoPaper (Double,Vector Double) identity = ident (LA.dim $ snd $ head xs) xxt x = asColumn x LA.<> asRow x -- a = foldl1' LA.add $ map (\(_,x) -> eta `scale` kronecker (xxt x) (xxt x)) xs a = scale eta q_zz b = foldl' LA.add (vec identity) $ map (\(y,x) -> vec $ (eta*y) `scale` xxt x) xs -- q_zz = foldl1' LA.add $ map (\(y,x) -> (asColumn$flatten$xxt x) LA.<> (asRow$flatten$xxt x)) xs -- q_yz = foldl1' LA.add $ map (\(y,x) -> scale (-2*y) (xxt x)) xs q_z = sum $ map (\(y,x) -> xxt x) xs q_zz = q_zz_mock q_zz_lowrank = (head $ head $ toBlocks [size] [rank] u) LA.<> (diagRect 0 (VG.slice 0 rank sigma) rank rank) LA.<> (head $ head $ toBlocks [rank] [size] $ trans v) :: Matrix Double -- rank=rows x0 rank=floor $ (fromIntegral size::Double)/2 size=rows q_zz_full (u,sigma,v) = svd q_zz_full q_zz_full = sum $ map (\(y,x) -> kronecker (xxt x) (xxt x)) xs q_zz_mock = kronecker zz zz where zz = sum $ (map (\(y,x) -> xxt x)) xs q_yz = sum $ map (\(y,x) -> scale y (xxt x)) xs q_yy = sum $ map (\(y,x) -> y^2) xs q_zzk= sum $ map (\(y,x) -> kronecker (xxt x) (xxt x)) xs eta = etaraw -- eta = etaraw / fromIntegral (length xs) tr = LA.sumElements . LA.takeDiag f :: Matrix Double -> Double f x = tr prod + if det < 0 then infinity else (-1) * log det + 0.5*eta* ( (sumElements $ (trans $ vec x) LA.<> q_zz LA.<> (vec x)) + (sumElements $ scale (-2) $ q_yz * x) + q_yy ) + eta2 * (pnorm Frobenius x) where det = LA.det prod prod = x LA.<> LA.inv x0 f_ x = tr (x LA.<> LA.inv x0) + 0.5*eta* ( (sumElements $ (trans $ vec x) LA.<> q_zz LA.<> (vec x)) + (sumElements $ scale (-2) $ q_yz * x) + q_yy ) f'_ x = (a LA.<> vec x) `LA.sub` b f''_ x = a f' x = f'a x + scale (eta2*2) x f'a x = reshape (rows x) $ flatten $ (vec $ (-1) `scale` inv x) `LA.add` (a LA.<> vec x) `LA.sub` b f'b x = inv x0 - inv x + scale eta ((reshape (rows x) $ flatten $ q_zzk LA.<> vec x) - q_yz) f'c x = (vec $ (-1) `scale` inv x) `LA.add` (a LA.<> vec x) `LA.sub` b f'' x = kronecker xinv xinv `LA.add` a + scale eta2 (ident $ (rows xinv)^2) -- f'' x = reshape (rows x) $ flatten $ kronecker xinv xinv `LA.add` a where xinv = inv x -- stepLineMin f f' lower mid upper -- g :: Matrix Double -> Matrix Double g :: LA.Vector Double -> Double g x = VG.sum $ VG.map abs $ x `LA.add` (LA.fromList [2,3]) y0 = LA.fromList [1,2::Double] m1 = 2 >< 2 $ [1,2,2,4::Double] m2 = 2 >< 2 $ [3,1,1,4::Double] findzero :: Matrix Double -> Matrix Double -> Matrix Double -> Matrix Double findzero !a !b !x0 = newtonRaphson x0 x0' 1000 --0000 where x0' = x0 `LA.sub` (((rows x0)><(cols x0)) $ repeat 1) -- gradientDescent !x 0 = x -- gradientDescent x i = gradientDescent x' (i-1) -- where -- x' = -- xinv = inv x -- df = kronecker xinv xinv `LA.add` a newtonRaphson !x !lastx !itr = --trace ("x="++show x++"\nx'="++show x'++"\n\n") $ if itr==0 then trace ("WARNING: findzero probably failed to converge; diff="++show diff++"; ratio="++show ratio) x else if diff <= 1e-8 || ratio <= 1e-8 then x else newtonRaphson x' x (itr-1) where diff = (maxElement $ cmap abs $ x `LA.sub` lastx) ratio = (maxElement $ cmap abs $ x `LA.sub` lastx) / maxElement (cmap abs x) xinv = inv x f = (vec $ (-1) `scale` xinv) `LA.add` (a LA.<> vec x) `LA.sub` b df = kronecker xinv xinv `LA.add` a -- x' = if itr > 20 -- then x `LA.sub` reshape (rows x) (flatten $ scale (0.1) df) -- else x `LA.sub` reshape (rows x) (flatten $ inv df LA.<> f) epsilon = 1e-13 -- 0.000000000000001 -- *(maxElement f/ fromIntegral (rows x*rows x)) -- x' = x `LA.sub` reshape (rows x) (flatten $ scale epsilon f) x' = x `LA.sub` reshape (rows x) (flatten $ inv df LA.<> f) vec :: Matrix Double -> Matrix Double vec = asColumn . flatten ------------------------------------------------------------------------------- -- metric instance ( VG.Vector dp r , Scalar (dp r) ~ r , LA.Product r ) => MkMahalanobis (Mega eta (dp r)) where type MetricDatapoint (Mega eta (dp r)) = dp r mkMahalanobis mega dp = Mahalanobis { rawdp = dp , moddp = VG.fromList $ toList $ flatten $ (_x mega) LA.<> asColumn v } where v = fromList $ VG.toList dp ------------------------------------------------------------------------------- -- test -- xs = -- [ [1,2] -- , [2,3] -- , [3,4] -- ] -- :: [[Double]] xs = [ (1, fromList [2,3]) , (1, fromList [3,3]) , (1, fromList [3,-2]) ] :: [(Double,Vector Double)] mb = (2><2)[-6.5,-10,-10,-14] :: Matrix Double mc = (2><2)[282,388,388,537] :: Matrix Double
iamkingmaker/HLearn
src/HLearn/Metrics/Mahalanobis/Mega.hs
bsd-3-clause
11,407
0
26
3,501
3,373
1,842
1,531
-1
-1
module Lang.LamIf.Analyses where import FP import MAAM import Lang.LamIf.Val import Lang.LamIf.Semantics import Lang.LamIf.Monads import Lang.LamIf.CPS -- import Lang.LamIf.StateSpace -- These instances are defined in MAAM.Time timeChoices :: [(String, ExTime)] timeChoices = [ ("*" , ExTime (W :: UniTime (Cτ Ψ)) ) , ("1" , ExTime (W :: UniTime (Kτ 1 Ψ)) ) , ("0" , ExTime (W :: UniTime (Zτ Ψ)) ) ] -- These instances are defined in Lang.CPS.Val valChoices :: [(String, ExVal)] valChoices = [ ( "concrete" , ExVal (W :: UniVal (Power CVal)) ) , ( "abstract" , ExVal (W :: UniVal (Power AVal)) ) ] -- These instances are defined in MAAM.MonadStep and Lang.CPS.Monads monadChoices :: [(String, ExMonad)] monadChoices = [ ( "ps" , ExMonad (W :: UniMonad PSΣ PSΣ𝒫 PS)) , ( "fs" , ExMonad (W :: UniMonad FSΣ FSΣ𝒫 FS)) , ( "fi" , ExMonad (W :: UniMonad FIΣ FIΣ𝒫 FI)) ] -- These are defined in Lang.CPS.Semantics gcChoices :: [(String, AllGC)] gcChoices = [ ( "no" , AllGC nogc ) , ( "yes" , AllGC yesgc ) ] -- These are defined in Lang.CPS.Semantics closureChoices :: [(String, AllCreateClo)] closureChoices = [ ( "link" , AllCreateClo linkClo ) , ( "copy" , AllCreateClo copyClo ) ] timeFilterChoices :: [(String, TimeFilter)] timeFilterChoices = [ ("*" , not . is haltL . stampedFix ) , ("app" , is appFL . stampedFix ) ]
FranklinChen/maam
src/Lang/LamIf/Analyses.hs
bsd-3-clause
1,400
18
11
287
494
289
205
-1
-1
module PackageTests.Tests(tests) where import PackageTests.PackageTester import qualified PackageTests.BenchmarkStanza.Check import qualified PackageTests.TestStanza.Check import qualified PackageTests.DeterministicAr.Check import qualified PackageTests.TestSuiteTests.ExeV10.Check import Control.Monad import Data.Version import Test.Tasty (mkTimeout, localOption) import Test.Tasty.HUnit (testCase) tests :: SuiteConfig -> TestTreeM () tests config = do --------------------------------------------------------------------- -- * External tests -- Test that Cabal parses 'benchmark' sections correctly tc "BenchmarkStanza" PackageTests.BenchmarkStanza.Check.suite -- Test that Cabal parses 'test' sections correctly tc "TestStanza" PackageTests.TestStanza.Check.suite -- Test that Cabal determinstically generates object archives tc "DeterministicAr" PackageTests.DeterministicAr.Check.suite --------------------------------------------------------------------- -- * Test suite tests groupTests "TestSuiteTests" $ do -- Test exitcode-stdio-1.0 test suites (and HPC) groupTests "ExeV10" (PackageTests.TestSuiteTests.ExeV10.Check.tests config) -- Test detailed-0.9 test suites groupTests "LibV09" $ let tcs :: FilePath -> TestM a -> TestTreeM () tcs name m = testTree' $ testCase name (runTestM config "TestSuiteTests/LibV09" (Just name) m) in do -- Test if detailed-0.9 builds correctly tcs "Build" $ cabal_build ["--enable-tests"] -- Tests for #2489, stdio deadlock mapTestTrees (localOption (mkTimeout $ 10 ^ (8 :: Int))) . tcs "Deadlock" $ do cabal_build ["--enable-tests"] shouldFail $ cabal "test" [] --------------------------------------------------------------------- -- * Inline tests -- Test if exitcode-stdio-1.0 benchmark builds correctly tc "BenchmarkExeV10" $ cabal_build ["--enable-benchmarks"] -- Test --benchmark-option(s) flags on ./Setup bench tc "BenchmarkOptions" $ do cabal_build ["--enable-benchmarks"] cabal "bench" [ "--benchmark-options=1 2 3" ] cabal "bench" [ "--benchmark-option=1" , "--benchmark-option=2" , "--benchmark-option=3" ] -- Test --test-option(s) flags on ./Setup test tc "TestOptions" $ do cabal_build ["--enable-tests"] cabal "test" ["--test-options=1 2 3"] cabal "test" [ "--test-option=1" , "--test-option=2" , "--test-option=3" ] -- Test attempt to have executable depend on internal -- library, but cabal-version is too old. tc "BuildDeps/InternalLibrary0" $ do r <- shouldFail $ cabal' "configure" [] -- Should tell you how to enable the desired behavior let sb = "library which is defined within the same package." assertOutputContains sb r -- Test executable depends on internal library. tc "BuildDeps/InternalLibrary1" $ cabal_build [] -- Test that internal library is preferred to an installed on -- with the same name and version tc "BuildDeps/InternalLibrary2" $ internal_lib_test "internal" -- Test that internal library is preferred to an installed on -- with the same name and LATER version tc "BuildDeps/InternalLibrary3" $ internal_lib_test "internal" -- Test that an explicit dependency constraint which doesn't -- match the internal library causes us to use external library tc "BuildDeps/InternalLibrary4" $ internal_lib_test "installed" -- Test "old build-dep behavior", where we should get the -- same package dependencies on all targets if cabal-version -- is sufficiently old. tc "BuildDeps/SameDepsAllRound" $ cabal_build [] -- Test "new build-dep behavior", where each target gets -- separate dependencies. This tests that an executable -- dep does not leak into the library. tc "BuildDeps/TargetSpecificDeps1" $ do cabal "configure" [] r <- shouldFail $ cabal' "build" [] assertRegex "error should be in MyLibrary.hs" "^MyLibrary.hs:" r assertRegex "error should be \"Could not find module `Text\\.PrettyPrint\"" "(Could not find module|Failed to load interface for).*Text\\.PrettyPrint" r -- This is a control on TargetSpecificDeps1; it should -- succeed. tc "BuildDeps/TargetSpecificDeps2" $ cabal_build [] -- Test "new build-dep behavior", where each target gets -- separate dependencies. This tests that an library -- dep does not leak into the executable. tc "BuildDeps/TargetSpecificDeps3" $ do cabal "configure" [] r <- shouldFail $ cabal' "build" [] assertRegex "error should be in lemon.hs" "^lemon.hs:" r assertRegex "error should be \"Could not find module `Text\\.PrettyPrint\"" "(Could not find module|Failed to load interface for).*Text\\.PrettyPrint" r -- Test that Paths module is generated and available for executables. tc "PathsModule/Executable" $ cabal_build [] -- Test that Paths module is generated and available for libraries. tc "PathsModule/Library" $ cabal_build [] -- Check that preprocessors (hsc2hs) are run tc "PreProcess" $ cabal_build ["--enable-tests", "--enable-benchmarks"] -- Check that preprocessors that generate extra C sources are handled tc "PreProcessExtraSources" $ cabal_build ["--enable-tests", "--enable-benchmarks"] -- Test building a vanilla library/executable which uses Template Haskell tc "TemplateHaskell/vanilla" $ cabal_build [] -- Test building a profiled library/executable which uses Template Haskell -- (Cabal has to build the non-profiled version first) tc "TemplateHaskell/profiling" $ cabal_build ["--enable-library-profiling", "--enable-profiling"] -- Test building a dynamic library/executable which uses Template -- Haskell testWhen (hasSharedLibraries config) $ tc "TemplateHaskell/dynamic" $ cabal_build ["--enable-shared", "--enable-executable-dynamic"] -- Test building an executable whose main() function is defined in a C -- file tc "CMain" $ cabal_build [] -- Test build when the library is empty, for #1241 tc "EmptyLib" $ withPackage "empty" $ cabal_build [] -- Test that "./Setup haddock" works correctly tc "Haddock" $ do dist_dir <- distDir let haddocksDir = dist_dir </> "doc" </> "html" </> "Haddock" cabal "configure" [] cabal "haddock" [] let docFiles = map (haddocksDir </>) ["CPP.html", "Literate.html", "NoCPP.html", "Simple.html"] mapM_ (assertFindInFile "For hiding needles.") docFiles -- Test that Haddock with a newline in synopsis works correctly, #3004 tc "HaddockNewline" $ do cabal "configure" [] cabal "haddock" [] -- Test that Cabal properly orders GHC flags passed to GHC (when -- there are multiple ghc-options fields.) tc "OrderFlags" $ cabal_build [] -- Test that reexported modules build correctly -- TODO: should also test that they import OK! tc "ReexportedModules" $ do whenGhcVersion (>= Version [7,9] []) $ cabal_build [] -- Test that Cabal computes different IPIDs when the source changes. tc "UniqueIPID" . withPackageDb $ do withPackage "P1" $ cabal "configure" [] withPackage "P2" $ cabal "configure" [] withPackage "P1" $ cabal "build" [] withPackage "P1" $ cabal "build" [] -- rebuild should work r1 <- withPackage "P1" $ cabal' "register" ["--print-ipid", "--inplace"] withPackage "P2" $ cabal "build" [] r2 <- withPackage "P2" $ cabal' "register" ["--print-ipid", "--inplace"] let exIPID s = takeWhile (/= '\n') $ head . filter (isPrefixOf $ "UniqueIPID-0.1-") $ (tails s) when ((exIPID $ resultOutput r1) == (exIPID $ resultOutput r2)) $ assertFailure $ "cabal has not calculated different Installed " ++ "package ID when source is changed." tc "DuplicateModuleName" $ do cabal_build ["--enable-tests"] r1 <- shouldFail $ cabal' "test" ["foo"] assertOutputContains "test B" r1 assertOutputContains "test A" r1 r2 <- shouldFail $ cabal' "test" ["foo2"] assertOutputContains "test C" r2 assertOutputContains "test A" r2 tc "TestNameCollision" $ do withPackageDb $ do withPackage "parent" $ cabal_install [] withPackage "child" $ do cabal_build ["--enable-tests"] cabal "test" [] -- Test that '--allow-newer' works via the 'Setup.hs configure' interface. tc "AllowNewer" $ do shouldFail $ cabal "configure" [] cabal "configure" ["--allow-newer"] shouldFail $ cabal "configure" ["--allow-newer=baz,quux"] cabal "configure" ["--allow-newer=base", "--allow-newer=baz,quux"] cabal "configure" ["--allow-newer=bar", "--allow-newer=base,baz" ,"--allow-newer=quux"] shouldFail $ cabal "configure" ["--enable-tests"] cabal "configure" ["--enable-tests", "--allow-newer"] shouldFail $ cabal "configure" ["--enable-benchmarks"] cabal "configure" ["--enable-benchmarks", "--allow-newer"] shouldFail $ cabal "configure" ["--enable-benchmarks", "--enable-tests"] cabal "configure" ["--enable-benchmarks", "--enable-tests" ,"--allow-newer"] shouldFail $ cabal "configure" ["--allow-newer=Foo:base"] shouldFail $ cabal "configure" ["--allow-newer=Foo:base" ,"--enable-tests", "--enable-benchmarks"] cabal "configure" ["--allow-newer=AllowNewer:base"] cabal "configure" ["--allow-newer=AllowNewer:base" ,"--allow-newer=Foo:base"] cabal "configure" ["--allow-newer=AllowNewer:base" ,"--allow-newer=Foo:base" ,"--enable-tests", "--enable-benchmarks"] -- Test that Cabal can choose flags to disable building a component when that -- component's dependencies are unavailable. The build should succeed without -- requiring the component's dependencies or imports. tc "BuildableField" $ do r <- cabal' "configure" ["-v"] assertOutputContains "Flags chosen: build-exe=False" r cabal "build" [] -- TODO: Enable these tests on Windows unlessWindows $ do tc "GhcPkgGuess/SameDirectory" $ ghc_pkg_guess "ghc" tc "GhcPkgGuess/SameDirectoryVersion" $ ghc_pkg_guess "ghc-7.10" tc "GhcPkgGuess/SameDirectoryGhcVersion" $ ghc_pkg_guess "ghc-7.10" unlessWindows $ do tc "GhcPkgGuess/Symlink" $ do -- We don't want to distribute a tarball with symlinks. See #3190. withSymlink "bin/ghc" "tests/PackageTests/GhcPkgGuess/Symlink/ghc" $ ghc_pkg_guess "ghc" tc "GhcPkgGuess/SymlinkVersion" $ do withSymlink "bin/ghc-7.10" "tests/PackageTests/GhcPkgGuess/SymlinkVersion/ghc" $ ghc_pkg_guess "ghc" tc "GhcPkgGuess/SymlinkGhcVersion" $ do withSymlink "bin/ghc-7.10" "tests/PackageTests/GhcPkgGuess/SymlinkGhcVersion/ghc" $ ghc_pkg_guess "ghc" -- Test error message we report when a non-buildable target is -- requested to be built tc "BuildTargetErrors" $ do cabal "configure" [] assertOutputContains "the component is marked as disabled" =<< shouldFail (cabal' "build" ["not-buildable-exe"]) where ghc_pkg_guess bin_name = do cwd <- packageDir with_ghc <- getWithGhcPath r <- withEnv [("WITH_GHC", Just with_ghc)] . shouldFail $ cabal' "configure" ["-w", cwd </> bin_name] assertOutputContains "is version 9999999" r return () -- Shared test function for BuildDeps/InternalLibrary* tests. internal_lib_test expect = withPackageDb $ do withPackage "to-install" $ cabal_install [] cabal_build [] r <- runExe' "lemon" [] assertEqual ("executable should have linked with the " ++ expect ++ " library") ("foo foo myLibFunc " ++ expect) (concatOutput (resultOutput r)) assertRegex :: String -> String -> Result -> TestM () assertRegex msg regex r = let out = resultOutput r in assertBool (msg ++ ",\nactual output:\n" ++ out) (out =~ regex) tc :: FilePath -> TestM a -> TestTreeM () tc name = testTree config name Nothing
tolysz/prepare-ghcjs
spec-lts8/cabal/Cabal/tests/PackageTests/Tests.hs
bsd-3-clause
12,804
0
22
3,220
2,242
1,063
1,179
192
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} module Data.PSQ.Class.Tests ( tests ) where import Prelude hiding (null, lookup, map, foldr) import Control.Applicative ((<$>)) import Control.DeepSeq (NFData, rnf) import Data.Tagged (Tagged (..), untag) import qualified Data.List as List import Data.Char (isPrint, isAlphaNum, ord, toLower) import Data.Foldable (Foldable, foldr) import Test.QuickCheck (Arbitrary (..), Property, (==>), forAll) import Test.HUnit (Assertion, assert, (@?=)) import Test.Framework (Test) import Test.Framework.Providers.HUnit (testCase) import Test.Framework.Providers.QuickCheck2 (testProperty) import Data.PSQ.Class import Data.PSQ.Class.Gen import Data.PSQ.Class.Util -------------------------------------------------------------------------------- -- Index of tests -------------------------------------------------------------------------------- tests :: forall psq. (PSQ psq, TestKey (Key psq), Arbitrary (psq Int Char), Eq (psq Int Char), Foldable (psq Int), Functor (psq Int), NFData (psq Int Char), Show (psq Int Char)) => Tagged psq [Test] tests = Tagged [ testCase "rnf" (untag' test_rnf) , testCase "equality" (untag' test_equality) , testCase "size" (untag' test_size) , testCase "size2" (untag' test_size2) , testCase "empty" (untag' test_empty) , testCase "lookup" (untag' test_lookup) , testCase "findMin" (untag' test_findMin) , testCase "alter" (untag' test_alter) , testCase "alterMin" (untag' test_alterMin) , testCase "fromList" (untag' test_fromList) , testCase "foldr" (untag' test_foldr) , testProperty "show" (untag' prop_show) , testProperty "rnf" (untag' prop_rnf) , testProperty "size" (untag' prop_size) , testProperty "singleton" (untag' prop_singleton) , testProperty "memberLookup" (untag' prop_memberLookup) , testProperty "insertLookup" (untag' prop_insertLookup) , testProperty "insertDelete" (untag' prop_insertDelete) , testProperty "insertDeleteView" (untag' prop_insertDeleteView) , testProperty "deleteNonMember" (untag' prop_deleteNonMember) , testProperty "deleteMin" (untag' prop_deleteMin) , testProperty "alter" (untag' prop_alter) , testProperty "alterMin" (untag' prop_alterMin) , testProperty "toList" (untag' prop_toList) , testProperty "keys" (untag' prop_keys) , testProperty "insertView" (untag' prop_insertView) , testProperty "deleteView" (untag' prop_deleteView) , testProperty "map" (untag' prop_map) , testProperty "fmap" (untag' prop_fmap) , testProperty "fold'" (untag' prop_fold') , testProperty "foldr" (untag' prop_foldr) , testProperty "valid" (untag' prop_valid) ] where untag' :: Tagged psq test -> test untag' = untag -------------------------------------------------------------------------------- -- HUnit tests -------------------------------------------------------------------------------- test_rnf :: forall psq. (PSQ psq, TestKey (Key psq), NFData (psq Int Char)) => Tagged psq Assertion test_rnf = Tagged $ rnf (empty :: psq Int Char) `seq` return () test_equality :: forall psq. (PSQ psq, TestKey (Key psq), Eq (psq Int Char)) => Tagged psq Assertion test_equality = Tagged $ do -- Mostly to get 100% coverage assert $ e /= s assert $ s /= e where e = empty :: psq Int Char s = singleton 3 100 'a' :: psq Int Char test_size :: forall psq. (PSQ psq, TestKey (Key psq)) => Tagged psq Assertion test_size = Tagged $ do null (empty :: psq Int Char) @?= True null (singleton 1 100 'a' :: psq Int Char) @?= False test_size2 :: forall psq. (PSQ psq, TestKey (Key psq)) => Tagged psq Assertion test_size2 = Tagged $ do size (empty :: psq Int ()) @?= 0 size (singleton 1 100 'a' :: psq Int Char) @?= 1 size (fromList [(1, 100, 'a'), (2, 101, 'c'), (3, 102, 'b')] :: psq Int Char) @?= 3 test_empty :: forall psq. (PSQ psq, TestKey (Key psq)) => Tagged psq Assertion test_empty = Tagged $ do toList (empty :: psq Int ()) @?= [] size (empty :: psq Char Int) @?= 0 test_lookup :: forall psq. (PSQ psq, TestKey (Key psq)) => Tagged psq Assertion test_lookup = Tagged $ do employeeCurrency 1 @?= Just 1 employeeCurrency 2 @?= Nothing where employeeDept = fromList [(1, 100, 2), (3, 101, 1)] :: psq Int Int deptCountry = fromList [(1, 102, 1), (2, 103, 2)] :: psq Int Int countryCurrency = fromList [(1, 104, 2), (2, 105, 1)] :: psq Int Int employeeCurrency :: Int -> Maybe Int employeeCurrency name = do dept <- snd <$> lookup (toTestKey name) employeeDept country <- snd <$> lookup (toTestKey dept) deptCountry snd <$> lookup (toTestKey country) countryCurrency test_findMin :: forall psq. (PSQ psq, TestKey (Key psq)) => Tagged psq Assertion test_findMin = Tagged $ do findMin (empty :: psq Int Char) @?= Nothing findMin (fromList [(5, 101, 'a'), (3, 100, 'b')] :: psq Int Char) @?= Just (3, 100, 'b') test_alter :: forall psq. (PSQ psq, TestKey (Key psq), Eq (psq Int Char), Show (psq Int Char)) => Tagged psq Assertion test_alter = Tagged $ do alter f 3 (empty :: psq Int Char) @?= ("Hello", singleton 3 100 'a') alter f 3 (singleton 3 100 'a' :: psq Int Char) @?= ("World", empty) alter f 3 (singleton 3 100 'b' :: psq Int Char) @?= ("Cats", singleton 3 101 'b') where f Nothing = ("Hello", Just (100, 'a')) f (Just (100, 'a')) = ("World", Nothing) f (Just _) = ("Cats", Just (101, 'b')) test_alterMin :: forall psq. (PSQ psq, TestKey (Key psq), Eq (psq Int Char), Show (psq Int Char)) => Tagged psq Assertion test_alterMin = Tagged $ do alterMin (\_ -> ((), Nothing)) (empty :: psq Int Char) @?= ((), empty) alterMin (\_ -> ((), Nothing)) (singleton 3 100 'a' :: psq Int Char) @?= ((), empty) test_fromList :: forall psq. (PSQ psq, TestKey (Key psq), Eq (psq Int Char), Show (psq Int Char)) => Tagged psq Assertion test_fromList = Tagged $ let ls = [(1, 0, 'A'), (2, 0, 'B'), (3, 0, 'C'), (4, 0, 'D')] in (fromList ls :: psq Int Char) @?= fromList (reverse ls) test_foldr :: forall psq. (PSQ psq, TestKey (Key psq), Foldable (psq Int)) => Tagged psq Assertion test_foldr = Tagged $ foldr (\x acc -> acc + ord x) 0 (empty :: psq Int Char) @?= 0 -------------------------------------------------------------------------------- -- QuickCheck properties -------------------------------------------------------------------------------- -- | For 100% test coverage... prop_show :: forall psq. (PSQ psq, TestKey (Key psq), Show (psq Int Char)) => Tagged psq Property prop_show = Tagged $ forAll arbitraryPSQ $ \t -> length (coverShowInstance (t :: psq Int Char)) > 0 -- | For 100% test coverage... prop_rnf :: forall psq. (PSQ psq, TestKey (Key psq), NFData (psq Int Char), Show (psq Int Char)) => Tagged psq Property prop_rnf = Tagged $ forAll arbitraryPSQ $ \t -> rnf (t :: psq Int Char) `seq` True prop_size :: forall psq. (PSQ psq, TestKey (Key psq), Show (psq Int Char)) => Tagged psq (psq Int Char -> Bool) prop_size = Tagged $ \t -> size (t :: psq Int Char) == length (toList t) prop_singleton :: forall psq. (PSQ psq, TestKey (Key psq), Eq (psq Int Char)) => Tagged psq Property prop_singleton = Tagged $ forAll arbitraryTestKey $ \k -> forAll arbitraryPriority $ \p -> forAll arbitrary $ \x -> insert k p x empty == (singleton k p x :: psq Int Char) prop_memberLookup :: forall psq. (PSQ psq, TestKey (Key psq), Arbitrary (psq Int Char), Show (psq Int Char)) => Tagged psq (psq Int Char -> Property) prop_memberLookup = Tagged $ \t -> forAll arbitraryTestKey $ \k -> case lookup k (t :: psq Int Char) of Nothing -> not (member k t) Just _ -> member k t prop_insertLookup :: forall psq. (PSQ psq, TestKey (Key psq), Arbitrary (psq Int Char), Show (psq Int Char)) => Tagged psq (psq Int Char -> Property) prop_insertLookup = Tagged $ \t -> forAll arbitraryTestKey $ \k -> forAll arbitraryPriority $ \p -> forAll arbitrary $ \c -> lookup k (insert k p c (t :: psq Int Char)) == Just (p, c) prop_insertDelete :: forall psq. (PSQ psq, TestKey (Key psq), Arbitrary (psq Int Char), Eq (psq Int Char), Show (psq Int Char)) => Tagged psq (psq Int Char -> Property) prop_insertDelete = Tagged $ \t -> forAll arbitraryTestKey $ \k -> forAll arbitraryPriority $ \p -> forAll arbitrary $ \c -> (lookup k t == Nothing) ==> (delete k (insert k p c t) == (t :: psq Int Char)) prop_insertDeleteView :: forall psq. (PSQ psq, TestKey (Key psq), Arbitrary (psq Int Char), Eq (psq Int Char), Show (psq Int Char)) => Tagged psq (psq Int Char -> Property) prop_insertDeleteView = Tagged $ \t -> forAll arbitraryTestKey $ \k -> forAll arbitraryPriority $ \p -> forAll arbitrary $ \c -> case deleteView k (insert k p c (t :: psq Int Char)) of Nothing -> False Just (p', c', t') | member k t -> p' == p && c' == c && size t' < size t | otherwise -> p' == p && c' == c && t' == t prop_deleteNonMember :: forall psq. (PSQ psq, TestKey (Key psq), Arbitrary (psq Int Char), Eq (psq Int Char), Show (psq Int Char)) => Tagged psq (psq Int Char -> Property) prop_deleteNonMember = Tagged $ \t -> forAll arbitraryTestKey $ \k -> (lookup k t == Nothing) ==> (delete k t == (t :: psq Int Char)) prop_deleteMin :: forall psq. (PSQ psq, TestKey (Key psq), Arbitrary (psq Int Char), Eq (psq Int Char), Show (psq Int Char)) => Tagged psq (psq Int Char -> Bool) prop_deleteMin = Tagged $ \t -> let t' = deleteMin t in if null t then t' == t else case findMin t of Nothing -> False Just (k, _, _) -> size t' == size t - 1 && member k t && not (member k t') prop_alter :: forall psq. (PSQ psq, TestKey (Key psq), Show (psq Int Char)) => Tagged psq (psq Int Char -> Property) prop_alter = Tagged $ \t -> forAll arbitraryTestKey $ \k -> let ((), t') = alter f k t :: ((), psq Int Char) in case lookup k t of Just _ -> (size t - 1) == size t' && lookup k t' == Nothing Nothing -> (size t + 1) == size t' && lookup k t' /= Nothing where f Nothing = ((), Just (100, 'a')) f (Just _) = ((), Nothing) prop_alterMin :: forall psq. (PSQ psq, TestKey (Key psq), Arbitrary (psq Int Char), Eq (psq Int Char), Show (psq Int Char)) => Tagged psq (psq Int Char -> Bool) prop_alterMin = Tagged $ \t -> let (mbMin, t') = alterMin f (t :: psq Int Char) in case mbMin of Nothing -> t' == singleton 3 100 'a' Just (k, p, v) -> findMin t == Just (k, p, v) && member k t && (case () of _ | isAlphaNum v -> lookup k t' == Just (fromTestKey k, v) | isPrint v -> lookup (toTestKey $ ord v) t' == Just (ord v, v) | otherwise -> not (member k t')) where f Nothing = (Nothing, Just (3, 100, 'a')) f (Just (k, p, v)) | isAlphaNum v = (Just (k, p, v), Just (k, fromTestKey k, v)) | isPrint v = (Just (k, p, v), Just (toTestKey (ord v), ord v, v)) | otherwise = (Just (k, p, v), Nothing) prop_toList :: forall psq. (PSQ psq, TestKey (Key psq), Arbitrary (psq Int Char), Eq (psq Int Char), Show (psq Int Char)) => Tagged psq (psq Int Char -> Bool) prop_toList = Tagged $ \t -> (t :: psq Int Char) == fromList (toList t) prop_keys :: forall psq. (PSQ psq, TestKey (Key psq), Arbitrary (psq Int Char), Show (psq Int Char)) => Tagged psq (psq Int Char -> Bool) prop_keys = Tagged $ \t -> List.sort (keys (t :: psq Int Char)) == List.sort [k | (k, _, _) <- toList t] prop_insertView :: forall psq. (PSQ psq, TestKey (Key psq), Arbitrary (psq Int Char), Show (psq Int Char)) => Tagged psq (psq Int Char -> Property) prop_insertView = Tagged $ \t -> forAll arbitraryTestKey $ \k -> forAll arbitraryPriority $ \p -> forAll arbitrary $ \x -> case insertView k p x (t :: psq Int Char) of (mbPx, t') -> lookup k t == mbPx && lookup k t' == Just (p, x) prop_deleteView :: forall psq. (PSQ psq, TestKey (Key psq), Arbitrary (psq Int Char), Show (psq Int Char)) => Tagged psq (psq Int Char -> Property) prop_deleteView = Tagged $ \t -> forAll arbitraryTestKey $ \k -> case deleteView k (t :: psq Int Char) of Nothing -> not (member k t) Just (p, v, t') -> lookup k t == Just (p, v) && not (member k t') prop_map :: forall psq. (PSQ psq, TestKey (Key psq), Arbitrary (psq Int Char), Eq (psq Int Char), Show (psq Int Char)) => Tagged psq (psq Int Char -> Bool) prop_map = Tagged $ \t -> map f (t :: psq Int Char) == fromList (List.map (\(k, p, x) -> (k, p, f k p x)) (toList t)) where f k p x = if fromEnum k > p then x else 'a' prop_fmap :: forall psq. (PSQ psq, TestKey (Key psq), Arbitrary (psq Int Char), Eq (psq Int Char), Functor (psq Int), Show (psq Int Char)) => Tagged psq (psq Int Char -> Bool) prop_fmap = Tagged $ \t -> fmap toLower (t :: psq Int Char) == fromList (List.map (\(p, v, x) -> (p, v, toLower x)) (toList t)) prop_fold' :: forall psq. (PSQ psq, TestKey (Key psq), Arbitrary (psq Int Char), Show (psq Int Char)) => Tagged psq (psq Int Char -> Bool) prop_fold' = Tagged $ \t -> fold' f acc0 (t :: psq Int Char) == List.foldl' (\acc (k, p, x) -> f k p x acc) acc0 (toList t) where -- Needs to be commutative f k p x (kpSum, xs) = (kpSum + fromEnum k + p, List.sort (x : xs)) acc0 = (0, []) prop_foldr :: forall psq. (PSQ psq, Arbitrary (psq Int Char), Foldable (psq Int), Show (psq Int Char)) => Tagged psq (psq Int Char -> Bool) prop_foldr = Tagged $ \t -> foldr f 0 (t :: psq Int Char) == List.foldr (\(_, _, x) acc -> f x acc) 0 (toList t) where f x acc = acc + ord x prop_valid :: forall psq. (PSQ psq, Arbitrary (psq Int Char), Show (psq Int Char)) => Tagged psq (psq Int Char -> Bool) prop_valid = Tagged valid
phadej/psqueues
tests/Data/PSQ/Class/Tests.hs
bsd-3-clause
16,433
0
22
5,579
6,284
3,283
3,001
373
3
{-# OPTIONS_GHC -Wunused-imports -Wunused-top-binds #-} module T10347 (N, mkN, mkSum) where import Data.Coerce import Data.Monoid (Sum(Sum)) newtype N a = MkN Int mkN :: Int -> N a mkN = coerce -- Should mark MkN (a locally defined constructor) as used mkSum :: Int -> Sum Int mkSum = coerce -- Should mark Sum (an imported constructor) as used
sdiehl/ghc
testsuite/tests/typecheck/should_compile/T10347.hs
bsd-3-clause
349
0
6
63
80
49
31
9
1
module PackageTests.MultipleSource.Check ( tests ) where import PackageTests.PackageTester import Test.Framework as TF (Test) import Test.Framework.Providers.HUnit (testCase) import Control.Monad (void, when) import System.Directory (doesDirectoryExist) import System.FilePath ((</>)) dir :: FilePath dir = packageTestsDirectory </> "MultipleSource" tests :: TestsPaths -> [TF.Test] tests paths = [ testCase "finds second source of multiple source" $ do sandboxExists <- doesDirectoryExist $ dir </> ".cabal-sandbox" when sandboxExists $ void $ cabal_sandbox paths dir ["delete"] assertSandboxSucceeded =<< cabal_sandbox paths dir ["init"] assertSandboxSucceeded =<< cabal_sandbox paths dir ["add-source", "p"] assertSandboxSucceeded =<< cabal_sandbox paths dir ["add-source", "q"] assertInstallSucceeded =<< cabal_install paths dir ["q"] ]
DavidAlphaFox/ghc
libraries/Cabal/cabal-install/tests/PackageTests/MultipleSource/Check.hs
bsd-3-clause
961
0
11
215
235
128
107
20
1
module TerminationExpr where {-@ showSep :: _ -> xs:_ -> _ / [xs] @-} -- use xs as reducing param showSep :: String -> [String] -> String showSep sep [] = "" showSep sep [x] = x showSep sep (x:xs) = x ++ sep ++ showSep sep xs
mightymoose/liquidhaskell
tests/error_messages/crash/TerminationExpr1.hs
bsd-3-clause
235
0
7
57
77
42
35
5
1
{-# LANGUAGE CPP, ForeignFunctionInterface #-} ----------------------------------------------------------------------------- {- | Module : Numeric.GSL.Polynomials Copyright : (c) Alberto Ruiz 2006 License : GPL-style Maintainer : Alberto Ruiz (aruiz at um dot es) Stability : provisional Portability : uses ffi Polynomials. <http://www.gnu.org/software/gsl/manual/html_node/General-Polynomial-Equations.html#General-Polynomial-Equations> -} ----------------------------------------------------------------------------- module Numeric.GSL.Polynomials ( polySolve ) where import Data.Packed.Internal import Data.Complex import System.IO.Unsafe (unsafePerformIO) #if __GLASGOW_HASKELL__ >= 704 import Foreign.C.Types (CInt(..)) #endif {- | Solution of general polynomial equations, using /gsl_poly_complex_solve/. For example, the three solutions of x^3 + 8 = 0 @\> polySolve [8,0,0,1] [(-1.9999999999999998) :+ 0.0, 1.0 :+ 1.732050807568877, 1.0 :+ (-1.732050807568877)]@ The example in the GSL manual: To find the roots of x^5 -1 = 0: @\> polySolve [-1, 0, 0, 0, 0, 1] [(-0.8090169943749475) :+ 0.5877852522924731, (-0.8090169943749475) :+ (-0.5877852522924731), 0.30901699437494734 :+ 0.9510565162951536, 0.30901699437494734 :+ (-0.9510565162951536), 1.0 :+ 0.0]@ -} polySolve :: [Double] -> [Complex Double] polySolve = toList . polySolve' . fromList polySolve' :: Vector Double -> Vector (Complex Double) polySolve' v | dim v > 1 = unsafePerformIO $ do r <- createVector (dim v-1) app2 c_polySolve vec v vec r "polySolve" return r | otherwise = error "polySolve on a polynomial of degree zero" foreign import ccall unsafe "gsl-aux.h polySolve" c_polySolve:: TVCV
mightymoose/liquidhaskell
benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL/Polynomials.hs
bsd-3-clause
1,736
0
13
268
201
108
93
15
1
import qualified Data.Vector as U import Data.Bits main = print . U.length . U.init . U.replicate 1000000 $ (7 :: Int)
dolio/vector
old-testsuite/microsuite/init.hs
bsd-3-clause
120
0
9
22
50
28
22
3
1
{-# LANGUAGE UnliftedFFITypes, MagicHash #-} -- !!! illegal types in foreign export delarations module ShouldFail where import GHC.Exts foreign export ccall foo :: Int# -> IO () foo i | isTrue# (i ==# 0#) = return () foreign export ccall bar :: Int -> Int# bar _ = 42#
ghc-android/ghc
testsuite/tests/ffi/should_fail/ccfail003.hs
bsd-3-clause
272
0
10
52
81
43
38
7
1
{-# LANGUAGE RecordWildCards, TransformListComp, NamedFieldPuns #-} module T3901 where import GHC.Exts (groupWith) data Rec = Rec {a :: Int} deriving (Show) recs1 = [a | Rec {a=a} <- [Rec 1], then group by a using groupWith] recs2 = [a | Rec {a} <- [Rec 1], then group by a using groupWith] recs3 = [a | Rec {..} <- [Rec 1], then group by a using groupWith] recs4 :: [[Int]] recs4 = [a | Rec {..} <- [Rec 1], then group by a using groupWith]
urbanslug/ghc
testsuite/tests/rename/should_compile/T3901.hs
bsd-3-clause
449
0
10
91
199
112
87
9
1
module SyntheticWeb.Client.SizeUrl ( SizeUrl , Payload , Url , fromSize , toUrl , toPayload ) where import Control.Monad.IO.Class (MonadIO) import SyntheticWeb.Plan.Types (Bytes, Size (..)) import SyntheticWeb.Statistical (Statistical (Exactly), sample) import System.Random.MWC (GenIO) import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy.Char8 as LBS type Url = BS.ByteString type Payload = LBS.ByteString -- | Representation of a "size url". An url where a number - integer -- based size - shall be translated to an url or a sized payload. newtype SizeUrl = SizeUrl Bytes deriving (Show) -- | Create a SizeUrl from a Size. fromSize :: MonadIO m => Size -> GenIO -> m SizeUrl fromSize (Size stat) gen = do Exactly bytes <- sample stat gen return $ SizeUrl bytes -- | Translate the SizeUrl to an url. toUrl :: SizeUrl -> Url toUrl (SizeUrl bytes) = '/' `BS.cons` BS.pack (show bytes) -- | Translate the SizeUrl to an equally sized payload. toPayload :: SizeUrl -> Payload -> Payload toPayload (SizeUrl bytes) = LBS.take (fromIntegral bytes)
kosmoskatten/synthetic-web
src/SyntheticWeb/Client/SizeUrl.hs
mit
1,112
0
8
206
284
165
119
25
1
-- Question 1 -- - Make a list of suits and list of rank -- - Loop in list of suits and pick only one rank randomly for each suit
martindavid/code-sandbox
comp90048/workshop/my_answer/workshop1.hs
mit
132
0
2
32
5
4
1
1
0
foo bar = baz
chreekat/vim-haskell-syntax
test/golden/toplevel/arg.hs
mit
14
0
4
4
9
4
5
1
1
{-| Module : PansiteApp.PandocTool Description : Pandoc tool Copyright : (C) Richard Cook, 2017-2018 Licence : MIT Maintainer : [email protected] Stability : experimental Portability : portable -} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module PansiteApp.PandocTool (pandocTool) where import Data.Aeson import Data.Aeson.Types import qualified Data.ByteString.Lazy as BL import Data.Default import Data.List import qualified Data.Text as Text (pack) import qualified Data.Text.IO as Text (writeFile) import Pansite import PansiteApp.Util import System.FilePath import Text.Blaze.Html.Renderer.String import Text.Pandoc ( Extension(..) , HTMLMathMethod(..) , Inline(..) , WriterOptions(..) , enableExtension , readMarkdown , readerExtensions , runPure , writeDocx , writeHtml5 ) import Text.Pandoc.Walk (walk) import Text.Pandoc.XML (toEntities) data PandocSettings = PandocSettings { psNumberSections :: Bool , psVars :: [(String, String)] , psTemplatePath :: Maybe FilePath , psTableOfContents :: Bool , psReferenceDoc :: Maybe FilePath , psMathJaxEnabled :: Bool , psIncludeInHeaderPath :: Maybe FilePath , psIncludeBeforeBodyPath :: Maybe FilePath , psIncludeAfterBodyPath :: Maybe FilePath } instance Default PandocSettings where def = PandocSettings False [] Nothing False Nothing False Nothing Nothing Nothing updater :: PandocSettings -> UpdateContext -> Value -> Parser PandocSettings updater PandocSettings{..} (UpdateContext resolveFilePath) = withObject "pandoc" $ \o -> let getFilePath key d = fmap (resolveFilePath <$>) (o .:? key .!= d) in PandocSettings <$> o .:? "number-sections" .!= psNumberSections <*> o .:? "vars" .!= psVars <*> getFilePath "template-path" psTemplatePath <*> o .:? "table-of-contents" .!= psTableOfContents <*> getFilePath "reference-doc" psReferenceDoc <*> o .:? "mathjax" .!= psMathJaxEnabled <*> getFilePath "include-in-header-path" psIncludeInHeaderPath <*> getFilePath "include-before-body-path" psIncludeBeforeBodyPath <*> getFilePath "include-after-body-path" psIncludeAfterBodyPath mathJaxUrl :: String mathJaxUrl = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_CHTML-full" maybeReadFileUtf8 :: Maybe FilePath -> IO (Maybe String) maybeReadFileUtf8 (Just path) = Just <$> readFileUtf8 path maybeReadFileUtf8 Nothing = return Nothing mkWriterOptions :: PandocSettings -> IO WriterOptions mkWriterOptions PandocSettings{..} = do mbTemplate <- maybeReadFileUtf8 psTemplatePath mbIncludeInHeader <- maybeReadFileUtf8 psIncludeInHeaderPath mbIncludeBeforeBody <- maybeReadFileUtf8 psIncludeBeforeBodyPath mbIncludeAfterBody <- maybeReadFileUtf8 psIncludeAfterBodyPath -- TODO: Let's do this more elegantly! Looks a little like a fold... let psVars1 = case mbIncludeInHeader of Nothing -> psVars Just s -> ("header-includes", s) : psVars psVars2 = case mbIncludeBeforeBody of Nothing -> psVars1 Just s -> ("include-before", s) : psVars1 psVars3 = case mbIncludeAfterBody of Nothing -> psVars2 Just s -> ("include-after", s) : psVars2 let htmlMathMethod = if psMathJaxEnabled then MathJax mathJaxUrl else PlainMath return $ def { writerNumberSections = psNumberSections , writerReferenceDoc = psReferenceDoc , writerTemplate = mbTemplate , writerTableOfContents = psTableOfContents , writerHTMLMathMethod = htmlMathMethod , writerVariables = psVars3 } runner :: PandocSettings -> RunContext -> IO () runner ps@PandocSettings{..} (RunContext outputPath inputPaths _) = do putStrLn "PandocTool" putStrLn $ " outputPath=" ++ outputPath putStrLn $ " inputPaths=" ++ show inputPaths putStrLn $ " psNumberSections=" ++ show psNumberSections putStrLn $ " psReferenceDoc=" ++ show psReferenceDoc putStrLn $ " psTableOfContents=" ++ show psTableOfContents putStrLn $ " psTemplatePath=" ++ show psTemplatePath putStrLn $ " psVars=" ++ show psVars md <- (intercalate "\n\n") <$> sequence (map readFileUtf8 inputPaths) let mdText = Text.pack md readerOpts = def exts = foldl' (flip enableExtension) (readerExtensions readerOpts) [Ext_backtick_code_blocks, Ext_yaml_metadata_block] readerOpts' = readerOpts { readerExtensions = exts } Right doc' = runPure $ readMarkdown readerOpts' mdText -- TODO: Irrefutable pattern doc = walk rewriteLinks doc' writerOpts <- mkWriterOptions ps -- TODO: Ugh. Let's make this less hacky. It works for now though. case (takeExtension outputPath) of ".docx" -> do let Right docx = runPure $ writeDocx writerOpts doc -- TODO: Irrefutable pattern BL.writeFile outputPath docx _ -> do let Right html = runPure $ writeHtml5 writerOpts doc -- TODO: Irrefutable pattern t = toEntities (Text.pack $ renderHtml html) Text.writeFile outputPath t -- TODO: This is very application-specific -- TODO: Figure out how to allow this behaviour to be specified in app configuration transformUrl :: String -> String transformUrl url = let (path, ext) = splitExtension url in case ext of ".md" -> path _ -> url -- TODO: This is very application-specific -- TODO: Figure out how to allow this behaviour to be specified in app configuration rewriteLinks :: Inline -> Inline rewriteLinks (Link attr is (url, title)) = Link attr is (transformUrl url, title) rewriteLinks i = i pandocTool :: Tool pandocTool = mkTool $ PandocSettings False [] Nothing False Nothing False Nothing Nothing Nothing mkTool :: PandocSettings -> Tool mkTool state = Tool "pandoc" updater' (runner state) where updater' ctx value = mkTool <$> updater state ctx value
rcook/pansite
app/PansiteApp/PandocTool.hs
mit
6,565
0
25
1,846
1,364
712
652
128
5
module Types ( module Data.Direction , module Types.Size , module Types.Jewel , module Types.Item , module Types.Consumable , module Types.Block , module Types.Enemy , module Types.GroundItem , module Types.Wall , module Types.Entity , module Types.Room , module Types.Level , module Types.Player , module Types.TextlunkyCommand , module Types.GameState , module Data.Vectors , module Types.Synonyms ) where import Data.Direction import Types.Size import Types.Jewel import Types.Item import Types.Consumable import Types.Block import Types.Enemy import Types.GroundItem import Types.Wall import Types.Entity import Types.Room import Types.Level import Types.Player import Types.TextlunkyCommand import Types.GameState import Data.Vectors import Types.Synonyms
5outh/textlunky
src/Types.hs
mit
1,006
0
5
334
193
123
70
35
0
module InitialUniverseProperties where import Test.Tasty import Test.Tasty.QuickCheck import qualified Data.Map as M import Rules import Data.AdditiveGroup import Data.List initialUniverseTests :: TestTree initialUniverseTests = testGroup "Initial universe tests" [ testProperty "There are workplaces with resources" $ let workplaceResources = getWorkplaceResources <$> M.elems (getWorkplaces initialUniverse) in any (/= zeroV) workplaceResources, testProperty "There are workplaces of all types" $ let workplaceTypes = nub $ sort $ getWorkplaceType <$> M.elems (getWorkplaces initialUniverse) in workplaceTypes == [CutForest ..], testProperty "There are no more than 40 workplaces" $ M.size (getWorkplaces initialUniverse) <= 40 ]
martin-kolinek/some-board-game-rules
test/InitialUniverseProperties.hs
mit
780
0
15
136
173
92
81
18
1
{-# LANGUAGE OverloadedStrings, QuasiQuotes, TemplateHaskell #-} module Language.C.Inline.Win32 (win32Ctx) where import Data.Monoid (mempty) import Language.C.Inline import Language.C.Inline.Context import System.Win32.Types import qualified Data.Map as Map import qualified Language.C.Types as C import qualified Language.Haskell.TH as TH win32Ctx :: Context win32Ctx = mempty { ctxTypesTable = win32TypesTable } win32TypesTable :: Map.Map C.TypeSpecifier TH.TypeQ win32TypesTable = Map.fromList [ (C.TypeName "BOOL", [t| BOOL |]) , (C.TypeName "BYTE", [t| BYTE |]) , (C.TypeName "UCHAR", [t| UCHAR |]) , (C.TypeName "USHORT", [t| USHORT |]) , (C.TypeName "UINT", [t| UINT |]) , (C.TypeName "INT", [t| INT |]) , (C.TypeName "WORD", [t| WORD |]) , (C.TypeName "DWORD", [t| DWORD |]) , (C.TypeName "LONG", [t| LONG |]) , (C.TypeName "FLOAT", [t| FLOAT |]) , (C.TypeName "LARGE_INTEGER", [t| LARGE_INTEGER |]) , (C.TypeName "UINT_PTR", [t| UINT_PTR |]) , (C.TypeName "DDWORD", [t| DDWORD |]) , (C.TypeName "ATOM", [t| ATOM |]) , (C.TypeName "WPARAM", [t| WPARAM |]) , (C.TypeName "LPARAM", [t| LPARAM |]) , (C.TypeName "LRESULT", [t| LRESULT |]) , (C.TypeName "SIZE_T", [t| SIZE_T |]) , (C.TypeName "HRESULT", [t| HRESULT |]) , (C.TypeName "LPVOID", [t| LPVOID |]) , (C.TypeName "LPBOOL", [t| LPBOOL |]) , (C.TypeName "LPBYTE", [t| LPBYTE |]) , (C.TypeName "PUCHAR", [t| PUCHAR |]) , (C.TypeName "LPDWORD", [t| LPDWORD |]) , (C.TypeName "LPSTR", [t| LPSTR |]) , (C.TypeName "LPCSTR", [t| LPCSTR |]) , (C.TypeName "LPWSTR", [t| LPWSTR |]) , (C.TypeName "LPCWSTR", [t| LPCWSTR |]) , (C.TypeName "LPTSTR", [t| LPTSTR |]) , (C.TypeName "LPCTSTR", [t| LPCTSTR |]) , (C.TypeName "HANDLE", [t| HANDLE |]) , (C.TypeName "HINSTANCE", [t| HINSTANCE |]) , (C.TypeName "HMODULE", [t| HMODULE |]) ]
anton-dessiatov/inline-c-win32
src/Language/C/Inline/Win32.hs
mit
1,855
0
9
323
707
469
238
46
1
module Language.Scheme.Error where import Language.Scheme.Error.Types import Control.Monad.Except (catchError) -- | We purposely leave extractValue undefined for a Left constructor, because that represents a programmer error. We intend to use extractValue only after a catchError, so it's better to fail fast than to inject bad values into the rest of the program. extractValue :: ThrowsError a -> a extractValue (Right val) = val -- Needs a type signature trapError action = catchError action (return . show)
stefaneng/scheme48
src/Language/Scheme/Error.hs
mit
513
0
7
78
73
42
31
6
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} -- NOTE: re-exported from Test.Hspec.Core.Spec module Test.Hspec.Core.Spec.Monad ( Spec , SpecWith , SpecM (..) , runSpecM , fromSpecList , runIO , mapSpecForest , mapSpecItem , mapSpecItem_ , modifyParams , modifyConfig ) where import Prelude () import Test.Hspec.Core.Compat import Control.Arrow import Control.Monad.Trans.Writer import Control.Monad.IO.Class (liftIO) import Test.Hspec.Core.Example import Test.Hspec.Core.Tree import Test.Hspec.Core.Config.Definition (Config) type Spec = SpecWith () type SpecWith a = SpecM a () -- | -- @since 2.10.0 modifyConfig :: (Config -> Config) -> SpecWith a modifyConfig f = SpecM $ tell (Endo f, mempty) -- | A writer monad for `SpecTree` forests newtype SpecM a r = SpecM (WriterT (Endo Config, [SpecTree a]) IO r) deriving (Functor, Applicative, Monad) -- | Convert a `Spec` to a forest of `SpecTree`s. runSpecM :: SpecWith a -> IO (Endo Config, [SpecTree a]) runSpecM (SpecM specs) = execWriterT specs -- | Create a `Spec` from a forest of `SpecTree`s. fromSpecForest :: (Endo Config, [SpecTree a]) -> SpecWith a fromSpecForest = SpecM . tell -- | Create a `Spec` from a forest of `SpecTree`s. fromSpecList :: [SpecTree a] -> SpecWith a fromSpecList = fromSpecForest . (,) mempty -- | Run an IO action while constructing the spec tree. -- -- `SpecM` is a monad to construct a spec tree, without executing any spec -- items. @runIO@ allows you to run IO actions during this construction phase. -- The IO action is always run when the spec tree is constructed (e.g. even -- when @--dry-run@ is specified). -- If you do not need the result of the IO action to construct the spec tree, -- `Test.Hspec.Core.Hooks.beforeAll` may be more suitable for your use case. runIO :: IO r -> SpecM a r runIO = SpecM . liftIO mapSpecForest :: ([SpecTree a] -> [SpecTree b]) -> SpecM a r -> SpecM b r mapSpecForest f (SpecM specs) = SpecM (mapWriterT (fmap (fmap (second f))) specs) mapSpecItem :: (ActionWith a -> ActionWith b) -> (Item a -> Item b) -> SpecWith a -> SpecWith b mapSpecItem g f = mapSpecForest (bimapForest g f) mapSpecItem_ :: (Item a -> Item a) -> SpecWith a -> SpecWith a mapSpecItem_ = mapSpecItem id modifyParams :: (Params -> Params) -> SpecWith a -> SpecWith a modifyParams f = mapSpecItem_ $ \item -> item {itemExample = \p -> (itemExample item) (f p)}
hspec/hspec
hspec-core/src/Test/Hspec/Core/Spec/Monad.hs
mit
2,458
0
13
488
656
361
295
43
1
module Handler.DeleteMember where import Import postDeleteMemberR :: TutorialName -> TutorialNames -> Handler Html postDeleteMemberR tn tns = do Entity _ Profile {..} <- requireProfile let parent | null tns = UserR profileHandle | otherwise = UserTutorialR profileHandle tn $ allButLast tns mconfirm <- lookupPostParam confirm eres <- $runDB $ do eres <- followSlugPath profileUser tn tns (mid, Entity _ content, _) <- either (const notFound) return eres m <- get404 mid (ownerUsages, foreignUsages) <- findOtherUsages mid (tmemberContent m) let helper :: (PersistEntity value, PersistEntityBackend value ~ SqlBackend) => Key value -> (value -> Maybe UserId) -> Text -> YesodDB App (Either Html (Route App)) helper id' getUser word = case mmsg of Nothing -> do deleteWhere [TmemberContent ==. tmemberContent m] muid <- getUser <$> get404 id' forM_ muid populateUserSummary setMessage $ toHtml $ word ++ " deleted" return $ Right parent Just msgs -> lift $ fmap Left $ defaultLayout $ do setTitle "Confirm deletion" [whamlet| <form method=post> $forall msg <- msgs <p>#{msg} <div> <button name=#{confirm} .confirm-button value=confirm>Confirm <a href=@{UserTutorialR profileHandle tn tns}>Cancel |] where word' = toLower word mmsg = case (null foreignUsages, mconfirm) of (True, Nothing) -> Just ["Are you sure you wish to remove this " ++ word' ++ "?"] (False, Nothing) -> Just $ (word ++ " is linked from the following foreign locations. Are you sure you wish to remove it?") : foreignUsages (_, Just _) -> Nothing if null ownerUsages then do -- No other links exist from the current user. case content of TcontentGroupSum gid -> do -- Only delete groups if they are empty. Entity hid _ <- getGroupHolder gid children <- count [TmemberHolder ==. hid] if children > 0 then do lift $ setMessage "Cannot remove non-empty group. Please first remove all contents." return $ Right $ UserTutorialR profileHandle tn tns else do case (null foreignUsages, mconfirm) of (False, Nothing) -> lift $ fmap Left $ defaultLayout $ do setTitle "Confirm deletion" [whamlet| <form method=post> <p>Other users link to this group. Are you sure you wish to delete it? <div> <button .confirm-button name=#{confirm} value=confirm>Confirm <a href=@{UserTutorialR profileHandle tn tns}>Cancel |] _ -> do deleteCascade gid setMessage "Group deleted" return $ Right parent TcontentTutorialSum tid -> do deleteWhere [RecentTutorialTutorial ==. tid] helper tid (Just . tutorialAuthor) "Tutorial" TcontentProjectSum _ -> fail "Cannot delete project from schoolofhaskell.com, instead use fpcomplete.com" else do -- Other links exists, we can delete this one delete mid setMessage "Content deleted" return $ Right parent case eres of Left html -> return html Right dest -> redirect dest where allButLast [] = [] allButLast [_] = [] allButLast (x:xs) = x : allButLast xs confirm = asText "confirm"
fpco/schoolofhaskell.com
src/Handler/DeleteMember.hs
mit
4,760
18
13
2,336
806
394
412
-1
-1
module Control.AutoUpdate.Util ( requestAnimationFrame , cancelAnimationFrame , waitForAnimationFrame , handle , cb ) where import GHCJS.Types import GHCJS.Foreign import Control.Concurrent.MVar (putMVar, takeMVar, newEmptyMVar) import System.IO hiding (Handle) newtype Handle = Handle (JSRef Handle) foreign import javascript unsafe "requestAnimationFrame" js_requestAnimationFrame :: JSFun (IO ()) -> IO Handle foreign import javascript unsafe "cancelAnimationFrame($1)" js_cancelAnimationFrame :: Handle -> IO () data AnimationFrameHandle = AnimationFrameHandle { handle :: Handle, cb :: JSFun (IO ())} requestAnimationFrame :: IO () -> IO AnimationFrameHandle requestAnimationFrame x = do cb <- fixIO $ \cb -> syncCallback AlwaysRetain True (release cb >> x) h <- js_requestAnimationFrame cb return $ AnimationFrameHandle h cb cancelAnimationFrame :: AnimationFrameHandle -> IO () cancelAnimationFrame (AnimationFrameHandle h cb) = release cb >> js_cancelAnimationFrame h waitForAnimationFrame :: IO () waitForAnimationFrame = do v <- newEmptyMVar requestAnimationFrame $ putMVar v () takeMVar v
arianvp/ghcjs-auto-update
Control/AutoUpdate/Util.hs
mit
1,139
9
14
175
321
166
155
29
1
module Zwerg.Graphics.Brick where import Zwerg.Prelude hiding ((<>)) import Zwerg import Zwerg.Event.Queue import Zwerg.Game import Zwerg.Graphics.Brick.Builder import Zwerg.Random import Zwerg.UI.Input import Brick.AttrMap import Brick.Util (on, fg) import Brick.Widgets.ProgressBar import Control.Monad.IO.Class (MonadIO, liftIO) import qualified Brick.Main as BM import qualified Brick.Types as BT import qualified Graphics.Vty as VTY import Data.Monoid ((<>)) import System.Mem (performGC) import Lens.Micro.Platform (view, set) import System.IO (hFlush, stderr) handleEventZwerg :: HasCallStack => ZwergState -> BT.BrickEvent () ZwergEvent -> BT.EventM () (BT.Next ZwergState) handleEventZwerg zs (BT.VtyEvent ev) = do liftIO $ hFlush stderr liftIO performGC let eventVTYtoZwergInput :: VTY.Event -> Maybe KeyCode eventVTYtoZwergInput (VTY.EvKey VTY.KEsc []) = Just Escape eventVTYtoZwergInput (VTY.EvKey (VTY.KChar ch) []) = Just $ KeyChar ch eventVTYtoZwergInput (VTY.EvKey VTY.KEnter []) = Just Return eventVTYtoZwergInput _ = Nothing case eventVTYtoZwergInput ev of Just Escape -> BM.halt zs Just key -> do let st = view gameState zs st' = runGame (processUserInput key) (view ranGen zs) st zs' = set gameState st' zs badPlayerInput = view (gameState . playerGoofed) zs' if badPlayerInput then BM.continue $ set (gameState . eventQueue) zDefault $ set (gameState . userLog) (view (gameState . userLog) zs') zs else BM.continue zs' _ -> BM.continue zs handleEventZwerg a b = BM.resizeOrQuit a b theMap :: AttrMap theMap = attrMap VTY.defAttr [ ("inventory" <> "focused" , VTY.black `Brick.Util.on` VTY.white ) , ("inventory" <> "unfocused" , VTY.white `Brick.Util.on` VTY.black ) , ("inventory" <> "drop_focused" , VTY.black `Brick.Util.on` VTY.red ) , ("inventory" <> "drop_unfocused" , VTY.white `Brick.Util.on` VTY.red ) , ("logo" , fg VTY.red) , (progressCompleteAttr , VTY.black `on` VTY.green ) , (progressIncompleteAttr , VTY.black `on` VTY.red ) ] zwergApp :: BM.App ZwergState ZwergEvent () zwergApp = BM.App { BM.appDraw = buildZwergUI , BM.appHandleEvent = handleEventZwerg , BM.appStartEvent = return , BM.appAttrMap = const theMap , BM.appChooseCursor = BM.neverShowCursor } initBrick :: (HasCallStack, MonadIO m) => m () initBrick = do gen <- newPureRanGen void $ liftIO $ BM.defaultMain zwergApp $ set ranGen gen initZwergState
zmeadows/zwerg
lib/Zwerg/Graphics/Brick.hs
mit
2,666
0
18
631
855
468
387
-1
-1
-- FrostyX's XMonad configuration -- -- This XMonad configuration is a mess. I am a newbie trying to hack things together -- and experiment. Do not take anything from this configuration unles you know what -- you are doing. Because the odds are, that I am not. -- -- Reload configuration: -- xmonad --recompile; xmonad --restart -- -- xmonad example config file. -- -- A template showing all available configuration hooks, -- and how to override the defaults in your own xmonad.hs conf file. -- -- Normally, you'd only override those defaults you care about. -- import XMonad import Data.Monoid import System.Exit import XMonad.Hooks.ManageDocks import qualified XMonad.StackSet as W import qualified Data.Map as M -- The preferred terminal program, which is used in a binding below and by -- certain contrib modules. -- myTerminal = "xterm" -- Whether focus follows the mouse pointer. myFocusFollowsMouse :: Bool myFocusFollowsMouse = True -- Whether clicking on a window to focus also passes the click to the window myClickJustFocuses :: Bool myClickJustFocuses = False -- Width of the window border in pixels. -- myBorderWidth = 1 -- modMask lets you specify which modkey you want to use. The default -- is mod1Mask ("left alt"). You may also consider using mod3Mask -- ("right alt"), which does not conflict with emacs keybindings. The -- "windows key" is usually mod4Mask. -- myModMask = mod1Mask -- The default number of workspaces (virtual screens) and their names. -- By default we use numeric strings, but any string may be used as a -- workspace name. The number of workspaces is determined by the length -- of this list. -- -- A tagging example: -- -- > workspaces = ["web", "irc", "code" ] ++ map show [4..9] -- myWorkspaces = ["1","2","3","4","5","6","7","8","9"] -- Border colors for unfocused and focused windows, respectively. -- myNormalBorderColor = "#dddddd" myFocusedBorderColor = "#ff0000" ------------------------------------------------------------------------ -- Key bindings. Add, modify or remove key bindings here. -- myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList $ -- launch a terminal [ ((modm .|. shiftMask, xK_Return), spawn $ XMonad.terminal conf) -- launch dmenu , ((modm, xK_p ), spawn "dmenu_run") -- launch gmrun , ((modm .|. shiftMask, xK_p ), spawn "gmrun") -- close focused window , ((modm .|. shiftMask, xK_c ), kill) -- Rotate through the available layout algorithms , ((modm, xK_space ), sendMessage NextLayout) -- Reset the layouts on the current workspace to default , ((modm .|. shiftMask, xK_space ), setLayout $ XMonad.layoutHook conf) -- Resize viewed windows to the correct size , ((modm, xK_n ), refresh) -- Move focus to the next window , ((modm, xK_Tab ), windows W.focusDown) -- Move focus to the next window , ((modm, xK_j ), windows W.focusDown) -- Move focus to the previous window , ((modm, xK_k ), windows W.focusUp ) -- Move focus to the master window , ((modm, xK_m ), windows W.focusMaster ) -- Swap the focused window and the master window , ((modm, xK_Return), windows W.swapMaster) -- Swap the focused window with the next window , ((modm .|. shiftMask, xK_j ), windows W.swapDown ) -- Swap the focused window with the previous window , ((modm .|. shiftMask, xK_k ), windows W.swapUp ) -- Shrink the master area , ((modm, xK_h ), sendMessage Shrink) -- Expand the master area , ((modm, xK_l ), sendMessage Expand) -- Push window back into tiling , ((modm, xK_t ), withFocused $ windows . W.sink) -- Increment the number of windows in the master area , ((modm , xK_comma ), sendMessage (IncMasterN 1)) -- Deincrement the number of windows in the master area , ((modm , xK_period), sendMessage (IncMasterN (-1))) -- Toggle the status bar gap -- Use this binding with avoidStruts from Hooks.ManageDocks. -- See also the statusBar function from Hooks.DynamicLog. -- -- , ((modm , xK_b ), sendMessage ToggleStruts) -- Quit xmonad , ((modm .|. shiftMask, xK_q ), io (exitWith ExitSuccess)) -- Restart xmonad , ((modm , xK_q ), spawn "xmonad --recompile; xmonad --restart") -- Run xmessage with a summary of the default keybindings (useful for beginners) , ((modm .|. shiftMask, xK_slash ), spawn ("echo \"" ++ help ++ "\" | xmessage -file -")) ] ++ -- -- mod-[1..9], Switch to workspace N -- mod-shift-[1..9], Move client to workspace N -- [((m .|. modm, k), windows $ f i) | (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9] , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]] ++ -- -- mod-{w,e,r}, Switch to physical/Xinerama screens 1, 2, or 3 -- mod-shift-{w,e,r}, Move client to screen 1, 2, or 3 -- [((m .|. modm, key), screenWorkspace sc >>= flip whenJust (windows . f)) | (key, sc) <- zip [xK_w, xK_e, xK_r] [0..] , (f, m) <- [(W.view, 0), (W.shift, shiftMask)]] ------------------------------------------------------------------------ -- Mouse bindings: default actions bound to mouse events -- myMouseBindings (XConfig {XMonad.modMask = modm}) = M.fromList $ -- mod-button1, Set the window to floating mode and move by dragging [ ((modm, button1), (\w -> focus w >> mouseMoveWindow w >> windows W.shiftMaster)) -- mod-button2, Raise the window to the top of the stack , ((modm, button2), (\w -> focus w >> windows W.shiftMaster)) -- mod-button3, Set the window to floating mode and resize by dragging , ((modm, button3), (\w -> focus w >> mouseResizeWindow w >> windows W.shiftMaster)) -- you may also bind events to the mouse scroll wheel (button4 and button5) ] ------------------------------------------------------------------------ -- Layouts: -- You can specify and transform your layouts by modifying these values. -- If you change layout bindings be sure to use 'mod-shift-space' after -- restarting (with 'mod-q') to reset your layout state to the new -- defaults, as xmonad preserves your old layout settings by default. -- -- The available layouts. Note that each layout is separated by |||, -- which denotes layout choice. -- myLayout = tiled ||| Mirror tiled ||| Full where -- default tiling algorithm partitions the screen into two panes tiled = Tall nmaster delta ratio -- The default number of windows in the master pane nmaster = 1 -- Default proportion of screen occupied by master pane ratio = 1/2 -- Percent of screen to increment by when resizing panes delta = 3/100 ------------------------------------------------------------------------ -- Window rules: -- Execute arbitrary actions and WindowSet manipulations when managing -- a new window. You can use this to, for example, always float a -- particular program, or have a client always appear on a particular -- workspace. -- -- To find the property name associated with a program, use -- > xprop | grep WM_CLASS -- and click on the client you're interested in. -- -- To match on the WM_NAME, you can use 'title' in the same way that -- 'className' and 'resource' are used below. -- myManageHook = composeAll [ className =? "MPlayer" --> doFloat , className =? "Gimp" --> doFloat , resource =? "desktop_window" --> doIgnore , resource =? "kdesktop" --> doIgnore ] ------------------------------------------------------------------------ -- Event handling -- * EwmhDesktops users should change this to ewmhDesktopsEventHook -- -- Defines a custom handler function for X Events. The function should -- return (All True) if the default handler is to be run afterwards. To -- combine event hooks use mappend or mconcat from Data.Monoid. -- myEventHook = mempty ------------------------------------------------------------------------ -- Status bars and logging -- Perform an arbitrary action on each internal state change or X event. -- See the 'XMonad.Hooks.DynamicLog' extension for examples. -- myLogHook = return () ------------------------------------------------------------------------ -- Startup hook -- Perform an arbitrary action each time xmonad starts or is restarted -- with mod-q. Used by, e.g., XMonad.Layout.PerWorkspace to initialize -- per-workspace layout choices. -- -- By default, do nothing. myStartupHook = return () ------------------------------------------------------------------------ -- Now run xmonad with all the defaults we set up. -- Run xmonad with the settings you specify. No need to modify this. -- main = xmonad defaults -- A structure containing your configuration settings, overriding -- fields in the default config. Any you don't override, will -- use the defaults defined in xmonad/XMonad/Config.hs -- -- No need to modify this. -- defaults = def { -- simple stuff terminal = myTerminal, focusFollowsMouse = myFocusFollowsMouse, clickJustFocuses = myClickJustFocuses, borderWidth = myBorderWidth, modMask = myModMask, workspaces = myWorkspaces, normalBorderColor = myNormalBorderColor, focusedBorderColor = myFocusedBorderColor, -- key bindings keys = myKeys, mouseBindings = myMouseBindings, -- hooks, layouts -- layoutHook = myLayout, -- manageHook = myManageHook, layoutHook = avoidStruts $ layoutHook def, manageHook = manageHook def <+> manageDocks, handleEventHook = myEventHook, logHook = myLogHook, startupHook = myStartupHook } -- | Finally, a copy of the default bindings in simple textual tabular format. help :: String help = unlines ["The default modifier key is 'alt'. Default keybindings:", "", "-- launching and killing programs", "mod-Shift-Enter Launch xterminal", "mod-p Launch dmenu", "mod-Shift-p Launch gmrun", "mod-Shift-c Close/kill the focused window", "mod-Space Rotate through the available layout algorithms", "mod-Shift-Space Reset the layouts on the current workSpace to default", "mod-n Resize/refresh viewed windows to the correct size", "", "-- move focus up or down the window stack", "mod-Tab Move focus to the next window", "mod-Shift-Tab Move focus to the previous window", "mod-j Move focus to the next window", "mod-k Move focus to the previous window", "mod-m Move focus to the master window", "", "-- modifying the window order", "mod-Return Swap the focused window and the master window", "mod-Shift-j Swap the focused window with the next window", "mod-Shift-k Swap the focused window with the previous window", "", "-- resizing the master/slave ratio", "mod-h Shrink the master area", "mod-l Expand the master area", "", "-- floating layer support", "mod-t Push window back into tiling; unfloat and re-tile it", "", "-- increase or decrease number of windows in the master area", "mod-comma (mod-,) Increment the number of windows in the master area", "mod-period (mod-.) Deincrement the number of windows in the master area", "", "-- quit, or restart", "mod-Shift-q Quit xmonad", "mod-q Restart xmonad", "mod-[1..9] Switch to workSpace N", "", "-- Workspaces & screens", "mod-Shift-[1..9] Move client to workspace N", "mod-{w,e,r} Switch to physical/Xinerama screens 1, 2, or 3", "mod-Shift-{w,e,r} Move client to screen 1, 2, or 3", "", "-- Mouse bindings: default actions bound to mouse events", "mod-button1 Set the window to floating mode and move by dragging", "mod-button2 Raise the window to the top of the stack", "mod-button3 Set the window to floating mode and resize by dragging"]
FrostyX/dotfiles
.xmonad/xmonad.hs
gpl-2.0
12,456
7
12
3,111
1,549
975
574
132
1
{-# LANGUAGE OverloadedStrings #-} module Tests.Readers.Markdown (tests) where import Text.Pandoc.Definition import Test.Framework import Tests.Helpers import Tests.Arbitrary() import Text.Pandoc.Builder import qualified Data.Set as Set -- import Text.Pandoc.Shared ( normalize ) import Text.Pandoc markdown :: String -> Pandoc markdown = readMarkdown def markdownSmart :: String -> Pandoc markdownSmart = readMarkdown def { readerSmart = True } markdownCDL :: String -> Pandoc markdownCDL = readMarkdown def { readerExtensions = Set.insert Ext_compact_definition_lists $ readerExtensions def } markdownGH :: String -> Pandoc markdownGH = readMarkdown def { readerExtensions = githubMarkdownExtensions } infix 4 =: (=:) :: ToString c => String -> (String, c) -> Test (=:) = test markdown testBareLink :: (String, Inlines) -> Test testBareLink (inp, ils) = test (readMarkdown def{ readerExtensions = Set.fromList [Ext_autolink_bare_uris, Ext_raw_html] }) inp (inp, doc $ para ils) autolink :: String -> Inlines autolink s = link s "" (str s) bareLinkTests :: [(String, Inlines)] bareLinkTests = [ ("http://google.com is a search engine.", autolink "http://google.com" <> " is a search engine.") , ("<a href=\"http://foo.bar.baz\">http://foo.bar.baz</a>", rawInline "html" "<a href=\"http://foo.bar.baz\">" <> "http://foo.bar.baz" <> rawInline "html" "</a>") , ("Try this query: http://google.com?search=fish&time=hour.", "Try this query: " <> autolink "http://google.com?search=fish&time=hour" <> ".") , ("HTTPS://GOOGLE.COM,", autolink "HTTPS://GOOGLE.COM" <> ",") , ("http://el.wikipedia.org/wiki/Τεχνολογία,", autolink "http://el.wikipedia.org/wiki/Τεχνολογία" <> ",") , ("doi:10.1000/182,", autolink "doi:10.1000/182" <> ",") , ("git://github.com/foo/bar.git,", autolink "git://github.com/foo/bar.git" <> ",") , ("file:///Users/joe/joe.txt, and", autolink "file:///Users/joe/joe.txt" <> ", and") , ("mailto:[email protected].", autolink "mailto:[email protected]" <> ".") , ("Use http: this is not a link!", "Use http: this is not a link!") , ("(http://google.com).", "(" <> autolink "http://google.com" <> ").") , ("http://en.wikipedia.org/wiki/Sprite_(computer_graphics)", autolink "http://en.wikipedia.org/wiki/Sprite_(computer_graphics)") , ("http://en.wikipedia.org/wiki/Sprite_[computer_graphics]", autolink "http://en.wikipedia.org/wiki/Sprite_[computer_graphics]") , ("http://en.wikipedia.org/wiki/Sprite_{computer_graphics}", autolink "http://en.wikipedia.org/wiki/Sprite_{computer_graphics}") , ("http://example.com/Notification_Center-GitHub-20101108-140050.jpg", autolink "http://example.com/Notification_Center-GitHub-20101108-140050.jpg") , ("https://github.com/github/hubot/blob/master/scripts/cream.js#L20-20", autolink "https://github.com/github/hubot/blob/master/scripts/cream.js#L20-20") , ("http://www.rubyonrails.com", autolink "http://www.rubyonrails.com") , ("http://www.rubyonrails.com:80", autolink "http://www.rubyonrails.com:80") , ("http://www.rubyonrails.com/~minam", autolink "http://www.rubyonrails.com/~minam") , ("https://www.rubyonrails.com/~minam", autolink "https://www.rubyonrails.com/~minam") , ("http://www.rubyonrails.com/~minam/url%20with%20spaces", autolink "http://www.rubyonrails.com/~minam/url%20with%20spaces") , ("http://www.rubyonrails.com/foo.cgi?something=here", autolink "http://www.rubyonrails.com/foo.cgi?something=here") , ("http://www.rubyonrails.com/foo.cgi?something=here&and=here", autolink "http://www.rubyonrails.com/foo.cgi?something=here&and=here") , ("http://www.rubyonrails.com/contact;new", autolink "http://www.rubyonrails.com/contact;new") , ("http://www.rubyonrails.com/contact;new%20with%20spaces", autolink "http://www.rubyonrails.com/contact;new%20with%20spaces") , ("http://www.rubyonrails.com/contact;new?with=query&string=params", autolink "http://www.rubyonrails.com/contact;new?with=query&string=params") , ("http://www.rubyonrails.com/~minam/contact;new?with=query&string=params", autolink "http://www.rubyonrails.com/~minam/contact;new?with=query&string=params") , ("http://en.wikipedia.org/wiki/Wikipedia:Today%27s_featured_picture_%28animation%29/January_20%2C_2007", autolink "http://en.wikipedia.org/wiki/Wikipedia:Today%27s_featured_picture_%28animation%29/January_20%2C_2007") , ("http://www.mail-archive.com/[email protected]/", autolink "http://www.mail-archive.com/[email protected]/") , ("http://www.amazon.com/Testing-Equal-Sign-In-Path/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1198861734&sr=8-1", autolink "http://www.amazon.com/Testing-Equal-Sign-In-Path/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1198861734&sr=8-1") , ("http://en.wikipedia.org/wiki/Texas_hold%27em", autolink "http://en.wikipedia.org/wiki/Texas_hold%27em") , ("https://www.google.com/doku.php?id=gps:resource:scs:start", autolink "https://www.google.com/doku.php?id=gps:resource:scs:start") , ("http://www.rubyonrails.com", autolink "http://www.rubyonrails.com") , ("http://manuals.ruby-on-rails.com/read/chapter.need_a-period/103#page281", autolink "http://manuals.ruby-on-rails.com/read/chapter.need_a-period/103#page281") , ("http://foo.example.com/controller/action?parm=value&p2=v2#anchor123", autolink "http://foo.example.com/controller/action?parm=value&p2=v2#anchor123") , ("http://foo.example.com:3000/controller/action", autolink "http://foo.example.com:3000/controller/action") , ("http://foo.example.com:3000/controller/action+pack", autolink "http://foo.example.com:3000/controller/action+pack") , ("http://business.timesonline.co.uk/article/0,,9065-2473189,00.html", autolink "http://business.timesonline.co.uk/article/0,,9065-2473189,00.html") , ("http://www.mail-archive.com/[email protected]/", autolink "http://www.mail-archive.com/[email protected]/") ] {- p_markdown_round_trip :: Block -> Bool p_markdown_round_trip b = matches d' d'' where d' = normalize $ Pandoc (Meta [] [] []) [b] d'' = normalize $ readMarkdown def { readerSmart = True } $ writeMarkdown def d' matches (Pandoc _ [Plain []]) (Pandoc _ []) = True matches (Pandoc _ [Para []]) (Pandoc _ []) = True matches (Pandoc _ [Plain xs]) (Pandoc _ [Para xs']) = xs == xs' matches x y = x == y -} tests :: [Test] tests = [ testGroup "inline code" [ "with attribute" =: "`document.write(\"Hello\");`{.javascript}" =?> para (codeWith ("",["javascript"],[]) "document.write(\"Hello\");") , "with attribute space" =: "`*` {.haskell .special x=\"7\"}" =?> para (codeWith ("",["haskell","special"],[("x","7")]) "*") , test (readMarkdown def{ readerExtensions = Set.insert Ext_scholarly_markdown $ readerExtensions def }) "double-backtick is inline math" $ "what part of ``\\mathbf{x_s}_\\frac{\\omega}{x \\delta}`` don't you understand? Also there's ``(V * \\rho)`` and ``y = Ax`` as well" =?> para ( "what part of " <> math "\\mathbf{x_s}_\\frac{\\omega}{x \\delta}" <> " don't you understand? Also there's " <> math "(V * \\rho)" <> " and " <> math "y = Ax" <> " as well") , test (readMarkdown def{ readerExtensions = Set.insert Ext_scholarly_markdown $ readerExtensions def }) "double-backtick is inline math except followed by whitespace" $ "what part of `` \\mathbf{x_s}_\\frac{\\omega}{x \\delta} `` don't you understand?" =?> para ( "what part of " <> codeWith ([],[],[]) "\\mathbf{x_s}_\\frac{\\omega}{x \\delta}" <> " don't you understand?" ) , test (readMarkdown def{ readerExtensions = Set.insert Ext_scholarly_markdown $ readerExtensions def }) "long backticks with Ext_tex_math_double_backtick enabled" $ "what part of ````\\mathbf{x_s}_\\frac{\\omega}{x \\delta} ```` don't you understand?" =?> para ( "what part of " <> codeWith ([],[],[]) "\\mathbf{x_s}_\\frac{\\omega}{x \\delta}" <> " don't you understand?" ) ] , testGroup "emph and strong" [ "two strongs in emph" =: "***a**b **c**d*" =?> para (emph (strong (str "a") <> str "b" <> space <> strong (str "c") <> str "d")) , "emph and strong emph alternating" =: "*xxx* ***xxx*** xxx\n*xxx* ***xxx*** xxx" =?> para (emph "xxx" <> space <> strong (emph "xxx") <> space <> "xxx" <> space <> emph "xxx" <> space <> strong (emph "xxx") <> space <> "xxx") , "emph with spaced strong" =: "*x **xx** x*" =?> para (emph ("x" <> space <> strong "xx" <> space <> "x")) , "intraword underscore with opening underscore (#1121)" =: "_foot_ball_" =?> para (emph (text "foot_ball")) ] , testGroup "raw LaTeX" [ "in URL" =: "\\begin\n" =?> para (text "\\begin") ] , testGroup "raw HTML" [ "nesting (issue #1330)" =: "<del>test</del>" =?> rawBlock "html" "<del>" <> plain (str "test") <> rawBlock "html" "</del>" ] , "unbalanced brackets" =: "[[[[[[[[[[[[[[[hi" =?> para (text "[[[[[[[[[[[[[[[hi") , testGroup "backslash escapes" [ "in URL" =: "[hi](/there\\))" =?> para (link "/there)" "" "hi") , "in title" =: "[hi](/there \"a\\\"a\")" =?> para (link "/there" "a\"a" "hi") , "in reference link title" =: "[hi]\n\n[hi]: /there (a\\)a)" =?> para (link "/there" "a)a" "hi") , "in reference link URL" =: "[hi]\n\n[hi]: /there\\.0" =?> para (link "/there.0" "" "hi") ] , testGroup "bare URIs" (map testBareLink bareLinkTests) , testGroup "autolinks" [ "with unicode dash following" =: "<http://foo.bar>\8212" =?> para (autolink "http://foo.bar" <> str "\8212") ] , testGroup "Headers" [ "blank line before header" =: "\n# Header\n" =?> headerWith ("header",[],[]) 1 "Header" ] , testGroup "smart punctuation" [ test markdownSmart "quote before ellipses" ("'...hi'" =?> para (singleQuoted "…hi")) , test markdownSmart "apostrophe before emph" ("D'oh! A l'*aide*!" =?> para ("D’oh! A l’" <> emph "aide" <> "!")) , test markdownSmart "apostrophe in French" ("À l'arrivée de la guerre, le thème de l'«impossibilité du socialisme»" =?> para "À l’arrivée de la guerre, le thème de l’«impossibilité du socialisme»") ] , testGroup "footnotes" [ "indent followed by newline and flush-left text" =: "[^1]\n\n[^1]: my note\n\n \nnot in note\n" =?> para (note (para "my note")) <> para "not in note" , "indent followed by newline and indented text" =: "[^1]\n\n[^1]: my note\n \n in note\n" =?> para (note (para "my note" <> para "in note")) , "recursive note" =: "[^1]\n\n[^1]: See [^1]\n" =?> para (note (para "See [^1]")) ] , testGroup "lhs" [ test (readMarkdown def{ readerExtensions = Set.insert Ext_literate_haskell $ readerExtensions def }) "inverse bird tracks and html" $ "> a\n\n< b\n\n<div>\n" =?> codeBlockWith ("",["sourceCode","literate","haskell"],[]) "a" <> codeBlockWith ("",["sourceCode","haskell"],[]) "b" <> rawBlock "html" "<div>\n\n" ] -- the round-trip properties frequently fail -- , testGroup "round trip" -- [ property "p_markdown_round_trip" p_markdown_round_trip -- ] , testGroup "definition lists" [ "no blank space" =: "foo1\n : bar\n\nfoo2\n : bar2\n : bar3\n" =?> definitionList [ (text "foo1", [plain (text "bar")]) , (text "foo2", [plain (text "bar2"), plain (text "bar3")]) ] , "blank space before first def" =: "foo1\n\n : bar\n\nfoo2\n\n : bar2\n : bar3\n" =?> definitionList [ (text "foo1", [para (text "bar")]) , (text "foo2", [para (text "bar2"), plain (text "bar3")]) ] , "blank space before second def" =: "foo1\n : bar\n\nfoo2\n : bar2\n\n : bar3\n" =?> definitionList [ (text "foo1", [plain (text "bar")]) , (text "foo2", [plain (text "bar2"), para (text "bar3")]) ] , "laziness" =: "foo1\n : bar\nbaz\n : bar2\n" =?> definitionList [ (text "foo1", [plain (text "bar baz"), plain (text "bar2")]) ] , "no blank space before first of two paragraphs" =: "foo1\n : bar\n\n baz\n" =?> definitionList [ (text "foo1", [para (text "bar") <> para (text "baz")]) ] ] , testGroup "+compact_definition_lists" [ test markdownCDL "basic compact list" $ "foo1\n: bar\n baz\nfoo2\n: bar2\n" =?> definitionList [ (text "foo1", [plain (text "bar baz")]) , (text "foo2", [plain (text "bar2")]) ] ] , testGroup "lists" [ "issue #1154" =: " - <div>\n first div breaks\n </div>\n\n <button>if this button exists</button>\n\n <div>\n with this div too.\n </div>\n" =?> bulletList [divWith nullAttr (para $ text "first div breaks") <> rawBlock "html" "<button>" <> plain (text "if this button exists") <> rawBlock "html" "</button>" <> divWith nullAttr (para $ text "with this div too.")] , test markdownGH "issue #1636" $ unlines [ "* a" , "* b" , "* c" , " * d" ] =?> bulletList [ plain "a" , plain "b" , plain "c" <> bulletList [plain "d"] ] ] ]
timtylin/scholdoc
tests/Tests/Readers/Markdown.hs
gpl-2.0
15,297
0
22
4,345
2,559
1,360
1,199
258
1
{-# LANGUAGE RankNTypes, QuasiQuotes, FlexibleContexts, DeriveDataTypeable, CPP, JavaScriptFFI #-} module Lib (genericSendJSON, sendJSON, onEnter, onKey, doOnce, dispatchCustom, clearInput, getListOfElementsByClass, getListOfElementsByTag, getCarnapDataMap, tryParse, treeToElement, genericTreeToUl, treeToUl, genericListToUl, listToUl, formToTree, leaves, adjustFirstMatching, decodeHtml, decodeJSON,toJSONString, cleanString, syncScroll, reloadPage, initElements, errorPopup, genInOutElts, getInOutElts,generateExerciseElts, withLabel, formAndLabel,seqAndLabel, folSeqAndLabel, folFormAndLabel, message, IOGoal(..), updateWithValue, submissionSource, assignmentKey, initialize, mutate, initializeCallback, initCallbackObj, toCleanVal, popUpWith, spinnerSVG, doneButton, questionButton, exclaimButton, expandButton, createSubmitButton, createButtonWrapper, maybeNodeListToList, trySubmit, inOpts, rewriteWith, setStatus, ButtonStatus(..), keyString) where import Data.Aeson import Data.Maybe (catMaybes) import qualified Data.ByteString.Lazy as BSL import Data.Text (pack) import Data.Text.Encoding import Data.Tree as T import Data.IORef (IORef, readIORef) import qualified Data.Map as M import Text.Read (readMaybe) import Text.Parsec import Text.StringLike import Text.HTML.TagSoup as TS import Text.Hamlet import Text.Blaze.Html.Renderer.String import Control.Lens import Control.Lens.Plated (children) import Control.Monad.Fix import Control.Monad.State import Control.Monad.Trans.Maybe (runMaybeT, MaybeT(..)) --The following three imports come from ghcjs-base, and break ghc-mod #ifdef __GHCJS__ import GHCJS.Types import GHCJS.Foreign import GHCJS.Foreign.Callback import GHCJS.Marshal #endif --the import below required to make ghc-mod work properly. GHCJS compiles --using the generated javascript FFI versions of 2.4.0, but those are --slightly different from the webkit versions of 2.4.0. In particular, --Element doesn't export IsElement, although Types does in the webkit --version---but it's the other way around in the FFI version. This appears --to be cleaner in 3.0, but there's no documentation for that at all, yet. import GHCJS.DOM import GHCJS.DOM.Types import GHCJS.DOM.Element import GHCJS.DOM.HTMLInputElement import qualified GHCJS.DOM.HTMLTextAreaElement as TA (setValue,getValue) import GHCJS.DOM.Document (createElement, getBody, createEvent) import GHCJS.DOM.Node import qualified GHCJS.DOM.HTMLCollection as HC import GHCJS.DOM.NodeList import qualified GHCJS.DOM.NamedNodeMap as NM import GHCJS.DOM.Event as EV import GHCJS.DOM.KeyboardEvent import GHCJS.DOM.EventM import GHCJS.DOM.EventTarget import GHCJS.DOM.EventTargetClosures (EventName(..)) import Carnap.GHCJS.SharedTypes import Carnap.GHCJS.SharedFunctions import Carnap.Calculi.NaturalDeduction.Syntax (NaturalDeductionCalc(..)) import Carnap.Languages.PurePropositional.Syntax (PureForm) import Carnap.Languages.PurePropositional.Logic import Carnap.Languages.PureFirstOrder.Parser (folFormulaParser) import Carnap.Languages.PureFirstOrder.Logic import Carnap.Languages.PurePropositional.Parser (purePropFormulaParser, standardLetters) -------------------------------------------------------- --1. Utility Functions -------------------------------------------------------- --------------------------- -- 1.0 Simple Patterns -- --------------------------- -------------------------------------------------------- --1.1 Events -------------------------------------------------------- onKey :: [String] -> EventM e KeyboardEvent () -> EventM e KeyboardEvent () onKey keylist action = do kbe <- event id <- getKeyIdentifier kbe -- XXX: keyIdentifier is deprecated and doesn't work in -- firefox; hence the use of `keyString`. But `key` -- doesn't work in some older browsers, so we keep -- this line around. id' <- liftIO $ keyString kbe if id `elem` keylist || id' `elem` keylist then EV.preventDefault kbe >> action else return () onEnter :: EventM e KeyboardEvent () -> EventM e KeyboardEvent () onEnter = onKey ["Enter"] doOnce :: (IsEventTarget t, IsEvent e) => t -> EventName t e -> Bool -> EventM t e r -> IO () doOnce target event bubble handler = do listener <- mfix $ \rec -> newListener $ do handler liftIO $ removeListener target event rec bubble addListener target event listener bubble dispatchCustom :: Document -> Element -> String -> IO () dispatchCustom w e s = do Just custom <- createEvent w "Event" initEvent custom s True True dispatchEvent e (Just custom) return () -------------------------------------------------------- --1.1.2 Common responsive behavior -------------------------------------------------------- syncScroll e1 e2 = do cup1 <- catchup e1 e2 cup2 <- catchup e2 e1 addListener e1 scroll cup1 False addListener e2 scroll cup2 False where catchup e1 e2 = newListener $ liftIO $ do st <- getScrollTop e1 setScrollTop e2 st -------------------------------------------------------- --1.2 DOM Manipulation -------------------------------------------------------- -------------------------------------------------------- --1.2.1 DOM Data -------------------------------------------------------- -- data structures for DOM elements data IOGoal = IOGoal { inputArea :: Element , outputArea :: Element , goalArea :: Element , content :: String , exerciseOptions :: M.Map String String } clearInput :: (MonadIO m) => HTMLInputElement -> m () clearInput i = setValue i (Just "") maybeNodeListToList mnl = case mnl of Nothing -> return [] Just nl -> do l <- getLength nl if l > 0 then mapM ((fmap . fmap) castToElement . item nl) [0 .. l-1] else return [] maybeHtmlCollectionToList mhc = case mhc of Nothing -> return [] Just hc -> do l <- HC.getLength hc if l > 0 then mapM ((fmap . fmap) castToElement . HC.item hc) [0 .. l-1] else return [] -- XXX: one might also want to include a "mutable lens" or "mutable traversal" --kind of thing: http://stackoverflow.com/questions/18794745/can-i-make-a-lens-with-a-monad-constraint getListOfElementsByClass :: IsElement self => self -> String -> IO [Maybe Element] getListOfElementsByClass elt c = getElementsByClassName elt c >>= maybeNodeListToList getListOfElementsByTag :: IsElement self => self -> String -> IO [Maybe Element] getListOfElementsByTag elt c = getElementsByTagName elt c >>= maybeNodeListToList getListOfElementsByCarnapType :: IsElement self => self -> String -> IO [Maybe Element] getListOfElementsByCarnapType elt s = querySelectorAll elt ("[data-carnap-type=" ++ s ++ "]") >>= maybeNodeListToList tryParse p s = unPack $ parse p "" s where unPack (Right s) = show s unPack (Left e) = show e treeToElement :: (a -> IO Element) -> (Element -> [Element] -> IO ()) -> Tree a -> IO Element treeToElement f g (T.Node n []) = f n treeToElement f g (T.Node n ts) = do r <- f n elts <- mapM (treeToElement f g) ts g r elts return r genericTreeToUl :: (a -> String) -> Document -> Tree (a, String) -> IO Element genericTreeToUl sf w t = treeToElement itemize listify t where itemize (x,c) = do s@(Just s') <- createElement w (Just "li") setInnerHTML s' (Just $ sf x) setAttribute s' "class" c return s' listify x xs = do o@(Just o') <- createElement w (Just "ul") mapM_ (appendChild o' . Just) xs appendChild x o return () treeToUl :: Show a => Document -> Tree (a, String) -> IO Element treeToUl = genericTreeToUl show genericListToUl :: (Element -> a -> IO ()) -> Document -> [a] -> IO Element genericListToUl f doc l = do elts <- mapM wrapIt l (Just ul) <- createElement doc (Just "ul") mapM_ (appendChild ul) elts return ul where wrapIt e = do (Just li) <- createElement doc (Just "li") f li e return (Just li) listToUl :: Show a => Document -> [a] -> IO Element listToUl = genericListToUl (\e a -> setInnerHTML e (Just $ show a)) {- This function supports a pattern where we gather a list of elements that have a designated input (usually a text area or something) and output children, and then attach events to them according to the classes of their parents. -} getInOutElts :: IsElement self => String -> self -> IO [Maybe (Element, Element, [String])] getInOutElts cls b = do els <- getListOfElementsByClass b cls mapM extract els where extract Nothing = return Nothing extract (Just el) = do cn <- getClassName el runMaybeT $ do i <- MaybeT $ getFirstElementChild el o <- MaybeT $ getNextElementSibling i return (i ,o ,words cn) genInOutElts :: IsElement self => Document -> String -> String -> String -> self -> IO [Maybe (Element, Element, M.Map String String)] genInOutElts w input output ty target = do els <- getListOfElementsByCarnapType target ty mapM initialize els where initialize Nothing = return Nothing initialize (Just el) = do Just content <- getTextContent el :: IO (Maybe String) [Just o, Just i] <- mapM (createElement w . Just) [output,input] setAttribute i "class" "input" setAttribute o "class" "output" setInnerHTML el (Just "") opts <- getCarnapDataMap el mapM_ (appendChild el . Just) [i,o] return $ Just (i, o, M.insert "content" content opts ) generateExerciseElts :: IsElement self => Document -> String -> self -> IO [Maybe IOGoal] generateExerciseElts w ty target = do els <- getListOfElementsByCarnapType target ty mapM initialize els where initialize Nothing = return Nothing initialize (Just el) = do Just content <- getTextContent el setInnerHTML el (Just "") [Just g, Just o, Just i] <- mapM (createElement w . Just) ["div","div","textarea"] setAttribute g "class" "goal" setAttribute i "class" "input" setAttribute o "class" "output" opts <- getCarnapDataMap el mapM_ (appendChild el . Just) [g,i,o] return $ Just (IOGoal i o g content opts) updateWithValue :: IsEvent ev => (String -> IO ()) -> EventM HTMLTextAreaElement ev () updateWithValue f = do (Just t) <- target :: IsEvent ev' => EventM HTMLTextAreaElement ev' (Maybe HTMLTextAreaElement) mv <- TA.getValue t case mv of Nothing -> return () Just v -> liftIO $ f v getCarnapDataMap :: Element -> IO (M.Map String String) getCarnapDataMap elt = do (Just nnmap) <- getAttributes elt len <- NM.getLength nnmap if len > 0 then do mnodes <- mapM (NM.item nnmap) [0 .. len -1] mnamevals <- mapM toNameVal mnodes return $ M.fromList . catMaybes $ mnamevals else return mempty where toNameVal (Just node) = do mn <- getNodeName node mv <- getNodeValue node case (mn,mv) of (Just n, Just v) | "data-carnap-" == take 12 n -> return $ Just (Prelude.drop 12 n,v) _ -> return Nothing toNameVal _ = return Nothing popUpWith :: Element -> Document -> Element -> String -> String -> Maybe String -> IO () popUpWith fd w elt label msg details = do setInnerHTML elt (Just label) (Just outerpopper) <- createElement w (Just "div") (Just innerpopper) <- createElement w (Just "div") setAttribute innerpopper "class" "popper" setAttribute outerpopper "class" "popperWrapper" setInnerHTML innerpopper (Just msg) appendChild outerpopper (Just innerpopper) case details of Just deets -> do (Just detailpopper) <- createElement w (Just "div") setAttribute detailpopper "class" "details" setInnerHTML detailpopper (Just deets) appendChild innerpopper (Just detailpopper) return () Nothing -> return () (Just p) <- getParentNode fd (Just gp) <- getParentNode p appender <- newListener $ appendPopper outerpopper gp remover <- newListener $ removePopper outerpopper gp addListener elt mouseOver appender False addListener elt mouseOut remover False where appendPopper pop targ = do liftIO $ appendChild targ (Just pop) liftIO $ makePopper elt pop removePopper pop targ = do liftIO $ removeChild targ (Just pop) return () -------------------------------------------------------- --1.3 Encodings -------------------------------------------------------- toJSONString :: ToJSON a => a -> JSString toJSONString = toJSString . decodeUtf8 . BSL.toStrict . encode decodeHtml :: (StringLike s, Show s) => s -> s decodeHtml = TS.fromTagText . head . parseTags decodeJSON :: String -> Maybe Value decodeJSON = decode . BSL.fromStrict . encodeUtf8 . pack --reencodes unicode characters in strings that have been mangled by "show" cleanString :: String -> String cleanString = concat . map cleanChunk . chunks where chunks s = case break (== '\"') s of (l,[]) -> l:[] (l,_:s') -> l:chunks s' cleanChunk c = case (readMaybe $ "\"" ++ c ++ "\"") :: Maybe String of Just s -> s Nothing -> c readMaybe s = case reads s of [(x, "")] -> Just x _ -> Nothing -------------------------------------------------------- --1.4 Optics -------------------------------------------------------- leaves :: Traversal' (Tree a) (Tree a) leaves f (T.Node x []) = f (T.Node x []) leaves f (T.Node x xs) = T.Node <$> pure x <*> traverse (leaves f) xs adjustFirstMatching :: Traversal' a b -> (b -> Bool) -> (b -> b) -> a -> a adjustFirstMatching t pred f x = evalState (traverseOf t adj x) True where adj y = do b <- get if b && pred y then put False >> return (f y) else return y -------------------------------------------------------- --1.5 Carnap-Specific -------------------------------------------------------- formToTree :: Plated a => a -> Tree a formToTree f = T.Node f (map formToTree (children f)) -------------------------------------------------------- --1.6 Boilerplate -------------------------------------------------------- data ButtonStatus = Edited | Submitted initElements :: (Document -> HTMLElement -> IO [a]) -> (Document -> a -> IO b) -> IO () initElements getter setter = runWebGUI $ \w -> do (Just dom) <- webViewGetDomDocument w (Just b) <- getBody dom elts <- getter dom b case elts of [] -> return () _ -> mapM_ (setter dom) elts createSubmitButton :: Document -> Element -> (String -> EventM e MouseEvent ()) -> M.Map String String -> IO (ButtonStatus -> IO ()) createSubmitButton w bw submit opts = case M.lookup "submission" opts of Just s | take 7 s == "saveAs:" -> do let l = Prelude.drop 7 s bt <- doneButton w "Submit" appendChild bw (Just bt) submitter <- newListener $ submit l addListener bt click submitter False return (setStatus w bt) _ -> return (const $ return ()) setStatus w b Edited = setAttribute b "data-carnap-exercise-status" "edited" setStatus w b Submitted = do dispatchCustom w b "problem-submission" setAttribute b "data-carnap-exercise-status" "submitted" loginCheck callback serverResponse | serverResponse == "submitted!" = callback | otherwise = alert serverResponse errorPopup msg = alert ("Something has gone wrong. Here's the error: " ++ msg) svgButtonWith :: String -> Document -> String -> IO Element svgButtonWith svg w thelabel = do [Just bt, Just bl, Just cm] <- mapM (createElement w . Just) ["button", "span","span"] setInnerHTML bl (Just thelabel) setInnerHTML cm (Just svg) appendChild bt (Just bl) appendChild bt (Just cm) return bt doneButton = svgButtonWith checkSVG questionButton = svgButtonWith questionSVG exclaimButton = svgButtonWith exclaimSVG expandButton = svgButtonWith expandSVG createButtonWrapper w o = do (Just bw) <- createElement w (Just "div") setAttribute bw "class" "buttonWrapper" Just par <- getParentNode o appendChild par (Just bw) return bw -------------------------------------------------------- --1.7 Parsing -------------------------------------------------------- formAndLabel :: Monad m => ParsecT String u m (String, PureForm) formAndLabel = withLabel (purePropFormulaParser standardLetters <* eof) seqAndLabel = withLabel (ndParseSeq montagueSCCalc) folSeqAndLabel = withLabel (ndParseSeq folCalc) folFormAndLabel = withLabel folFormulaParser withLabel :: Monad m => ParsecT String u m b -> ParsecT String u m (String, b) withLabel parser = do label <- many (digit <|> char '.') spaces s <- parser return (label,s) trySubmit w problemType opts ident problemData correct = do msource <- liftIO submissionSource key <- liftIO assignmentKey case msource of Nothing -> message "Not able to identify problem source. Perhaps this document has not been assigned?" Just source -> do Just t <- eventCurrentTarget liftIO $ sendJSON (Submit problemType ident problemData source correct (M.lookup "points" opts >>= readMaybe) key) (loginCheck $ (alert $ "Submitted Exercise " ++ ident) >> setStatus w (castToElement t) Submitted) errorPopup ------------------ --1.8 SVG Data -- ------------------ spinnerSVG = renderHtml [shamlet| <svg version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 40 40" enable-background="new 0 0 40 40" xml:space="preserve"> <path opacity="0.2" fill="#000" d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946 s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634 c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z"/> <path fill="#000" d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0 C22.32,8.481,24.301,9.057,26.013,10.047z"> <animateTransform attributeType="xml" attributeName="transform" type="rotate" from="0 20 20" to="360 20 20" dur="0.5s" repeatCount="indefinite"/>|] checkSVG = renderHtml [shamlet| <svg version="1.1" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"> <g transform="translate(-46.113 -84.018)"> <path d="m106.11 84.018a60 60 0 0 0-60 60 60 60 0 0 0 60 60 60 60 0 0 0 60-60 60 60 0 0 0-60-60zm0 12.095a47.905 47.905 0 0 1 47.905 47.905 47.905 47.905 0 0 1-47.905 47.905 47.905 47.905 0 0 1-47.905-47.905 47.905 47.905 0 0 1 47.905-47.905z"/> <path.filler d="m74.95 141.17 23.653 28.743 38.739-45.778" style="fill:none;stroke-width:15;"/>|] questionSVG = renderHtml [shamlet| <svg version="1.1" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"> <defs>style="fill:none;stroke-width:15;"/&gt;</defs> <path d="m59.997 0a60 60 0 0 0-60 60 60 60 0 0 0 60 60 60 60 0 0 0 60-60 60 60 0 0 0-60-60zm0 12.095a47.905 47.905 0 0 1 47.905 47.905 47.905 47.905 0 0 1-47.905 47.905 47.905 47.905 0 0 1-47.905-47.905 47.905 47.905 0 0 1 47.905-47.905z"/> <ellipse cx="58.22" cy="92.034" rx="5.339" ry="5.0847" style="fill:none"/> <ellipse.filler cx="59.997" cy="88.865" rx="8.8983" ry="8.1355" style="stroke-width:1.1744"/> <rect.filler x="51.862" y="63.401" width="16.271" height="14.746" ry="0" style="stroke-width:1.0664"/> <path.filler d="m58.942 20.517c-13.969 0.18878-25.496 10.964-26.601 24.864h12.328c1.0506-7.2042 7.1885-12.579 14.482-12.683 8.1481-0.10463 14.858 6.3652 15.034 14.497 0.17565 8.1314-6.2477 14.884-14.393 15.131-2.7817 0.0785-5.1501 0.07525-7.9299 0.07525v11.066c2.6798 0.76758 5.4622 1.1171 8.2489 1.0361 14.841-0.45005 26.544-12.755 26.224-27.571-0.32052-14.817-12.547-26.606-27.394-26.415z" style="stroke-width:.98886"/>|] expandSVG = renderHtml [shamlet| <svg version="1.1" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"> <defs>style="fill:none;stroke-width:15;"/&gt;</defs> <path d="m0 0v120h120v-120zm14 14h92v92h-92z"/> <g transform="translate(140.64 -.21112)"> <rect.filler x="-120.64" y="70.211" width="10" height="30"/> <rect.filler transform="rotate(90)" x="90.211" y="90.642" width="10" height="30"/> <rect.filler transform="rotate(45)" x="-19.447" y="114.1" width="10" height="30"/> <g transform="rotate(90 60.142 59.858)"> <g transform="translate(140.64 -.21112)"> <rect.filler x="-120.64" y="70.211" width="10" height="30"/> <rect.filler transform="rotate(90)" x="90.211" y="90.642" width="10" height="30"/> <rect.filler transform="rotate(45)" x="-19.447" y="114.1" width="10" height="30"/> <g transform="rotate(180 60.142 59.858)"> <g transform="translate(140.64 -.21112)"> <rect.filler x="-120.64" y="70.211" width="10" height="30"/> <rect.filler transform="rotate(90)" x="90.211" y="90.642" width="10" height="30"/> <rect.filler transform="rotate(45)" x="-19.447" y="114.1" width="10" height="30"/> <g transform="rotate(-90 60.142 59.858)"> <g transform="translate(140.64 -.21112)"> <rect.filler x="-120.64" y="70.211" width="10" height="30"/> <rect.filler transform="rotate(90)" x="90.211" y="90.642" width="10" height="30"/> <rect.filler transform="rotate(45)" x="-19.447" y="114.1" width="10" height="30"/>|] exclaimSVG = renderHtml [shamlet| <svg version="1.1" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"> <defs>style="fill:none;stroke-width:15;"/&gt;</defs> <path d="m59.997 0a60 60 0 0 0-60 60 60 60 0 0 0 60 60 60 60 0 0 0 60-60 60 60 0 0 0-60-60zm0 12.095a47.905 47.905 0 0 1 47.905 47.905 47.905 47.905 0 0 1-47.905 47.905 47.905 47.905 0 0 1-47.905-47.905 47.905 47.905 0 0 1 47.905-47.905z"/> <ellipse cx="58.22" cy="92.034" rx="5.339" ry="5.0847" style="fill:none"/> <ellipse.filler cx="59.997" cy="88.865" rx="8.8983" ry="8.1355" style="stroke-width:1.1744"/> <rect.filler x="51.862" y="25.932" width="16.271" height="47.797" ry="0" style="stroke-width:1.9199"/>|] -------------------------------------------------------- --2. FFI Wrappers -------------------------------------------------------- #ifdef __GHCJS__ sendJSON :: ToJSON a => a -> (String -> IO ()) -> (String -> IO ()) -> IO () sendJSON x succ fail = do cb1 <- asyncCallback1 (cb succ) cb2 <- asyncCallback3 (cb3 fail) jsonCommand (toJSONString x) cb1 cb2 where cb f x = do (Just s) <- fromJSVal x f s cb3 f _ x _ = do (Just s) <- fromJSVal x f s genericSendJSON :: ToJSON a => a -> (Value -> IO ()) -> (Value -> IO ()) -> IO () genericSendJSON x succ fail = do cb1 <- asyncCallback1 (cb succ) cb2 <- asyncCallback3 (cb3 fail) jsonCommand (toJSONString x) cb1 cb2 where cb f x = do (Just v) <- fromJSVal x f v cb3 f _ x _ = do (Just v) <- fromJSVal x f v keyString :: KeyboardEvent -> IO String keyString e = key e >>= return . fromJSString alert :: String -> IO () alert = alert' . toJSString foreign import javascript unsafe "JSON.parse(JSON.stringify($1))" sanatizeJSVal :: JSVal -> IO JSVal foreign import javascript unsafe "try {jsonCommand($1,$2,$3)} catch(e) {console.log(e)};" jsonCommand :: JSString -> Callback (JSVal -> IO()) -> Callback (JSVal -> JSVal -> JSVal -> IO()) -> IO () foreign import javascript unsafe "$1.key" key :: KeyboardEvent -> IO JSString foreign import javascript unsafe "location.reload()" reloadPage :: IO () foreign import javascript unsafe "alert($1)" alert' :: JSString -> IO () foreign import javascript unsafe "window.location.href()" currentUrl :: IO JSString foreign import javascript unsafe "(function(){try {var v=submission_source;} catch (e) {var v=\"no submission source found\";}; return v})()" submissionQueryJS :: IO JSString foreign import javascript unsafe "(function(){try {var v=assignment_key;} catch (e) {var v=\"\";}; return v})()" assignmentKeyJS :: IO JSString foreign import javascript unsafe "try {new Popper($1,$2,{placement:\"right\"});} catch (e) {$2.className=\"manualPopper\"};" makePopper :: Element -> Element -> IO () foreign import javascript unsafe "window.Carnap = {};" initCallbackObj :: IO () --"window.VAR" is apparently best practice for declaring global vars foreign import javascript unsafe "Carnap[$1]=$2;" initializeCallbackJS :: JSString-> Callback (payload -> succ -> IO ()) -> IO () --TODO: unify with other callback code in SequentCheck foreign import javascript unsafe "$1($2);" simpleCall :: JSVal -> JSVal -> IO () submissionSource = do qr <- submissionQueryJS case fromJSString qr of "book" -> return $ Just Book "no submission source found" -> return $ Nothing s | take 11 s == "assignment:" -> return $ Just (Assignment $ Prelude.drop 11 s) _ -> do errorPopup "Bad submission source"; return Nothing message s = liftIO (alert s) assignmentKey :: IO String assignmentKey = do k <- assignmentKeyJS return $ fromJSString k initialize :: EventName t Event initialize = EventName $ toJSString "initialize" mutate :: EventName t Event mutate = EventName $ toJSString "mutate" toCleanVal :: JSVal -> IO (Maybe Value) toCleanVal x = sanatizeJSVal x >>= fromJSVal initializeCallback :: String -> (Value -> IO Value) -> IO () initializeCallback s f = do theCB <- asyncCallback2 (cb f) initializeCallbackJS (toJSString s) theCB where cb f jsval onSuccess = do Just val <- toCleanVal jsval rslt <- f val rslt' <- toJSVal rslt simpleCall onSuccess rslt' #else initialize :: EventName t Event initialize = EventName "initialize" mutate :: EventName t Event mutate = EventName "mutate" initializeCallback :: (Value -> IO Value) -> IO () initializeCallback = error "initializeCallback requires the GHCJS FFI" toCleanVal :: JSVal -> IO (Maybe Value) toCleanVal = error "toCleaVal requires the GHCJS FFI" initCallbackObj :: IO () initCallbackObj = error "initCallbackObj requires the GHCJS FFI" assignmentKey :: IO String assignmentKey = Prelude.error "assignmentKey requires the GHJS FFI" submissionSource :: IO (Maybe ProblemSource) submissionSource = Prelude.error "submissionSource requires the GHCJS FFI" sendJSON :: ToJSON a => a -> (String -> IO ()) -> (String -> IO ()) -> IO () sendJSON = Prelude.error "sendJSON requires the GHCJS FFI" genericSendJSON :: ToJSON a => a -> (Value -> IO ()) -> (Value -> IO ()) -> IO () genericSendJSON = Prelude.error "sendJSON requires the GHCJS FFI" keyString :: KeyboardEvent -> IO String keyString = Prelude.error "keyString requires the GHCJS FFI" alert :: String -> IO () alert = Prelude.error "alert requires the GHCJS FFI" makePopper :: Element -> Element -> IO () makePopper = Prelude.error "makePopper requires the GHCJS FFI" currentUrl = Prelude.error "currentUrl requires the GHCJS FFI" message s = liftIO (alert s) reloadPage :: IO () reloadPage = Prelude.error "reloadPage requires the GHCJS FFI" #endif
gleachkr/Carnap
Carnap-GHCJS/src/Lib.hs
gpl-3.0
31,296
25
19
9,266
6,483
3,232
3,251
350
4
module Amoeba.Middleware.Config.Extra where import Amoeba.Middleware.Config.Config import Control.Monad (liftM) filePathLoader path file = liftM (++ file) $ strOption path
graninas/The-Amoeba-World
src/Amoeba/Middleware/Config/Extra.hs
gpl-3.0
173
0
7
19
49
29
20
4
1
{-# LANGUAGE OverloadedStrings #-} module Ampersand.Prototype.PHP ( evaluateExpSQL , createTempDatabase , tempDbName ) where import Ampersand.Basics import Ampersand.ADL1 import Ampersand.FSpec import Ampersand.FSpec.SQL import Ampersand.Misc import Ampersand.Prototype.ProtoUtil import Ampersand.Prototype.TableSpec import Control.Exception import Data.List import qualified Data.Text as Text import qualified Data.Text.IO as Text import System.Directory import System.FilePath import System.Process createTablePHP :: TableSpec -> [Text.Text] createTablePHP tSpec = map (Text.pack . ("// "<>)) (tsCmnt tSpec) <> [-- Drop table if it already exists "if($columns = mysqli_query($DB_link, "<>queryAsPHP (showColumsSql tSpec)<>")){" , " mysqli_query($DB_link, "<>queryAsPHP (dropTableSql tSpec)<>");" , "}" ] <> [ "$sql="<>queryAsPHP (createTableSql False tSpec)<>";" , "mysqli_query($DB_link,$sql);" , "if($err=mysqli_error($DB_link)) {" , " $error=true; echo $err.'<br />';" , "}" , "" ] -- evaluate normalized exp in SQL evaluateExpSQL :: FSpec -> Text.Text -> Expression -> IO [(String,String)] evaluateExpSQL fSpec dbNm expr = -- verboseLn (getOpts fSpec) ("evaluateExpSQL fSpec "++showA expr) -- verboseLn (getOpts fSpec) (intercalate "\n" . showPrf showA . cfProof (getOpts fSpec)) expr -- verboseLn (getOpts fSpec) "End of proof" performQuery fSpec dbNm violationsQuery where violationsExpr = conjNF (getOpts fSpec) expr violationsQuery = prettySQLQuery 26 fSpec violationsExpr performQuery :: FSpec -> Text.Text -> SqlQuery -> IO [(String,String)] performQuery fSpec dbNm queryStr = do { queryResult <- (executePHPStr . showPHP) php ; if "Error" `isPrefixOf` queryResult -- not the most elegant way, but safe since a correct result will always be a list then do verboseLn opts{verboseP=True} (Text.unpack $ "\n******Problematic query:\n"<>queryAsSQL queryStr<>"\n******") fatal ("PHP/SQL problem: "<>queryResult) else case reads queryResult of [(pairs,"")] -> return pairs _ -> fatal ("Parse error on php result: \n"<>(unlines . map (" " ++) . lines $ queryResult)) } where opts = getOpts fSpec php :: [Text.Text] php = connectToMySqlServerPHP opts (Just dbNm) <> [ "$sql="<>queryAsPHP queryStr<>";" , "$result=mysqli_query($DB_link,$sql);" , "if(!$result)" , " die('Error : Connect to server failed'.($ernr=mysqli_errno($DB_link)).': '.mysqli_error($DB_link).'(Sql: $sql)');" , "$rows=Array();" , " while ($row = mysqli_fetch_array($result)) {" , " $rows[]=$row;" , " unset($row);" , " }" , "echo '[';" , "for ($i = 0; $i < count($rows); $i++) {" , " if ($i==0) echo ''; else echo ',';" , " echo '(\"'.addslashes($rows[$i]['src']).'\", \"'.addslashes($rows[$i]['tgt']).'\")';" , "}" , "echo ']';" ] -- call the command-line php with phpStr as input executePHPStr :: Text.Text -> IO String executePHPStr phpStr = do { tempdir <- catch getTemporaryDirectory (\e -> do let err = show (e :: IOException) hPutStr stderr ("Warning: Couldn't find temp directory. Using current directory : " <> err) return ".") ; (tempPhpFile, temph) <- openTempFile tempdir "tmpPhpQueryOfAmpersand.php" ; Text.hPutStr temph phpStr ; hClose temph ; results <- executePHP tempPhpFile -- ; removeFile tempPhpFile ; return (normalizeNewLines results) } normalizeNewLines :: String -> String normalizeNewLines = f . intercalate "\n" . lines where f [] = [] f ('\r':'\n':rest) = '\n':f rest f (c:cs) = c: f cs executePHP :: String -> IO String executePHP phpPath = do { let cp = (shell command) { cwd = Just (takeDirectory phpPath) } inputFile = phpPath outputFile = inputFile++"Result" command = "php "++show inputFile++" > "++show outputFile ; _ <- readCreateProcess cp "" ; result <- readFile outputFile ; removeFile outputFile ; return result } showPHP :: [Text.Text] -> Text.Text showPHP phpLines = Text.unlines $ ["<?php"]<>phpLines<>["?>"] tempDbName :: Options -> Text.Text tempDbName opts = "TempDB_"<>Text.pack (dbName opts) connectToMySqlServerPHP :: Options -> Maybe Text.Text-> [Text.Text] connectToMySqlServerPHP opts mDbName = [ "// Try to connect to the MySQL server" , "global $DB_host,$DB_user,$DB_pass;" , "$DB_host='"<>subst sqlHost <>"';" , "$DB_user='"<>subst sqlLogin<>"';" , "$DB_pass='"<>subst sqlPwd <>"';" , "" ]<> (case mDbName of Nothing -> [ "$DB_link = mysqli_connect($DB_host,$DB_user,$DB_pass);" , "// Check connection" , "if (mysqli_connect_errno()) {" , " die('Failed to connect to MySQL: ' . mysqli_connect_error());" , "}" , "" ] Just dbNm -> ["$DB_name='"<>dbNm<>"';"]<> connectToTheDatabasePHP ) where subst :: (Options -> String) -> Text.Text subst x = addSlashes . Text.pack . x $ opts connectToTheDatabasePHP :: [Text.Text] connectToTheDatabasePHP = [ "// Connect to the database" , "$DB_link = mysqli_connect($DB_host,$DB_user,$DB_pass,$DB_name);" , "// Check connection" , "if (mysqli_connect_errno()) {" , " die('Error : Failed to connect to the database: ' . mysqli_connect_error());" , " }" , "" ]<> [ "$sql=\"SET SESSION sql_mode = 'ANSI,TRADITIONAL'\";" -- ANSI because of the syntax of the generated SQL -- TRADITIONAL because of some more safety , "if (!mysqli_query($DB_link,$sql)) {" , " die('Error setting sql_mode: ' . mysqli_error($DB_link));" , " }" , "" ] createTempDatabase :: FSpec -> IO Bool createTempDatabase fSpec = do { result <- executePHPStr . showPHP $ phpStr ; verboseLn (getOpts fSpec) (if null result then "Temp database created succesfully." else "Temp database creation failed! :\n"<>lineNumbers phpStr<>"\nThe result:\n"<>result ) ; return (null result) } where lineNumbers :: [Text.Text] -> String lineNumbers = intercalate " \n" . map withNumber . zip [1..] . map Text.unpack where withNumber :: (Int,String) -> String withNumber (n,t) = "/*"<>take (5-length(show n)) "00000"<>show n<>"*/ "<>t phpStr :: [Text.Text] phpStr = connectToMySqlServerPHP (getOpts fSpec) Nothing <> [ "/*** Set global varables to ensure the correct working of MySQL with Ampersand ***/" , "" , " /* file_per_table is required for long columns */" , " $sql='SET GLOBAL innodb_file_per_table = true';" , " $result=mysqli_query($DB_link, $sql);" , " if(!$result)" , " die('Error '.($ernr=mysqli_errno($DB_link)).': '.mysqli_error($DB_link).'(Sql: $sql)');" , "" , " /* file_format = Barracuda is required for long columns */" , " $sql='SET GLOBAL innodb_file_format = `Barracuda`';" , " $result=mysqli_query($DB_link, $sql);" , " if(!$result)" , " die('Error '.($ernr=mysqli_errno($DB_link)).': '.mysqli_error($DB_link).'(Sql: $sql)');" , "" , " /* large_prefix gives max single-column indices of 3072 bytes = win! */" , " $sql='SET GLOBAL innodb_large_prefix = true';" , " $result=mysqli_query($DB_link, $sql);" , " if(!$result)" , " die('Error '.($ernr=mysqli_errno($DB_link)).': '.mysqli_error($DB_link).'(Sql: $sql)');" , "" ]<> [ "$DB_name='"<>tempDbName (getOpts fSpec)<>"';" , "// Drop the database if it exists" , "$sql="<>queryAsPHP dropDB<>";" , "mysqli_query($DB_link,$sql);" , "// Don't bother about the error if the database didn't exist..." , "" , "// Create the database" , "$sql="<>queryAsPHP createDB<>";" , "if (!mysqli_query($DB_link,$sql)) {" , " // For diagnosis, dump the current file, so we can see what is going on." , " $trace = debug_backtrace();" , " $file = $trace[1]['file'];" , " $thisFile = file_get_contents($file);" , " fwrite(STDERR, $thisFile . \"\\n\");" , " die('Error creating the database: ' . mysqli_error($DB_link));" , " }" , "" ] <> connectToTheDatabasePHP <> [ "/*** Create new SQL tables ***/" , "" ] <> [ "" , "//// Number of plugs: " <> Text.pack (show (length (plugInfos fSpec))) ] -- Create all plugs <> concatMap (createTablePHP . plug2TableSpec) [p | InternalPlug p <- plugInfos fSpec] -- Populate all plugs <> concatMap populatePlugPHP [p | InternalPlug p <- plugInfos fSpec] where dropDB :: SqlQuery dropDB = SqlQuerySimple $ "DROP DATABASE "<>(singleQuote . tempDbName . getOpts $ fSpec) createDB :: SqlQuery createDB = SqlQuerySimple $ "CREATE DATABASE "<>(singleQuote . tempDbName . getOpts $ fSpec)<>" DEFAULT CHARACTER SET UTF8 COLLATE utf8_bin" populatePlugPHP plug = case tableContents fSpec plug of [] -> [] tblRecords -> ( "mysqli_query($DB_link, "<> queryAsPHP query <>");" ):["if($err=mysqli_error($DB_link)) { $error=true; echo $err.'<br />'; }"] where query = insertQuery True tableName attrNames tblRecords tableName = Text.pack . name $ plug attrNames = map (Text.pack . attName) . plugAttributes $ plug
AmpersandTarski/ampersand
src/Ampersand/Prototype/PHP.hs
gpl-3.0
9,876
0
19
2,634
1,978
1,067
911
212
3
{-# LANGUAGE FlexibleInstances #-} module Database.Design.Ampersand.Input.ADL1.CtxError ( CtxError(PE) , showErr, makeError, addError , cannotDisamb, cannotDisambRel , mustBeOrdered, mustBeOrderedLst, mustBeOrderedConcLst , mustBeBound , GetOneGuarded(..), uniqueNames, mkDanglingPurposeError , mkUndeclaredError, mkMultipleInterfaceError, mkInterfaceRefCycleError, mkIncompatibleInterfaceError , mkMultipleDefaultError, mkDanglingRefError , mkIncompatibleViewError, mkOtherAtomInSessionError , Guarded(..) , whenCheckedIO, whenChecked , unguard ) -- SJC: I consider it ill practice to export CTXE -- Reason: CtxError should obtain all error messages -- By not exporting anything that takes a string, we prevent other modules from containing error message -- If you build a function that must generate an error, put it in CtxError and call it instead -- see `getOneExactly' / `GetOneGuarded' as a nice example -- Although I also consider it ill practice to export PE, I did this as a quick fix for the parse errors where import Control.Applicative import Database.Design.Ampersand.ADL1 import Database.Design.Ampersand.FSpec.ShowADL import Database.Design.Ampersand.Basics -- import Data.Traversable import Data.List (intercalate) import GHC.Exts (groupWith) import Database.Design.Ampersand.Core.ParseTree import Text.Parsec.Error (Message(..), messageString) import Database.Design.Ampersand.Input.ADL1.FilePos() fatal,_notUsed :: Int -> String -> a fatal = fatalMsg "Input.ADL1.CtxError" _notUsed = fatal -- unguard is like an applicative join, which can be used to elegantly express monadic effects for Guarded. -- The function is a bit more compositional than the previous ly used <?> as you don't have to tuple all the arguments. -- Similar to join and bind we have: unguard g = id <?> g, and f <?> g = unguard $ f <$> g unguard :: Guarded (Guarded a) -> Guarded a unguard (Errors errs) = Errors errs unguard (Checked g) = g data CtxError = CTXE Origin String -- SJC: I consider it ill practice to export CTXE, see remark at top | PE Message instance Show CtxError where show (CTXE o s) = "CTXE " ++ show o ++ " " ++ show s show (PE msg) = "PE " ++ messageString msg errors :: Guarded t -> [CtxError] errors (Checked _) = [] errors (Errors lst) = lst makeError :: String -> Guarded a makeError msg = Errors [PE (Message msg)] addError :: String -> Guarded a -> Guarded b addError msg guard = Errors (PE (Message msg):errors guard) class GetOneGuarded a where getOneExactly :: (Traced a1, ShowADL a1) => a1 -> [a] -> Guarded a getOneExactly _ [a] = Checked a getOneExactly o l@[] = hasNone l o getOneExactly o lst = Errors [CTXE o'$ "Found too many:\n "++s | CTXE o' s <- errors (hasNone lst o)] hasNone :: (Traced a1, ShowADL a1) => [a] -- this argument should be ignored! It is only here to help indicate a type (you may put []) -> a1 -- the object where the problem is arising -> Guarded a hasNone _ o = getOneExactly o [] instance GetOneGuarded (P_SubIfc a) where hasNone _ o = Errors [CTXE (origin o)$ "Required: one subinterface in "++showADL o] instance GetOneGuarded (SubInterface) where hasNone _ o = Errors [CTXE (origin o)$ "Required: one subinterface in "++showADL o] instance GetOneGuarded Declaration where getOneExactly _ [d] = Checked d getOneExactly o [] = Errors [CTXE (origin o)$ "No declaration for "++showADL o] getOneExactly o lst = Errors [CTXE (origin o)$ "Too many declarations match "++showADL o++".\n Be more specific. These are the matching declarations:"++concat ["\n - "++showADL l++" at "++showFullOrig (origin l) | l<-lst]] cannotDisambRel :: TermPrim -> [Expression] -> Guarded Expression cannotDisambRel o exprs = Errors [CTXE (origin o) message] where message = case exprs of [] -> "No declarations match the relation: "++showADL o _ -> case o of (PNamedR(PNamedRel _ _ Nothing)) -> intercalate "\n" $ ["Cannot disambiguate the relation: "++showADL o ," Please add a signature (e.g. [A*B]) to the relation." ," Relations you may have intended:" ]++ [" "++showADL e++"["++name (source e)++"*"++name (target e)++"]" |e<-exprs] _ -> intercalate "\n" $ ["Cannot disambiguate: "++showADL o ," Please add a signature." ," You may have intended one of these:" ]++ [" "++showADL e|e<-exprs] cannotDisamb :: TermPrim -> Guarded Expression cannotDisamb o = Errors [CTXE (origin o)$ "Cannot disambiguate: "++showADL o++"\n Please add a signature to it"] uniqueNames :: (Named a, Traced a) => [a] -> Guarded () uniqueNames a = case (filter moreThanOne . groupWith name) a of [] -> pure () xs -> Errors (map messageFor xs) where moreThanOne (_:_:_) = True moreThanOne _ = False messageFor :: (Named a, Traced a) => [a] -> CtxError messageFor (x:xs) = CTXE (origin x) ("Names / labels must be unique. "++(show . name) x++", however, is used at:"++ concatMap (("\n "++ ) . show . origin) (x:xs) ++"." ) messageFor _ = fatal 90 "messageFor must only be used on lists with more that one element!" mkDanglingPurposeError :: Purpose -> CtxError mkDanglingPurposeError p = CTXE (origin p) $ "Purpose refers to non-existent " ++ showADL (explObj p) -- Unfortunately, we cannot use position of the explanation object itself because it is not an instance of Trace. mkDanglingRefError :: String -- The type of thing that dangles. eg. "Rule" -> String -- the reference itself. eg. "Rule 42" -> Origin -- The place where the thing is found. -> CtxError mkDanglingRefError entity ref orig = CTXE orig $ "Refference to non-existent " ++ entity ++ ": "++show ref mkUndeclaredError :: (Traced e, Named e) => String -> e -> String -> CtxError mkUndeclaredError entity objDef ref = CTXE (origin objDef) $ "Undeclared " ++ entity ++ " " ++ show ref ++ " referenced at field " ++ show (name objDef) mkMultipleInterfaceError :: String -> Interface -> [Interface] -> CtxError mkMultipleInterfaceError role ifc duplicateIfcs = CTXE (origin ifc) $ "Multiple interfaces named " ++ show (name ifc) ++ " for role " ++ show role ++ ":" ++ concatMap (("\n "++ ) . show . origin) (ifc:duplicateIfcs) mkInterfaceRefCycleError :: [Interface] -> CtxError mkInterfaceRefCycleError [] = fatal 108 "mkInterfaceRefCycleError called on []" mkInterfaceRefCycleError cyclicIfcs@(ifc:_) = -- take the first one (there will be at least one) as the origin of the error CTXE (origin ifc) $ "Interfaces form a reference cycle:\n" ++ unlines [ "- " ++ show (name i) ++ " at position " ++ show (origin i) | i <- cyclicIfcs ] mkIncompatibleInterfaceError :: P_ObjDef a -> A_Concept -> A_Concept -> String -> CtxError mkIncompatibleInterfaceError objDef expTgt refSrc ref = CTXE (origin objDef) $ "Incompatible interface reference "++ show ref ++ " at field " ++ show (name objDef) ++ ":\nReferenced interface "++show ref++" has type " ++ show (name refSrc) ++ ", which is not comparable to the target " ++ show (name expTgt) ++ " of the expression at this field." mkMultipleDefaultError :: (A_Concept, [ViewDef]) -> CtxError mkMultipleDefaultError (_, []) = fatal 118 "mkMultipleDefaultError called on []" mkMultipleDefaultError (c, viewDefs@(vd0:_)) = CTXE (origin vd0) $ "Multiple default views for concept " ++ show (name c) ++ ":" ++ concat ["\n VIEW " ++ vdlbl vd ++ " (at " ++ show (origin vd) ++ ")" | vd <- viewDefs ] mkIncompatibleViewError :: P_ObjDef a -> String -> String -> String -> CtxError mkIncompatibleViewError objDef viewId viewRefCptStr viewCptStr = CTXE (origin objDef) $ "Incompatible view annotation <"++viewId++"> at field " ++ show (name objDef) ++ ":\nView " ++ show viewId ++ " has type " ++ show viewCptStr ++ ", which should be equal to or more general than the target " ++ show viewRefCptStr ++ " of the expression at this field." mkOtherAtomInSessionError :: String -> CtxError mkOtherAtomInSessionError atomValue = CTXE OriginUnknown $ "The special concept `SESSION` must not contain anything else then `_SESSION`. However it is populated with `"++atomValue++"`." class ErrorConcept a where showEC :: a -> String showMini :: a -> String instance ErrorConcept (P_ViewD a) where showEC x = showADL (vd_cpt x) ++" given in VIEW "++vd_lbl x showMini x = showADL (vd_cpt x) instance ErrorConcept (P_IdentDef) where showEC x = showADL (ix_cpt x) ++" given in Identity "++ix_lbl x showMini x = showADL (ix_cpt x) instance (ShowADL a2) => ErrorConcept (SrcOrTgt, A_Concept, a2) where showEC (p1,c1,e1) = showEC' (p1,c1,showADL e1) showMini (_,c1,_) = showADL c1 showEC' :: (SrcOrTgt, A_Concept, String) -> String showEC' (p1,c1,e1) = showADL c1++" ("++show p1++" of "++e1++")" instance (ShowADL a2, Association a2) => ErrorConcept (SrcOrTgt, a2) where showEC (p1,e1) = case p1 of Src -> showEC' (p1,source e1,showADL e1) Tgt -> showEC' (p1,target e1,showADL e1) showMini (p1,e1) = case p1 of Src -> showADL (source e1) Tgt -> showADL (target e1) instance (ShowADL a2, Association a2) => ErrorConcept (SrcOrTgt, Origin, a2) where showEC (p1,o,e1) = case p1 of Src -> showEC' (p1,source e1,showADL e1 ++ ", "++showMinorOrigin o) Tgt -> showEC' (p1,target e1,showADL e1 ++ ", "++showMinorOrigin o) showMini (p1,_,e1) = case p1 of Src -> showADL (source e1) Tgt -> showADL (target e1) mustBeOrdered :: (Traced a1, ErrorConcept a2, ErrorConcept a3) => a1 -> a2 -> a3 -> Guarded a mustBeOrdered o a b = Errors [CTXE (origin o)$ "Type error, cannot match:\n the concept "++showEC a ++"\n and concept "++showEC b ++"\n if you think there is no type error, add an order between concepts "++showMini a++" and "++showMini b++"."] mustBeOrderedLst :: (Traced o, ShowADL o, ShowADL a) => o -> [(A_Concept, SrcOrTgt, a)] -> Guarded b mustBeOrderedLst o lst = Errors [CTXE (origin o)$ "Type error in "++showADL o++"\n Cannot match:"++ concat [ "\n - concept "++showADL c++", "++show st++" of "++showADL a | (c,st,a) <- lst ] ++ "\n if you think there is no type error, add an order between the mismatched concepts." ] mustBeOrderedConcLst :: Origin -> (SrcOrTgt, Expression) -> (SrcOrTgt, Expression) -> [[A_Concept]] -> Guarded a mustBeOrderedConcLst o (p1,e1) (p2,e2) cs = Errors [CTXE o$ "Ambiguous type when matching: "++show p1++" of "++showADL e1++"\n" ++" and "++show p2++" of "++showADL e2++".\n" ++" The type can be "++intercalate " or " (map (showADL . Slash) cs) ++"\n None of these concepts is known to be the smallest, you may want to add an order between them."] newtype Slash a = Slash [a] instance ShowADL a => ShowADL (Slash a) where showADL (Slash x) = intercalate "/" (map showADL x) mustBeBound :: Origin -> [(SrcOrTgt, Expression)] -> Guarded a mustBeBound o [(p,e)] = Errors [CTXE o$ "An ambiguity arises in type checking. Be more specific by binding the "++show p++" of the expression "++showADL e++".\n"++ " You could add more types inside the expression, or just write "++writeBind e++"."] mustBeBound o lst = Errors [CTXE o$ "An ambiguity arises in type checking. Be more specific in the expressions "++intercalate " and " (map (showADL . snd) lst) ++".\n"++ " You could add more types inside the expression, or write:"++ concat ["\n "++writeBind e| (_,e)<-lst]] writeBind :: Expression -> String writeBind (ECpl e) = "("++showADL (EDcV (sign e))++" - "++showADL e++")" writeBind e = "("++showADL e++") /\\ "++showADL (EDcV (sign e)) data Guarded a = Errors [CtxError] | Checked a deriving Show instance Functor Guarded where fmap _ (Errors a) = Errors a fmap f (Checked a) = Checked (f a) instance Applicative Guarded where pure = Checked (<*>) (Checked f) (Checked a) = Checked (f a) (<*>) (Errors a) (Checked _) = Errors a (<*>) (Checked _) (Errors b) = Errors b (<*>) (Errors a) (Errors b) = Errors (a ++ b) -- this line makes Guarded not a monad -- Guarded is NOT a monad! -- Reason: (<*>) has to be equal to `ap' if it is, and this definition is different -- Use <?> if you wish to use the monad-like thing -- Shorthand for working with Guarded in IO whenCheckedIO :: IO (Guarded a) -> (a -> IO (Guarded b)) -> IO (Guarded b) whenCheckedIO ioGA fIOGB = do gA <- ioGA case gA of Errors err -> return (Errors err) Checked a -> fIOGB a whenChecked :: Guarded a -> (a -> Guarded b) -> Guarded b whenChecked ga fgb = case ga of Checked a -> fgb a Errors err -> Errors err showErr :: CtxError -> String showErr (CTXE o s) = s ++ "\n " ++ showFullOrig o showErr (PE msg) = messageString msg showFullOrig :: Origin -> String showFullOrig (FileLoc (FilePos filename line column) t) = "Error at symbol " ++ t ++ " in file " ++ filename ++ " at line " ++ show line ++ " : " ++ show column showFullOrig x = show x showMinorOrigin :: Origin -> String showMinorOrigin (FileLoc (FilePos _ line column) _) = "line " ++ show line ++" : "++show column showMinorOrigin v = show v
DanielSchiavini/ampersand
src/Database/Design/Ampersand/Input/ADL1/CtxError.hs
gpl-3.0
14,130
0
21
3,607
4,177
2,136
2,041
234
4
module P01HelloSpec (main,spec) where import Test.Hspec import Test.Hspec.QuickCheck import P01Hello hiding (main) main :: IO () main = hspec spec spec = do describe "chooseGreet" $ do it "insults David Cameron correctly" $ do chooseGreet "David Cameron" == "PIGFUCKER!" it "greets Charlie correctly" $ do chooseGreet "Charlie" == "Greetings, professor. How about a nice game of chess?" it "greets other correctly" $ do chooseGreet "Wilma" == "Hello, Wilma, how do you do?"
ciderpunx/57-exercises-for-programmers
test/P01HelloSpec.hs
gpl-3.0
511
0
14
109
125
61
64
14
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.DeploymentManager -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- The Google Cloud Deployment Manager v2 API provides services for -- configuring, deploying, and viewing Google Cloud services and APIs via -- templates which specify deployments of Cloud resources. -- -- /See:/ <https://cloud.google.com/deployment-manager Cloud Deployment Manager V2 API Reference> module Network.Google.DeploymentManager ( -- * Service Configuration deploymentManagerService -- * OAuth Scopes , cloudPlatformReadOnlyScope , cloudPlatformScope , ndevCloudmanScope , ndevCloudmanReadOnlyScope -- * API Declaration , DeploymentManagerAPI -- * Resources -- ** deploymentmanager.deployments.cancelPreview , module Network.Google.Resource.DeploymentManager.Deployments.CancelPreview -- ** deploymentmanager.deployments.delete , module Network.Google.Resource.DeploymentManager.Deployments.Delete -- ** deploymentmanager.deployments.get , module Network.Google.Resource.DeploymentManager.Deployments.Get -- ** deploymentmanager.deployments.getIamPolicy , module Network.Google.Resource.DeploymentManager.Deployments.GetIAMPolicy -- ** deploymentmanager.deployments.insert , module Network.Google.Resource.DeploymentManager.Deployments.Insert -- ** deploymentmanager.deployments.list , module Network.Google.Resource.DeploymentManager.Deployments.List -- ** deploymentmanager.deployments.patch , module Network.Google.Resource.DeploymentManager.Deployments.Patch -- ** deploymentmanager.deployments.setIamPolicy , module Network.Google.Resource.DeploymentManager.Deployments.SetIAMPolicy -- ** deploymentmanager.deployments.stop , module Network.Google.Resource.DeploymentManager.Deployments.Stop -- ** deploymentmanager.deployments.testIamPermissions , module Network.Google.Resource.DeploymentManager.Deployments.TestIAMPermissions -- ** deploymentmanager.deployments.update , module Network.Google.Resource.DeploymentManager.Deployments.Update -- ** deploymentmanager.manifests.get , module Network.Google.Resource.DeploymentManager.Manifests.Get -- ** deploymentmanager.manifests.list , module Network.Google.Resource.DeploymentManager.Manifests.List -- ** deploymentmanager.operations.get , module Network.Google.Resource.DeploymentManager.Operations.Get -- ** deploymentmanager.operations.list , module Network.Google.Resource.DeploymentManager.Operations.List -- ** deploymentmanager.resources.get , module Network.Google.Resource.DeploymentManager.Resources.Get -- ** deploymentmanager.resources.list , module Network.Google.Resource.DeploymentManager.Resources.List -- ** deploymentmanager.types.list , module Network.Google.Resource.DeploymentManager.Types.List -- * Types -- ** OperationWarningsItemDataItem , OperationWarningsItemDataItem , operationWarningsItemDataItem , owidiValue , owidiKey -- ** ConfigFile , ConfigFile , configFile , cfContent -- ** OperationWarningsItemCode , OperationWarningsItemCode (..) -- ** AuditConfig , AuditConfig , auditConfig , acService , acAuditLogConfigs -- ** DeploymentsUpdateCreatePolicy , DeploymentsUpdateCreatePolicy (..) -- ** Expr , Expr , expr , eLocation , eExpression , eTitle , eDescription -- ** OperationsListResponse , OperationsListResponse , operationsListResponse , olrNextPageToken , olrOperations -- ** ResourceUpdateWarningsItemDataItem , ResourceUpdateWarningsItemDataItem , resourceUpdateWarningsItemDataItem , ruwidiValue , ruwidiKey -- ** ResourceUpdateWarningsItemCode , ResourceUpdateWarningsItemCode (..) -- ** DeploymentsDeleteDeletePolicy , DeploymentsDeleteDeletePolicy (..) -- ** TypesListResponse , TypesListResponse , typesListResponse , tlrNextPageToken , tlrTypes -- ** DeploymentsUpdateDeletePolicy , DeploymentsUpdateDeletePolicy (..) -- ** DeploymentsPatchDeletePolicy , DeploymentsPatchDeletePolicy (..) -- ** Operation , Operation , operation , oTargetId , oStatus , oOperationGroupId , oInsertTime , oProgress , oStartTime , oKind , oError , oHTTPErrorMessage , oZone , oWarnings , oHTTPErrorStatusCode , oUser , oSelfLink , oName , oStatusMessage , oCreationTimestamp , oEndTime , oId , oOperationType , oRegion , oDescription , oTargetLink , oClientOperationId -- ** TestPermissionsResponse , TestPermissionsResponse , testPermissionsResponse , tprPermissions -- ** DeploymentsPatchCreatePolicy , DeploymentsPatchCreatePolicy (..) -- ** ResourcesListResponse , ResourcesListResponse , resourcesListResponse , rlrNextPageToken , rlrResources -- ** DeploymentUpdate , DeploymentUpdate , deploymentUpdate , duManifest , duLabels , duDescription -- ** ResourceUpdate , ResourceUpdate , resourceUpdate , ruState , ruError , ruAccessControl , ruWarnings , ruIntent , ruManifest , ruFinalProperties , ruProperties -- ** DeploymentLabelEntry , DeploymentLabelEntry , deploymentLabelEntry , dleValue , dleKey -- ** OperationStatus , OperationStatus (..) -- ** ResourceUpdateState , ResourceUpdateState (..) -- ** ResourceUpdateIntent , ResourceUpdateIntent (..) -- ** TestPermissionsRequest , TestPermissionsRequest , testPermissionsRequest , tPermissions -- ** Manifest , Manifest , manifest , mInsertTime , mLayout , mConfig , mExpandedConfig , mManifestSizeBytes , mImports , mSelfLink , mName , mId , mManifestSizeLimitBytes -- ** ResourceUpdateWarningsItem , ResourceUpdateWarningsItem , resourceUpdateWarningsItem , ruwiData , ruwiCode , ruwiMessage -- ** DeploymentsCancelPreviewRequest , DeploymentsCancelPreviewRequest , deploymentsCancelPreviewRequest , dcprFingerprint -- ** AuditLogConfigLogType , AuditLogConfigLogType (..) -- ** Resource , Resource , resource , rInsertTime , rAccessControl , rURL , rWarnings , rUpdateTime , rName , rManifest , rFinalProperties , rId , rType , rUpdate , rProperties -- ** Xgafv , Xgafv (..) -- ** DeploymentUpdateLabelEntry , DeploymentUpdateLabelEntry , deploymentUpdateLabelEntry , duleValue , duleKey -- ** ResourceUpdateErrorErrorsItem , ResourceUpdateErrorErrorsItem , resourceUpdateErrorErrorsItem , rueeiLocation , rueeiCode , rueeiMessage -- ** ManifestsListResponse , ManifestsListResponse , manifestsListResponse , mlrNextPageToken , mlrManifests -- ** OperationError , OperationError , operationError , oeErrors -- ** GlobalSetPolicyRequest , GlobalSetPolicyRequest , globalSetPolicyRequest , gsprEtag , gsprBindings , gsprPolicy -- ** Policy , Policy , policy , pAuditConfigs , pEtag , pVersion , pBindings -- ** Type , Type , type' , tInsertTime , tOperation , tSelfLink , tName , tId -- ** ImportFile , ImportFile , importFile , ifContent , ifName -- ** OperationErrorErrorsItem , OperationErrorErrorsItem , operationErrorErrorsItem , oeeiLocation , oeeiCode , oeeiMessage -- ** DeploymentsStopRequest , DeploymentsStopRequest , deploymentsStopRequest , dsrFingerprint -- ** ResourceWarningsItemDataItem , ResourceWarningsItemDataItem , resourceWarningsItemDataItem , rwidiValue , rwidiKey -- ** AuditLogConfig , AuditLogConfig , auditLogConfig , alcLogType , alcExemptedMembers -- ** ResourceUpdateError , ResourceUpdateError , resourceUpdateError , rueErrors -- ** ResourceWarningsItemCode , ResourceWarningsItemCode (..) -- ** DeploymentsListResponse , DeploymentsListResponse , deploymentsListResponse , dlrNextPageToken , dlrDeployments -- ** ResourceWarningsItem , ResourceWarningsItem , resourceWarningsItem , rwiData , rwiCode , rwiMessage -- ** ResourceAccessControl , ResourceAccessControl , resourceAccessControl , racGcpIAMPolicy -- ** TargetConfiguration , TargetConfiguration , targetConfiguration , tcConfig , tcImports -- ** OperationWarningsItem , OperationWarningsItem , operationWarningsItem , owiData , owiCode , owiMessage -- ** Binding , Binding , binding , bMembers , bRole , bCondition -- ** Deployment , Deployment , deployment , dInsertTime , dOperation , dFingerprint , dUpdateTime , dSelfLink , dName , dManifest , dId , dLabels , dDescription , dUpdate , dTarget -- ** DeploymentsInsertCreatePolicy , DeploymentsInsertCreatePolicy (..) ) where import Network.Google.Prelude import Network.Google.DeploymentManager.Types import Network.Google.Resource.DeploymentManager.Deployments.CancelPreview import Network.Google.Resource.DeploymentManager.Deployments.Delete import Network.Google.Resource.DeploymentManager.Deployments.Get import Network.Google.Resource.DeploymentManager.Deployments.GetIAMPolicy import Network.Google.Resource.DeploymentManager.Deployments.Insert import Network.Google.Resource.DeploymentManager.Deployments.List import Network.Google.Resource.DeploymentManager.Deployments.Patch import Network.Google.Resource.DeploymentManager.Deployments.SetIAMPolicy import Network.Google.Resource.DeploymentManager.Deployments.Stop import Network.Google.Resource.DeploymentManager.Deployments.TestIAMPermissions import Network.Google.Resource.DeploymentManager.Deployments.Update import Network.Google.Resource.DeploymentManager.Manifests.Get import Network.Google.Resource.DeploymentManager.Manifests.List import Network.Google.Resource.DeploymentManager.Operations.Get import Network.Google.Resource.DeploymentManager.Operations.List import Network.Google.Resource.DeploymentManager.Resources.Get import Network.Google.Resource.DeploymentManager.Resources.List import Network.Google.Resource.DeploymentManager.Types.List {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the Cloud Deployment Manager V2 API service. type DeploymentManagerAPI = TypesListResource :<|> ResourcesListResource :<|> ResourcesGetResource :<|> ManifestsListResource :<|> ManifestsGetResource :<|> DeploymentsInsertResource :<|> DeploymentsListResource :<|> DeploymentsGetIAMPolicyResource :<|> DeploymentsPatchResource :<|> DeploymentsGetResource :<|> DeploymentsCancelPreviewResource :<|> DeploymentsSetIAMPolicyResource :<|> DeploymentsStopResource :<|> DeploymentsTestIAMPermissionsResource :<|> DeploymentsDeleteResource :<|> DeploymentsUpdateResource :<|> OperationsListResource :<|> OperationsGetResource
brendanhay/gogol
gogol-deploymentmanager/gen/Network/Google/DeploymentManager.hs
mpl-2.0
11,837
0
21
2,516
1,294
930
364
298
0
<h3>Example 52 (simple heat map)</h3> <plot height=500 aspect=1> <heatmap x="[[test.x]]" y="[[test.y]]" fill-zero="none" fill="[[@P{blue;red}]]"></heatmap> </plot> <plot-data name="test" format="csv" cols="x,y"> -1.358218406,-1.680180041 1.019182305,0.372856303 -0.046088243,-1.437769350 -1.652131815,1.508971050 0.880858861,-1.351061092 -0.421879985,0.460046324 -1.775861788,-0.377353402 -0.432299413,-0.544505160 0.597065895,1.063556238 1.018733929,0.516806935 0.693442592,0.818444791 -0.151663918,0.365657710 -0.484266425,1.106456147 -0.563660625,-0.340853294 1.027548529,1.374454347 0.018512709,0.497770566 -0.898245409,-0.273169274 0.401530957,-0.674111550 -1.614098348,-0.004893727 0.475737412,-0.167170150 2.896699296,-1.644885154 0.369390551,-0.363407053 0.195674450,0.796902390 -0.455183324,0.579003105 -0.840773769,-1.275440408 0.201168111,-0.145193347 -0.977505714,-1.097588725 -0.157543842,0.931822793 1.213436851,1.298792286 -0.095741952,2.106816580 -0.111263004,-2.078441409 -1.052447580,0.491906540 -0.223993725,0.596251685 -0.052027197,0.232441049 1.649155223,1.106705488 0.034758550,0.089969971 0.630451636,-2.019073856 0.317187144,0.159083991 0.907639885,0.389694700 3.507502055,0.745939039 0.241160732,0.863903018 -1.626223538,1.011512303 0.989728940,1.009256748 0.617118223,-0.954345976 1.281573323,-0.980004467 0.495453751,-0.368463663 0.123889926,-1.535610105 0.335354589,0.014701983 -0.338484233,-0.666617714 1.027240081,-0.576596127 0.171040222,0.260085664 0.111490346,-0.164757454 -0.596089124,1.235859094 0.375068347,1.108377818 0.875997125,0.491710332 0.226746929,0.666406706 -2.352907879,-0.200828814 -0.300730546,-0.467913893 0.206455528,0.983026064 -0.740838462,-1.625012236 -0.282646786,0.966176452 -1.444361250,-0.192205832 1.215377424,-0.655657397 -0.717685934,-1.684864615 -0.592155462,-0.063825352 2.519884926,-1.399751647 -0.235264465,-1.448776053 0.168046668,-0.677469532 -0.858446520,0.075247524 -0.426844135,0.138844531 -1.010234356,0.591016780 0.679895798,0.764228183 -0.387500047,-1.692940404 2.520777242,1.920958205 -0.488662927,0.472892173 0.009272712,-0.936161622 -0.053498613,0.573661462 -0.457075249,0.502713786 -0.574686946,-0.257165813 0.285084048,0.307028734 -0.445707159,0.529429678 1.748563380,-1.349685484 0.428504645,0.141547824 -0.710781981,1.296516455 -0.907194831,-1.654794968 -0.654270763,-1.238840341 -0.174782471,0.165698550 2.120830108,0.656595369 0.256434229,-0.068412006 0.097702199,0.657398908 -1.643564412,-1.029640776 1.287269469,0.253276516 -0.779834081,-0.752704032 -0.400443388,-0.144411218 0.864388402,-1.466337337 -0.326945256,-2.497433918 0.312223956,0.377362888 0.948793386,0.738802681 0.456457305,0.478290244 0.466944067,-0.500205475 </plot-data>
openbrainsrc/hRadian
examples/Example/defunct/Eg52.hs
mpl-2.0
2,735
127
18
134
738
460
278
-1
-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.Sheets.Spreadsheets.Values.BatchUpdate -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Sets values in one or more ranges of a spreadsheet. The caller must -- specify the spreadsheet ID, a valueInputOption, and one or more -- ValueRanges. -- -- /See:/ <https://developers.google.com/sheets/ Google Sheets API Reference> for @sheets.spreadsheets.values.batchUpdate@. module Network.Google.Resource.Sheets.Spreadsheets.Values.BatchUpdate ( -- * REST Resource SpreadsheetsValuesBatchUpdateResource -- * Creating a Request , spreadsheetsValuesBatchUpdate , SpreadsheetsValuesBatchUpdate -- * Request Lenses , svbuXgafv , svbuUploadProtocol , svbuAccessToken , svbuSpreadsheetId , svbuUploadType , svbuPayload , svbuCallback ) where import Network.Google.Prelude import Network.Google.Sheets.Types -- | A resource alias for @sheets.spreadsheets.values.batchUpdate@ method which the -- 'SpreadsheetsValuesBatchUpdate' request conforms to. type SpreadsheetsValuesBatchUpdateResource = "v4" :> "spreadsheets" :> Capture "spreadsheetId" Text :> "values:batchUpdate" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] BatchUpdateValuesRequest :> Post '[JSON] BatchUpdateValuesResponse -- | Sets values in one or more ranges of a spreadsheet. The caller must -- specify the spreadsheet ID, a valueInputOption, and one or more -- ValueRanges. -- -- /See:/ 'spreadsheetsValuesBatchUpdate' smart constructor. data SpreadsheetsValuesBatchUpdate = SpreadsheetsValuesBatchUpdate' { _svbuXgafv :: !(Maybe Xgafv) , _svbuUploadProtocol :: !(Maybe Text) , _svbuAccessToken :: !(Maybe Text) , _svbuSpreadsheetId :: !Text , _svbuUploadType :: !(Maybe Text) , _svbuPayload :: !BatchUpdateValuesRequest , _svbuCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SpreadsheetsValuesBatchUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'svbuXgafv' -- -- * 'svbuUploadProtocol' -- -- * 'svbuAccessToken' -- -- * 'svbuSpreadsheetId' -- -- * 'svbuUploadType' -- -- * 'svbuPayload' -- -- * 'svbuCallback' spreadsheetsValuesBatchUpdate :: Text -- ^ 'svbuSpreadsheetId' -> BatchUpdateValuesRequest -- ^ 'svbuPayload' -> SpreadsheetsValuesBatchUpdate spreadsheetsValuesBatchUpdate pSvbuSpreadsheetId_ pSvbuPayload_ = SpreadsheetsValuesBatchUpdate' { _svbuXgafv = Nothing , _svbuUploadProtocol = Nothing , _svbuAccessToken = Nothing , _svbuSpreadsheetId = pSvbuSpreadsheetId_ , _svbuUploadType = Nothing , _svbuPayload = pSvbuPayload_ , _svbuCallback = Nothing } -- | V1 error format. svbuXgafv :: Lens' SpreadsheetsValuesBatchUpdate (Maybe Xgafv) svbuXgafv = lens _svbuXgafv (\ s a -> s{_svbuXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). svbuUploadProtocol :: Lens' SpreadsheetsValuesBatchUpdate (Maybe Text) svbuUploadProtocol = lens _svbuUploadProtocol (\ s a -> s{_svbuUploadProtocol = a}) -- | OAuth access token. svbuAccessToken :: Lens' SpreadsheetsValuesBatchUpdate (Maybe Text) svbuAccessToken = lens _svbuAccessToken (\ s a -> s{_svbuAccessToken = a}) -- | The ID of the spreadsheet to update. svbuSpreadsheetId :: Lens' SpreadsheetsValuesBatchUpdate Text svbuSpreadsheetId = lens _svbuSpreadsheetId (\ s a -> s{_svbuSpreadsheetId = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). svbuUploadType :: Lens' SpreadsheetsValuesBatchUpdate (Maybe Text) svbuUploadType = lens _svbuUploadType (\ s a -> s{_svbuUploadType = a}) -- | Multipart request metadata. svbuPayload :: Lens' SpreadsheetsValuesBatchUpdate BatchUpdateValuesRequest svbuPayload = lens _svbuPayload (\ s a -> s{_svbuPayload = a}) -- | JSONP svbuCallback :: Lens' SpreadsheetsValuesBatchUpdate (Maybe Text) svbuCallback = lens _svbuCallback (\ s a -> s{_svbuCallback = a}) instance GoogleRequest SpreadsheetsValuesBatchUpdate where type Rs SpreadsheetsValuesBatchUpdate = BatchUpdateValuesResponse type Scopes SpreadsheetsValuesBatchUpdate = '["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/spreadsheets"] requestClient SpreadsheetsValuesBatchUpdate'{..} = go _svbuSpreadsheetId _svbuXgafv _svbuUploadProtocol _svbuAccessToken _svbuUploadType _svbuCallback (Just AltJSON) _svbuPayload sheetsService where go = buildClient (Proxy :: Proxy SpreadsheetsValuesBatchUpdateResource) mempty
brendanhay/gogol
gogol-sheets/gen/Network/Google/Resource/Sheets/Spreadsheets/Values/BatchUpdate.hs
mpl-2.0
5,928
0
18
1,347
793
464
329
122
1
import System.IO import System.Random import Control.Concurrent import Control.Monad import Control.Concurrent.STM data Gate = MkGate Int (Tvar int) newGate :: Int -> Stm Gate newGate n = do tv <- newTVar 0 return (MkGate n tv) passGate :: Gate -> IO() passGate (MkGate n tv) = atomically (do n_left <-readTvar tv check (n_left > 0) writeTnar tv (n_left - 1)) opreateGate :: Gate -> IO () opreateGate (MkGate n tv) = do atomically (writeTVar tv n) atomically (do n_left <- readTVar tv check (n_left == 0)) data Group = MkGroup Int (TVar (Int,Gate,Gate)) newGroup :: Int -> IO Group newGroup n = atomically (do g1 <- newGate n g2 <- newGate n tv <-newTVar (n,g1,g2)) return (MkGroup n tv) awaitGroup :: Group ->STM (Gate,Gate) awaitGroup (MkGroup n tv) = do (n_left,g1,g2) <- readTVar tv check (n_left == 0) new_g1 <- newGate n new_g2 <- newGate n writeTVar tv (n,new_g1,new_g2) return (g1,g2) randomDeloy :: IO () randomDeloy = do time <- getStdRandom(randomR (1,3)) threadDelay (time * 10^6) joinGroup (MkGroup n tv) = atomically (do (n_left,g1,g2) <- readTVar tv check (n_left > 0) writeTVar tv (n_left-1,g1,g2) return (g1,g2)) task :: Group -> IO () -> IO () task group do_task = do (in_gate,out_gate) <- joinGroup group passGate in_gate do_task passGate out_gate elf',reindeer':: Group -> Int -> IO() elf' group e_id = task group (getHelp e_id) reindeer' group deer_id = task group (deliverToys deer_id) getHelp,deliverToys :: Int ->IO () getHelp e_id = putStrLn ("Elf "++ show e_id ++" is getting help from Santa") deliverToys d_id = putStrLn ("Reindeer " ++ show d_id ++ " delivering toys") elf,reindeer :: Group ->Int -> IO ThreadId elf gp e_id = forkIO (forever (do {elf' gp e_id; randomDelay})) reindeer gp d_id = forkIO (forever (do {reindeer' gp d_id; randomDelay})) santa' :: Group -> Group -> IO () santa' elf_gp rein_gp = do putSteLn "-----------------------------" (do_task, (in)gate, out_gate)) <- atoically (orElse (chooseGroup rein_gp "Let's deliver toys!") (chooseGroup elf_gp "Let me help with the toys!")) putStrLn ("Ho! Ho! Ho! "++ do_task) operateGate in_gate operateGate out_gate Where chooseGroup :: Group -> String -> STM (String, (Gate,Gate)) chooseGroup gp do_task = do gate <- awaitGroup gp return (do_task,gates) choose :: [(STM a,a -> IO ())] -> IO () choose choices = join (atomically (foldrl orElse actions)) Where actions :: [STM (IO())] actions = [do {val <- g ; return (rhs val)} | (g,rhs) <- choices] santa :: Group -> Group -> IO () santa elf|_gp rein_gp = do putStrLn "--------------------------" choose [(awaitGroup rein_gp, run "Let's deliver toys!"), (awaitGroup elf_gp, run "Let me help with the toys!")] where run :: String -> (Gate,Gate) -> IO () run do_task (in_gate, out_gate) = do putStrLn ("Ho! Ho! Ho! "++ do_task) operateGate in_gate operateGate out_gate main::IO() main = do hSetBuffering stdout LineBuffering elf_group <-newGroup 3 sequence_ [elf elf_group n| n <- [1..10]] rein_group <- newGroup 9 sequence_ [reindeer rein_group n | n <- [1..9]] forever (santa elf_group rein_group)
cwlmyjm/haskell
Learning/sdlr.hs
mpl-2.0
3,644
121
12
1,089
1,453
750
703
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DefaultSignatures #-} module Panda.Metadata ( getMeta , getEitherMeta , putMeta ) where import Control.Applicative import Control.Monad import qualified Data.ByteString.Char8 as B import Data.Map (Map, toList) import Data.Maybe import Data.Yaml import Data.Vector as V import GHC.Generics -- -- NOTE: recode using optional fromJSON constructors -- data Meta = Meta { alias :: Maybe String, -- Name of the tab which displays this file in HTML page clearance :: Maybe Int, -- clearance level of this file (higher = more public) contributor :: Maybe String, -- Name of contributor editor :: Maybe String, -- Name of editor source :: Maybe String, -- source to acknowledge layout :: Maybe String, -- the HTML or TeX id of the layout template keywords :: Maybe Array, -- of keywords year :: Maybe String, -- of a paper paper :: Maybe String, -- name of a paper qno :: Maybe Int, -- question number stids1 :: Maybe Array, -- of Station ids stids2 :: Maybe Array, -- of Station ids pvids1 :: Maybe Array, -- of Pervasive ids pvids2 :: Maybe Array -- of Pervasive ids } deriving Show instance FromJSON Meta where parseJSON (Object v) = Meta <$> v .:? "alias" .!= Nothing <*> v .:? "clearance" .!= Nothing <*> v .:? "contributor" .!= Nothing <*> v .:? "editor" .!= Nothing <*> v .:? "source" .!= Nothing <*> v .:? "layout" .!= Nothing <*> v .:? "keywords" .!= Nothing <*> v .:? "year" .!= Nothing <*> v .:? "paper" .!= Nothing <*> v .:? "qno" .!= Nothing <*> v .:? "stids1" .!= Nothing <*> v .:? "stids2" .!= Nothing <*> v .:? "pvids1" .!= Nothing <*> v .:? "pvids2" .!= Nothing -- A non-Object value is of the wrong type, so use mzero to fail. parseJSON _ = mzero instance ToJSON Meta where toJSON m = object [ "alias" .= alias m, "clearance" .= clearance m, "contributor" .= contributor m, "editor" .= editor m, "source" .= source m, "layout" .= layout m, "keywords" .= keywords m, "year" .= year m, "paper" .= paper m, "qno" .= qno m, "stids1" .= stids1 m, "stids2" .= stids2 m, "pvids1" .= pvids1 m, "pvids2" .= pvids2 m ] getMeta :: B.ByteString -> Maybe Meta getMeta = decode getEitherMeta :: B.ByteString -> Either String Meta getEitherMeta = decodeEither putMeta :: Maybe Meta -> String putMeta (Just meta) = B.unpack $ encode meta putMeta _ = "error"
gmp26/panda
src/Panda/Metadata.hs
lgpl-3.0
3,174
0
47
1,251
670
364
306
72
1
module Isomorphisms where data Weekday = Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday deriving (Enum, Eq, Ord, Show) data Seven = One | Two | Three | Four | Five | Six | Seven deriving (Enum, Eq, Ord, Show) transform :: (Enum a, Ord a, Enum b, Ord b) => a -> b transform = toEnum . fromEnum i0 :: Seven i0 = transform Tuesday i0' :: Weekday i0' = transform Tuesday i1 :: Weekday i1 = transform Three transform2 :: (Enum a, Ord a) => Int -> a transform2 = toEnum . (`rem` 7) i2 :: Weekday i2 = transform2 15 i3 :: Seven i3 = transform2 15 -- End
haroldcarr/learn-haskell-coq-ml-etc
haskell/book/2019-Program_Design_by_Calculation-Oliveira/2015-05-LambdaConf/Isomorphisms.hs
unlicense
627
0
6
175
242
138
104
19
1
module Debug.Trace.Disable where trace _ x = x traceShow = trace traceM _ = return ()
jtapolczai/FileSync
Debug/Trace/Disable.hs
apache-2.0
87
0
6
17
35
19
16
4
1
module Delahaye.A338013 (a338013_list, a338013) where import Delahaye.A338012 (a338012_list) import Helpers.Delahaye (missingFromTables) import Data.Set (Set) import qualified Data.Set as Set a338013 :: Int -> Integer a338013 n = a338013_list !! (n-1) a338013_list :: [Integer] a338013_list = missingFromTables [(+), (*)] a338012_list
peterokagey/haskellOEIS
src/Delahaye/A338013.hs
apache-2.0
337
0
7
41
108
66
42
9
1
module Kernel.Scheduling where import Control.Monad import Data.Function ( on ) import Data.Ratio import Data.Int import Data.List ( findIndex, minimumBy ) import qualified Data.Map as Map import Data.Maybe ( fromMaybe ) import Kernel.Data import Flow import Flow.Domain import Flow.Kernel import Flow.Vector makeOskarDomain :: Config -> Int -> Strategy (Domain Bins, Flow Index) makeOskarDomain cfg = makeScheduleDomain (cfgInput cfg) oskarRepeat oskarWeight -- | Given a set of entities to schedule with associated repeats and weights, -- make a new 'Bin' domain with associated index 'Flow'. makeScheduleDomain :: [a] -- ^ Items to schedule -> (a -> Int) -- ^ Number of repeats for item -> (a -> Double) -- ^ Weight of item -> Int -- ^ Number of nodes (= split to prepare) -> Strategy (Domain Bins, Flow Index) makeScheduleDomain items repeats weight nodes = do -- Balance let totalWeight a = fromIntegral (repeats a) * weight a balance = balancer nodes (map totalWeight items) -- We will now make a bin domain where every repeat is going to be -- one bin, with the size of the bin given by the faction of nodes -- we allocate to it. This is so that when we split the bins by the -- number of nodes later, we get exactly what we'd expect. let repBins :: [(Ratio Int, Int32)] repBins = concat $ zipWith3 repBin items balance [0..] repBin item alloc i = replicate (repeats item) (alloc % repeats item, i) repBinStarts = scanl (+) 0 $ map fst repBins totalReps = length repBins -- Make bin domain from a vector describing the bins as outlined -- above. let binRepr = VectorRepr WriteAccess :: VectorRepr Int () ddom <- makeBinDomain $ mappingKernel "scheduler" Z binRepr $ \_ _ -> do binVec <- allocCVector (3 * totalReps) :: IO (Vector Int64) let binVecDbl = castVector binVec :: Vector Double forM_ (zip3 [0..] repBins repBinStarts) $ \(n, (size, _), start) -> do pokeVector binVecDbl (n*3+0) (fromRational $ toRational start) pokeVector binVecDbl (n*3+1) (fromRational $ toRational (start+size)) pokeVector binVec (n*3+2) 1 return (castVector binVec) -- Make a Flow containing the indices ixFlow <- bindNew $ mappingKernel "indices" Z (indexRepr ddom) $ \_ _ -> castVector <$> (makeVector allocCVector $ map snd repBins) -- Finally, define a kernel that can be used to split the index set -- All done return (ddom, ixFlow) -- | Fairly simple kernel useful for splitting schedules as produced -- by 'makeScheduleDomain'. scheduleSplit :: DDom -> DDom -> Flow Index -> Kernel Index scheduleSplit inDom outDom = mappingKernel "schedule splitter" (indexRepr inDom :. Z) (indexRepr outDom) $ \[ixPar] outRBox -> do -- Get input and output bins let ((inRBox, ixs):_) = Map.assocs ixPar inBins = regionBins $ head inRBox outBins = regionBins $ head outRBox -- Check how many bins we need to drop let isOutStart bin = regionBinLow bin == regionBinLow (head outBins) toDrop = fromMaybe (error "Could not find start output bin in input bins!") (findIndex isOutStart inBins) -- Make new vector for the output region inIxs <- unmakeVector (castVector ixs) 0 (length inBins) :: IO [Int32] castVector <$> (makeVector allocCVector $ take (length outBins) $ drop toDrop inIxs) balancer :: Int -- ^ Number of nodes -> [Double] -- ^ Full execution times for each freq. channel (T for image × N iteraterion) -> [Int] -- ^ Number of nodes allocated to each channel balancer n ts = snd $ minimumBy (compare `on` fst) $ do -- Generate all possible schedules nTail <- replicateM (nCh - 1) [1 .. n - nCh + 1] let n0 = n - sum nTail ns = n0 : nTail guard (n0 > 0) -- Return pair of execution time and schedule return (maximum $ zipWith (\k t -> t / fromIntegral k) ns ts, ns) where nCh = length ts
SKA-ScienceDataProcessor/RC
MS6/programs/Kernel/Scheduling.hs
apache-2.0
4,027
0
21
979
1,103
570
533
64
1
{-# LANGUAGE QuasiQuotes #-} module Main where import System.Directory (createDirectoryIfMissing, doesFileExist, listDirectory) import System.FilePath (combine, takeBaseName) import Control.Monad (filterM) import Data.Char (toUpper) import System.Environment (getArgs) import qualified Data.Text.Lazy as Text import Data.Map (Map) import qualified Data.Map as M import System.Console.Docopt (Arguments, Docopt, Option, docopt, parseArgs, exitWithUsage, exitWithUsageMessage, getArgOrExitWith, argument, isPresent, command) import Data.GraphViz (graphToDot, fmtNode, fmtEdge, nonClusteredParams) import Data.GraphViz.Attributes (toLabel) import Data.GraphViz.Printing (toDot, renderDot) import Data.Graph.Inductive.Graph hiding (Context) import qualified Data.Graph.Inductive.Graph as Graph import Data.Graph.Inductive.PatriciaTree import AttributeGrammar import Lexer import Parser import Monotone import qualified ConstPropagation as CP import qualified StronglyLiveVariables as SLV usage :: Docopt usage = [docopt| mf version 0.1.0 Usage: mf <max-context-depth> <file> mf all <max-context-depth> <inputDir> <outputDir> mf --help | -h |] getArgOrExit :: Arguments -> Option -> IO String getArgOrExit = getArgOrExitWith usage parseArgsOrExit :: [String] -> IO Arguments parseArgsOrExit = either (\err -> exitWithUsageMessage usage (show err)) (\args -> return args) . parseArgs usage main :: IO () main = do arguments <- getArgs args <- parseArgsOrExit arguments if (args `isPresent` (command "--help")) || (args `isPresent` (command "-h")) then exitWithUsage usage else do maxDepth <- args `getArgOrExit` (argument "max-context-depth") if args `isPresent` (command "all") then do inputDir <- args `getArgOrExit` (argument "inputDir") outputDir <- args `getArgOrExit` (argument "outputDir") runAll (read maxDepth) inputDir outputDir else do maxDepth <- args `getArgOrExit` (argument "max-context-depth") file <- args `getArgOrExit` (argument "file") run (read maxDepth) file run :: Int -> String -> IO () run maxDepth path = do p <- happy . alex <$> readFile path let (freshLabel, t) = sem_Program p 0 let (startLabel, finishLabel) = (freshLabel, freshLabel + 1) let (edges, entryPoint, errors, exitLabels, nodes, _) = sem_Program' t let extraNodes = (startLabel, S (Skip' startLabel)) : (finishLabel, S (Skip' finishLabel)) : nodes let extraEdges = (startLabel, entryPoint, "") : map (\el -> (el, finishLabel, "")) exitLabels ++ edges let cfg = mkGraph extraNodes extraEdges :: Gr ProcOrStat String let nodeMap = M.fromList extraNodes if null errors then do putStrLn "CP ANALYSIS:" let cpAnalysis = fmap (\(x, y) -> (show x, show y)) (CP.runAnalysis maxDepth (emap (const ()) cfg) startLabel) putStrLn $ renderAnalysis cpAnalysis nodeMap (map fst extraNodes) extraEdges putStrLn "" putStrLn "SLV ANALYSIS:" let slvAnalysis = fmap (\(x, y) -> (show y, show x)) $ (SLV.runAnalysis (emap (const ()) cfg) finishLabel) putStrLn $ renderAnalysis slvAnalysis nodeMap (map fst extraNodes) extraEdges putStrLn "" else putStrLn $ "Errors: " ++ show errors runAll :: Int -> String -> String -> IO () runAll maxDepth inputDir outputDir = do dirEntries <- listDirectory inputDir inputFiles <- filterM doesFileExist $ map (combine inputDir) dirEntries createDirectoryIfMissing True outputDir sequence_ $ map (\inputFile -> let name = takeBaseName inputFile cpFilePath = (combine outputDir (name ++ ".cp")) slvFilePath = (combine outputDir (name ++ ".slv")) in createGraphs maxDepth inputFile cpFilePath slvFilePath) inputFiles where createGraphs :: Int -> String -> String -> String -> IO () createGraphs maxDepth inputfile cpgraph slvgraph = do p <- happy . alex <$> readFile inputfile let (freshLabel, t) = sem_Program p 0 let (startLabel, finishLabel) = (freshLabel, freshLabel + 1) let (edges, entryPoint, errors, exitLabels, nodes, _) = sem_Program' t let extraNodes = (startLabel, S (Skip' startLabel)) : (finishLabel, S (Skip' finishLabel)) : nodes let extraEdges = (startLabel, entryPoint, "") : map (\el -> (el, finishLabel, "")) exitLabels ++ edges let cfg = mkGraph extraNodes extraEdges :: Gr ProcOrStat String let nodeMap = M.fromList extraNodes if null errors then do let cpAnalysis = fmap (\(x, y) -> (show x, show y)) (CP.runAnalysis maxDepth (emap (const ()) cfg) startLabel) writeFile cpgraph $ renderAnalysis cpAnalysis nodeMap (map fst extraNodes) extraEdges let slvAnalysis = fmap (\(x, y) -> (show y, show x)) $ (SLV.runAnalysis (emap (const ()) cfg) finishLabel) writeFile slvgraph $ renderAnalysis slvAnalysis nodeMap (map fst extraNodes) extraEdges else putStrLn $ "Errors when analyzing '" ++ inputfile ++ "': " ++ show errors renderGraph :: Gr String String -> String renderGraph g = Text.unpack $ renderDot $ toDot $ graphToDot params g where params = nonClusteredParams { fmtNode = fn, fmtEdge = fe } fn (i, l) = [toLabel (Text.append (Text.pack ("Node id: " ++ show i ++ " \n")) (Text.pack l))] fe (_, _, l) = [toLabel l] -- Transforms the analysis results in a graph where each node shows the results of the analysis, -- as well as the statement or procedure in question renderAnalysis :: Map Int (String, String) -> Map Int ProcOrStat -> [Int] -> [(Int, Int, String)] -> String renderAnalysis analysis realNodes nodes edges = let anNodes = map renderNode nodes graph = mkGraph anNodes edges in renderGraph graph where renderNode label = let (open, closed) = analysis M.! label procOrStat = show $ realNodes M.! label in (label, unlines [open, procOrStat, closed])
aochagavia/CompilerConstruction
mf/src/Main.hs
apache-2.0
6,034
0
22
1,328
2,007
1,056
951
107
3
{-# LANGUAGE OverloadedStrings, TypeFamilies, DeriveFunctor, GADTs, TemplateHaskell, FunctionalDependencies, FlexibleInstances, NoMonomorphismRestriction, DeriveGeneric,DeriveDataTypeable, DataKinds #-} module TF.Type.StackEffect where import TF.ForthTypes import TF.TH import Lens.Simple import Control.Lens (makeWrapped) -- type DefiningOrNot = Either DefiningArg StreamArg data DefiningOrNot = Defining DefiningArg | NotDefining StreamArg deriving (Show,Eq,Ord) -- type IndexedStackType = (DataType, Maybe Int) data IndexedStackType = IndexedStackType { stackType :: DataType , typeIndex :: (Maybe Int) } deriving (Show,Eq,Ord) type Identifier = Int type ClassName = String newtype Intersection = Intersection Bool deriving (Eq,Show,Ord) type DataStackEffect = [StackEffect] data MultiStackEffect = MultiStackEffect { _steffsMultiEffects :: DataStackEffect } deriving (Show, Eq) data StackEffectsWI = StackEffectsWI { stefwiMultiEffects :: MultiStackEffect , stefwiIntersection :: Intersection } deriving (Show,Eq) type StackEffectPair = (StackEffect, StackEffect) data StackEffectPairsWI = StackEffectWI { stefwiStackEffectPairs :: [StackEffectPair] , stefwiIntersect :: Intersections } deriving (Show,Eq,Ord) data Intersections = Intersections { compileEffect :: Bool , execEffect :: Bool } deriving (Show,Eq,Ord) data DataArgOrStreamArg dataArg = DataArg dataArg | NonDataArg DefiningOrNot deriving (Show, Eq) type StackArg = DataArgOrStreamArg [IndexedStackType] type StackArg' = DataArgOrStreamArg IndexedStackType type StackArg'' = DataArgOrStreamArg IndexedStackType type SingleSemiEffect = [StackArg] type SemiEffect = [SingleSemiEffect] -- type DefiningOrNot' a = Either a a -- _Defining = _Left -- _NotDefining = _Right data DataType = Dynamic | WildcardWrapper | Wildcard | UnknownType Identifier | Reference DataType | NoReference BasicType deriving (Show,Eq,Ord) type UniqueArg = Int data RuntimeSpecification = NoR | UnknownR UniqueArg | KnownR StackEffect | ResolvedR UniqueArg StackEffect deriving (Show,Eq,Ord) data ExecutionToken = ExecutionToken { symbol :: TypeSymbol , exectokenRuntimeSpecified :: Maybe RuntimeSpecification } deriving (Show,Ord,Eq) data BasicType = ClassType ClassName | PrimType PrimType | ExecutionType ExecutionToken deriving (Show,Eq,Ord) data ArgInfo a = ArgInfo { argName :: String , resolved :: Maybe String , endDelimiter :: Maybe String } deriving (Show,Eq,Ord) newtype ForthEffect = ForthEffect ([StackEffectPair], Intersections) deriving (Show, Eq,Ord) data DefiningArg = DefiningArg { definingArgInfo :: ArgInfo StackEffect , argType :: Maybe IndexedStackType -- , runtimeEffect :: Maybe [(StackEffect,StackEffect)] , runtimeEffect :: Maybe ForthEffect -- TODO -- -- replace wiht maybe runtimespecification } deriving (Show,Eq,Ord) data StreamArg = StreamArg { streamArgInfo :: ArgInfo RuntimeSpecification , runtimeSpecified :: Maybe RuntimeSpecification } deriving (Show,Eq,Ord) data StackEffect = StackEffect { before :: [IndexedStackType] , streamArgs :: [DefiningOrNot] , after :: [IndexedStackType] } deriving (Show, Eq,Ord) makeLens ''StackEffect makeTraversals ''DataType makeTraversals ''BasicType makeLens ''ArgInfo makeLens ''DefiningArg makeLens ''StreamArg makeTraversals ''RuntimeSpecification makeTraversals ''DefiningOrNot makeLens ''ExecutionToken makeLens ''IndexedStackType makeWrapped ''MultiStackEffect makeLens ''StackEffectsWI makeLens ''StackEffectPairsWI makeWrapped ''Intersection makeLens ''Intersections makeWrapped ''ForthEffect
sleepomeno/TForth
src/TF/Type/StackEffect.hs
apache-2.0
4,161
0
10
1,050
888
494
394
90
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} module Test.SCInstances where import Control.Monad import qualified Data.Text as T import qualified Data.Vector as V import Test.SmallCheck.Series import Test.SmallCheck.Series.Instances () import qualified Codec.Packstream.Marker as PSM import qualified Codec.Packstream.Signature as PSS newtype Marker = MkMarker { marker :: PSM.Marker } deriving (Eq, Show) instance Monad m => Serial m Marker where series = generate $ \d -> map MkMarker $ take d PSM.allMarkers newtype Signature = MkSignature { signature :: PSS.Signature } deriving (Eq, Show) instance Monad m => Serial m Signature where series = liftM (MkSignature . PSS.signature) series newtype Entry a = MkEntry { unEntry :: (T.Text, a) } deriving (Eq, Show) instance Serial m a => Serial m (Entry a) where series = cons2 p where p a b = MkEntry (a, b) newtype Vec a = MkVec { vector :: V.Vector a } deriving (Eq, Show) instance Serial m [a] => Serial m (Vec a) where series = fmap (MkVec . V.fromList) series
boggle/neo4j-haskell-driver
test/Test/SCInstances.hs
apache-2.0
1,233
0
10
290
362
210
152
24
0
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QListView.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:23 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QListView ( QqListView(..) ,batchSize ,clearPropertyFlags ,flow ,qgridSize, gridSize ,isSelectionRectVisible ,isWrapping ,layoutMode ,movement ,setBatchSize ,setFlow ,qsetGridSize, setGridSize ,setLayoutMode ,setMovement ,setSelectionRectVisible ,setUniformItemSizes ,uniformItemSizes ,qListView_delete ,qListView_deleteLater ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QItemSelectionModel import Qtc.Enums.Gui.QAbstractItemView import Qtc.Enums.Gui.QPaintDevice import Qtc.Enums.Core.Qt import Qtc.Enums.Gui.QListView import Qtc.Enums.Gui.QAbstractItemDelegate import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui instance QuserMethod (QListView ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QListView_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QListView_userMethod" qtc_QListView_userMethod :: Ptr (TQListView a) -> CInt -> IO () instance QuserMethod (QListViewSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QListView_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QListView ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QListView_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QListView_userMethodVariant" qtc_QListView_userMethodVariant :: Ptr (TQListView a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QListViewSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QListView_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj class QqListView x1 where qListView :: x1 -> IO (QListView ()) instance QqListView (()) where qListView () = withQListViewResult $ qtc_QListView foreign import ccall "qtc_QListView" qtc_QListView :: IO (Ptr (TQListView ())) instance QqListView ((QWidget t1)) where qListView (x1) = withQListViewResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QListView1 cobj_x1 foreign import ccall "qtc_QListView1" qtc_QListView1 :: Ptr (TQWidget t1) -> IO (Ptr (TQListView ())) batchSize :: QListView a -> (()) -> IO (Int) batchSize x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_batchSize cobj_x0 foreign import ccall "qtc_QListView_batchSize" qtc_QListView_batchSize :: Ptr (TQListView a) -> IO CInt clearPropertyFlags :: QListView a -> (()) -> IO () clearPropertyFlags x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_clearPropertyFlags cobj_x0 foreign import ccall "qtc_QListView_clearPropertyFlags" qtc_QListView_clearPropertyFlags :: Ptr (TQListView a) -> IO () instance QqcontentsSize (QListView ()) (()) where qcontentsSize x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_contentsSize cobj_x0 foreign import ccall "qtc_QListView_contentsSize" qtc_QListView_contentsSize :: Ptr (TQListView a) -> IO (Ptr (TQSize ())) instance QqcontentsSize (QListViewSc a) (()) where qcontentsSize x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_contentsSize cobj_x0 instance QcontentsSize (QListView ()) (()) where contentsSize x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_contentsSize_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QListView_contentsSize_qth" qtc_QListView_contentsSize_qth :: Ptr (TQListView a) -> Ptr CInt -> Ptr CInt -> IO () instance QcontentsSize (QListViewSc a) (()) where contentsSize x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_contentsSize_qth cobj_x0 csize_ret_w csize_ret_h instance QcurrentChanged (QListView ()) ((QModelIndex t1, QModelIndex t2)) where currentChanged x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QListView_currentChanged cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QListView_currentChanged" qtc_QListView_currentChanged :: Ptr (TQListView a) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO () instance QcurrentChanged (QListViewSc a) ((QModelIndex t1, QModelIndex t2)) where currentChanged x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QListView_currentChanged cobj_x0 cobj_x1 cobj_x2 instance QdataChanged (QListView ()) ((QModelIndex t1, QModelIndex t2)) where dataChanged x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QListView_dataChanged cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QListView_dataChanged" qtc_QListView_dataChanged :: Ptr (TQListView a) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO () instance QdataChanged (QListViewSc a) ((QModelIndex t1, QModelIndex t2)) where dataChanged x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QListView_dataChanged cobj_x0 cobj_x1 cobj_x2 instance QdoItemsLayout (QListView ()) (()) where doItemsLayout x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_doItemsLayout_h cobj_x0 foreign import ccall "qtc_QListView_doItemsLayout_h" qtc_QListView_doItemsLayout_h :: Ptr (TQListView a) -> IO () instance QdoItemsLayout (QListViewSc a) (()) where doItemsLayout x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_doItemsLayout_h cobj_x0 instance QdragLeaveEvent (QListView ()) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_dragLeaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_dragLeaveEvent_h" qtc_QListView_dragLeaveEvent_h :: Ptr (TQListView a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent (QListViewSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_dragLeaveEvent_h cobj_x0 cobj_x1 instance QdragMoveEvent (QListView ()) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_dragMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_dragMoveEvent_h" qtc_QListView_dragMoveEvent_h :: Ptr (TQListView a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent (QListViewSc a) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_dragMoveEvent_h cobj_x0 cobj_x1 instance QdropEvent (QListView ()) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_dropEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_dropEvent_h" qtc_QListView_dropEvent_h :: Ptr (TQListView a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent (QListViewSc a) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_dropEvent_h cobj_x0 cobj_x1 instance Qevent (QListView ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_event_h" qtc_QListView_event_h :: Ptr (TQListView a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QListViewSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_event_h cobj_x0 cobj_x1 flow :: QListView a -> (()) -> IO (Flow) flow x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_flow cobj_x0 foreign import ccall "qtc_QListView_flow" qtc_QListView_flow :: Ptr (TQListView a) -> IO CLong qgridSize :: QListView a -> (()) -> IO (QSize ()) qgridSize x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_gridSize cobj_x0 foreign import ccall "qtc_QListView_gridSize" qtc_QListView_gridSize :: Ptr (TQListView a) -> IO (Ptr (TQSize ())) gridSize :: QListView a -> (()) -> IO (Size) gridSize x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_gridSize_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QListView_gridSize_qth" qtc_QListView_gridSize_qth :: Ptr (TQListView a) -> Ptr CInt -> Ptr CInt -> IO () instance QhorizontalOffset (QListView ()) (()) where horizontalOffset x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_horizontalOffset cobj_x0 foreign import ccall "qtc_QListView_horizontalOffset" qtc_QListView_horizontalOffset :: Ptr (TQListView a) -> IO CInt instance QhorizontalOffset (QListViewSc a) (()) where horizontalOffset x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_horizontalOffset cobj_x0 instance QindexAt (QListView ()) ((Point)) where indexAt x0 (x1) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QListView_indexAt_qth_h cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QListView_indexAt_qth_h" qtc_QListView_indexAt_qth_h :: Ptr (TQListView a) -> CInt -> CInt -> IO (Ptr (TQModelIndex ())) instance QindexAt (QListViewSc a) ((Point)) where indexAt x0 (x1) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QListView_indexAt_qth_h cobj_x0 cpoint_x1_x cpoint_x1_y instance QqindexAt (QListView ()) ((QPoint t1)) where qindexAt x0 (x1) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_indexAt_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_indexAt_h" qtc_QListView_indexAt_h :: Ptr (TQListView a) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex ())) instance QqindexAt (QListViewSc a) ((QPoint t1)) where qindexAt x0 (x1) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_indexAt_h cobj_x0 cobj_x1 instance QinternalDrag (QListView ()) ((DropActions)) where internalDrag x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_internalDrag cobj_x0 (toCLong $ qFlags_toInt x1) foreign import ccall "qtc_QListView_internalDrag" qtc_QListView_internalDrag :: Ptr (TQListView a) -> CLong -> IO () instance QinternalDrag (QListViewSc a) ((DropActions)) where internalDrag x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_internalDrag cobj_x0 (toCLong $ qFlags_toInt x1) instance QinternalDrop (QListView ()) ((QDropEvent t1)) where internalDrop x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_internalDrop cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_internalDrop" qtc_QListView_internalDrop :: Ptr (TQListView a) -> Ptr (TQDropEvent t1) -> IO () instance QinternalDrop (QListViewSc a) ((QDropEvent t1)) where internalDrop x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_internalDrop cobj_x0 cobj_x1 instance QisIndexHidden (QListView ()) ((QModelIndex t1)) where isIndexHidden x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_isIndexHidden cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_isIndexHidden" qtc_QListView_isIndexHidden :: Ptr (TQListView a) -> Ptr (TQModelIndex t1) -> IO CBool instance QisIndexHidden (QListViewSc a) ((QModelIndex t1)) where isIndexHidden x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_isIndexHidden cobj_x0 cobj_x1 instance QisRowHidden (QListView a) ((Int)) where isRowHidden x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_isRowHidden cobj_x0 (toCInt x1) foreign import ccall "qtc_QListView_isRowHidden" qtc_QListView_isRowHidden :: Ptr (TQListView a) -> CInt -> IO CBool isSelectionRectVisible :: QListView a -> (()) -> IO (Bool) isSelectionRectVisible x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_isSelectionRectVisible cobj_x0 foreign import ccall "qtc_QListView_isSelectionRectVisible" qtc_QListView_isSelectionRectVisible :: Ptr (TQListView a) -> IO CBool isWrapping :: QListView a -> (()) -> IO (Bool) isWrapping x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_isWrapping cobj_x0 foreign import ccall "qtc_QListView_isWrapping" qtc_QListView_isWrapping :: Ptr (TQListView a) -> IO CBool layoutMode :: QListView a -> (()) -> IO (LayoutMode) layoutMode x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_layoutMode cobj_x0 foreign import ccall "qtc_QListView_layoutMode" qtc_QListView_layoutMode :: Ptr (TQListView a) -> IO CLong instance QmodelColumn (QListView a) (()) where modelColumn x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_modelColumn cobj_x0 foreign import ccall "qtc_QListView_modelColumn" qtc_QListView_modelColumn :: Ptr (TQListView a) -> IO CInt instance QmouseMoveEvent (QListView ()) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_mouseMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_mouseMoveEvent_h" qtc_QListView_mouseMoveEvent_h :: Ptr (TQListView a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent (QListViewSc a) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_mouseMoveEvent_h cobj_x0 cobj_x1 instance QmouseReleaseEvent (QListView ()) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_mouseReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_mouseReleaseEvent_h" qtc_QListView_mouseReleaseEvent_h :: Ptr (TQListView a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent (QListViewSc a) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_mouseReleaseEvent_h cobj_x0 cobj_x1 instance QmoveCursor (QListView ()) ((CursorAction, KeyboardModifiers)) (IO (QModelIndex ())) where moveCursor x0 (x1, x2) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_moveCursor cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2) foreign import ccall "qtc_QListView_moveCursor" qtc_QListView_moveCursor :: Ptr (TQListView a) -> CLong -> CLong -> IO (Ptr (TQModelIndex ())) instance QmoveCursor (QListViewSc a) ((CursorAction, KeyboardModifiers)) (IO (QModelIndex ())) where moveCursor x0 (x1, x2) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_moveCursor cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2) movement :: QListView a -> (()) -> IO (Movement) movement x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_movement cobj_x0 foreign import ccall "qtc_QListView_movement" qtc_QListView_movement :: Ptr (TQListView a) -> IO CLong instance QpaintEvent (QListView ()) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_paintEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_paintEvent_h" qtc_QListView_paintEvent_h :: Ptr (TQListView a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent (QListViewSc a) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_paintEvent_h cobj_x0 cobj_x1 instance QqrectForIndex (QListView ()) ((QModelIndex t1)) where qrectForIndex x0 (x1) = withQRectResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_rectForIndex cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_rectForIndex" qtc_QListView_rectForIndex :: Ptr (TQListView a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect ())) instance QqrectForIndex (QListViewSc a) ((QModelIndex t1)) where qrectForIndex x0 (x1) = withQRectResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_rectForIndex cobj_x0 cobj_x1 instance QrectForIndex (QListView ()) ((QModelIndex t1)) where rectForIndex x0 (x1) = withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_rectForIndex_qth cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h foreign import ccall "qtc_QListView_rectForIndex_qth" qtc_QListView_rectForIndex_qth :: Ptr (TQListView a) -> Ptr (TQModelIndex t1) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO () instance QrectForIndex (QListViewSc a) ((QModelIndex t1)) where rectForIndex x0 (x1) = withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_rectForIndex_qth cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h instance Qreset (QListView ()) (()) (IO ()) where reset x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_reset_h cobj_x0 foreign import ccall "qtc_QListView_reset_h" qtc_QListView_reset_h :: Ptr (TQListView a) -> IO () instance Qreset (QListViewSc a) (()) (IO ()) where reset x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_reset_h cobj_x0 instance QresizeContents (QListView ()) ((Int, Int)) where resizeContents x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_resizeContents cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QListView_resizeContents" qtc_QListView_resizeContents :: Ptr (TQListView a) -> CInt -> CInt -> IO () instance QresizeContents (QListViewSc a) ((Int, Int)) where resizeContents x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_resizeContents cobj_x0 (toCInt x1) (toCInt x2) instance QresizeEvent (QListView ()) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_resizeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_resizeEvent_h" qtc_QListView_resizeEvent_h :: Ptr (TQListView a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent (QListViewSc a) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_resizeEvent_h cobj_x0 cobj_x1 instance QresizeMode (QListView a) (()) (IO (QListViewResizeMode)) where resizeMode x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_resizeMode cobj_x0 foreign import ccall "qtc_QListView_resizeMode" qtc_QListView_resizeMode :: Ptr (TQListView a) -> IO CLong instance QrowsAboutToBeRemoved (QListView ()) ((QModelIndex t1, Int, Int)) where rowsAboutToBeRemoved x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_rowsAboutToBeRemoved cobj_x0 cobj_x1 (toCInt x2) (toCInt x3) foreign import ccall "qtc_QListView_rowsAboutToBeRemoved" qtc_QListView_rowsAboutToBeRemoved :: Ptr (TQListView a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO () instance QrowsAboutToBeRemoved (QListViewSc a) ((QModelIndex t1, Int, Int)) where rowsAboutToBeRemoved x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_rowsAboutToBeRemoved cobj_x0 cobj_x1 (toCInt x2) (toCInt x3) instance QrowsInserted (QListView ()) ((QModelIndex t1, Int, Int)) where rowsInserted x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_rowsInserted cobj_x0 cobj_x1 (toCInt x2) (toCInt x3) foreign import ccall "qtc_QListView_rowsInserted" qtc_QListView_rowsInserted :: Ptr (TQListView a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO () instance QrowsInserted (QListViewSc a) ((QModelIndex t1, Int, Int)) where rowsInserted x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_rowsInserted cobj_x0 cobj_x1 (toCInt x2) (toCInt x3) instance QscrollContentsBy (QListView ()) ((Int, Int)) where scrollContentsBy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_scrollContentsBy_h cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QListView_scrollContentsBy_h" qtc_QListView_scrollContentsBy_h :: Ptr (TQListView a) -> CInt -> CInt -> IO () instance QscrollContentsBy (QListViewSc a) ((Int, Int)) where scrollContentsBy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_scrollContentsBy_h cobj_x0 (toCInt x1) (toCInt x2) instance QscrollTo (QListView a) ((QModelIndex t1)) where scrollTo x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_scrollTo cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_scrollTo" qtc_QListView_scrollTo :: Ptr (TQListView a) -> Ptr (TQModelIndex t1) -> IO () instance QscrollTo (QListView ()) ((QModelIndex t1, ScrollHint)) where scrollTo x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_scrollTo1_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QListView_scrollTo1_h" qtc_QListView_scrollTo1_h :: Ptr (TQListView a) -> Ptr (TQModelIndex t1) -> CLong -> IO () instance QscrollTo (QListViewSc a) ((QModelIndex t1, ScrollHint)) where scrollTo x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_scrollTo1_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) instance QselectedIndexes (QListView ()) (()) where selectedIndexes x0 () = withQListObjectRefResult $ \arr -> withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_selectedIndexes cobj_x0 arr foreign import ccall "qtc_QListView_selectedIndexes" qtc_QListView_selectedIndexes :: Ptr (TQListView a) -> Ptr (Ptr (TQModelIndex ())) -> IO CInt instance QselectedIndexes (QListViewSc a) (()) where selectedIndexes x0 () = withQListObjectRefResult $ \arr -> withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_selectedIndexes cobj_x0 arr instance QselectionChanged (QListView ()) ((QItemSelection t1, QItemSelection t2)) where selectionChanged x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QListView_selectionChanged cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QListView_selectionChanged" qtc_QListView_selectionChanged :: Ptr (TQListView a) -> Ptr (TQItemSelection t1) -> Ptr (TQItemSelection t2) -> IO () instance QselectionChanged (QListViewSc a) ((QItemSelection t1, QItemSelection t2)) where selectionChanged x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QListView_selectionChanged cobj_x0 cobj_x1 cobj_x2 setBatchSize :: QListView a -> ((Int)) -> IO () setBatchSize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setBatchSize cobj_x0 (toCInt x1) foreign import ccall "qtc_QListView_setBatchSize" qtc_QListView_setBatchSize :: Ptr (TQListView a) -> CInt -> IO () setFlow :: QListView a -> ((Flow)) -> IO () setFlow x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setFlow cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QListView_setFlow" qtc_QListView_setFlow :: Ptr (TQListView a) -> CLong -> IO () qsetGridSize :: QListView a -> ((QSize t1)) -> IO () qsetGridSize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_setGridSize cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_setGridSize" qtc_QListView_setGridSize :: Ptr (TQListView a) -> Ptr (TQSize t1) -> IO () setGridSize :: QListView a -> ((Size)) -> IO () setGridSize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QListView_setGridSize_qth cobj_x0 csize_x1_w csize_x1_h foreign import ccall "qtc_QListView_setGridSize_qth" qtc_QListView_setGridSize_qth :: Ptr (TQListView a) -> CInt -> CInt -> IO () setLayoutMode :: QListView a -> ((LayoutMode)) -> IO () setLayoutMode x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setLayoutMode cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QListView_setLayoutMode" qtc_QListView_setLayoutMode :: Ptr (TQListView a) -> CLong -> IO () instance QsetModelColumn (QListView a) ((Int)) where setModelColumn x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setModelColumn cobj_x0 (toCInt x1) foreign import ccall "qtc_QListView_setModelColumn" qtc_QListView_setModelColumn :: Ptr (TQListView a) -> CInt -> IO () setMovement :: QListView a -> ((Movement)) -> IO () setMovement x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setMovement cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QListView_setMovement" qtc_QListView_setMovement :: Ptr (TQListView a) -> CLong -> IO () instance QsetPositionForIndex (QListView ()) ((Point, QModelIndex t2)) where setPositionForIndex x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> withObjectPtr x2 $ \cobj_x2 -> qtc_QListView_setPositionForIndex_qth cobj_x0 cpoint_x1_x cpoint_x1_y cobj_x2 foreign import ccall "qtc_QListView_setPositionForIndex_qth" qtc_QListView_setPositionForIndex_qth :: Ptr (TQListView a) -> CInt -> CInt -> Ptr (TQModelIndex t2) -> IO () instance QsetPositionForIndex (QListViewSc a) ((Point, QModelIndex t2)) where setPositionForIndex x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> withObjectPtr x2 $ \cobj_x2 -> qtc_QListView_setPositionForIndex_qth cobj_x0 cpoint_x1_x cpoint_x1_y cobj_x2 instance QqsetPositionForIndex (QListView ()) ((QPoint t1, QModelIndex t2)) where qsetPositionForIndex x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QListView_setPositionForIndex cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QListView_setPositionForIndex" qtc_QListView_setPositionForIndex :: Ptr (TQListView a) -> Ptr (TQPoint t1) -> Ptr (TQModelIndex t2) -> IO () instance QqsetPositionForIndex (QListViewSc a) ((QPoint t1, QModelIndex t2)) where qsetPositionForIndex x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QListView_setPositionForIndex cobj_x0 cobj_x1 cobj_x2 instance QsetResizeMode (QListView a) ((QListViewResizeMode)) where setResizeMode x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setResizeMode cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QListView_setResizeMode" qtc_QListView_setResizeMode :: Ptr (TQListView a) -> CLong -> IO () instance QsetRootIndex (QListView ()) ((QModelIndex t1)) where setRootIndex x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_setRootIndex_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_setRootIndex_h" qtc_QListView_setRootIndex_h :: Ptr (TQListView a) -> Ptr (TQModelIndex t1) -> IO () instance QsetRootIndex (QListViewSc a) ((QModelIndex t1)) where setRootIndex x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_setRootIndex_h cobj_x0 cobj_x1 instance QsetRowHidden (QListView a) ((Int, Bool)) where setRowHidden x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setRowHidden cobj_x0 (toCInt x1) (toCBool x2) foreign import ccall "qtc_QListView_setRowHidden" qtc_QListView_setRowHidden :: Ptr (TQListView a) -> CInt -> CBool -> IO () instance QqsetSelection (QListView ()) ((QRect t1, SelectionFlags)) where qsetSelection x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_setSelection cobj_x0 cobj_x1 (toCLong $ qFlags_toInt x2) foreign import ccall "qtc_QListView_setSelection" qtc_QListView_setSelection :: Ptr (TQListView a) -> Ptr (TQRect t1) -> CLong -> IO () instance QqsetSelection (QListViewSc a) ((QRect t1, SelectionFlags)) where qsetSelection x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_setSelection cobj_x0 cobj_x1 (toCLong $ qFlags_toInt x2) instance QsetSelection (QListView ()) ((Rect, SelectionFlags)) where setSelection x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QListView_setSelection_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h (toCLong $ qFlags_toInt x2) foreign import ccall "qtc_QListView_setSelection_qth" qtc_QListView_setSelection_qth :: Ptr (TQListView a) -> CInt -> CInt -> CInt -> CInt -> CLong -> IO () instance QsetSelection (QListViewSc a) ((Rect, SelectionFlags)) where setSelection x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QListView_setSelection_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h (toCLong $ qFlags_toInt x2) setSelectionRectVisible :: QListView a -> ((Bool)) -> IO () setSelectionRectVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setSelectionRectVisible cobj_x0 (toCBool x1) foreign import ccall "qtc_QListView_setSelectionRectVisible" qtc_QListView_setSelectionRectVisible :: Ptr (TQListView a) -> CBool -> IO () instance QsetSpacing (QListView ()) ((Int)) where setSpacing x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setSpacing cobj_x0 (toCInt x1) foreign import ccall "qtc_QListView_setSpacing" qtc_QListView_setSpacing :: Ptr (TQListView a) -> CInt -> IO () instance QsetSpacing (QListViewSc a) ((Int)) where setSpacing x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setSpacing cobj_x0 (toCInt x1) setUniformItemSizes :: QListView a -> ((Bool)) -> IO () setUniformItemSizes x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setUniformItemSizes cobj_x0 (toCBool x1) foreign import ccall "qtc_QListView_setUniformItemSizes" qtc_QListView_setUniformItemSizes :: Ptr (TQListView a) -> CBool -> IO () instance QsetViewMode (QListView a) ((QListViewViewMode)) where setViewMode x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setViewMode cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QListView_setViewMode" qtc_QListView_setViewMode :: Ptr (TQListView a) -> CLong -> IO () instance QsetWordWrap (QListView a) ((Bool)) where setWordWrap x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setWordWrap cobj_x0 (toCBool x1) foreign import ccall "qtc_QListView_setWordWrap" qtc_QListView_setWordWrap :: Ptr (TQListView a) -> CBool -> IO () instance QsetWrapping (QListView a) ((Bool)) where setWrapping x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setWrapping cobj_x0 (toCBool x1) foreign import ccall "qtc_QListView_setWrapping" qtc_QListView_setWrapping :: Ptr (TQListView a) -> CBool -> IO () instance Qspacing (QListView ()) (()) where spacing x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_spacing cobj_x0 foreign import ccall "qtc_QListView_spacing" qtc_QListView_spacing :: Ptr (TQListView a) -> IO CInt instance Qspacing (QListViewSc a) (()) where spacing x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_spacing cobj_x0 instance QstartDrag (QListView ()) ((DropActions)) where startDrag x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_startDrag cobj_x0 (toCLong $ qFlags_toInt x1) foreign import ccall "qtc_QListView_startDrag" qtc_QListView_startDrag :: Ptr (TQListView a) -> CLong -> IO () instance QstartDrag (QListViewSc a) ((DropActions)) where startDrag x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_startDrag cobj_x0 (toCLong $ qFlags_toInt x1) instance QtimerEvent (QListView ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_timerEvent" qtc_QListView_timerEvent :: Ptr (TQListView a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QListViewSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_timerEvent cobj_x0 cobj_x1 uniformItemSizes :: QListView a -> (()) -> IO (Bool) uniformItemSizes x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_uniformItemSizes cobj_x0 foreign import ccall "qtc_QListView_uniformItemSizes" qtc_QListView_uniformItemSizes :: Ptr (TQListView a) -> IO CBool instance QupdateGeometries (QListView ()) (()) where updateGeometries x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_updateGeometries cobj_x0 foreign import ccall "qtc_QListView_updateGeometries" qtc_QListView_updateGeometries :: Ptr (TQListView a) -> IO () instance QupdateGeometries (QListViewSc a) (()) where updateGeometries x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_updateGeometries cobj_x0 instance QverticalOffset (QListView ()) (()) where verticalOffset x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_verticalOffset cobj_x0 foreign import ccall "qtc_QListView_verticalOffset" qtc_QListView_verticalOffset :: Ptr (TQListView a) -> IO CInt instance QverticalOffset (QListViewSc a) (()) where verticalOffset x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_verticalOffset cobj_x0 instance QviewMode (QListView a) (()) (IO (QListViewViewMode)) where viewMode x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_viewMode cobj_x0 foreign import ccall "qtc_QListView_viewMode" qtc_QListView_viewMode :: Ptr (TQListView a) -> IO CLong instance QviewOptions (QListView ()) (()) where viewOptions x0 () = withQStyleOptionViewItemResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_viewOptions cobj_x0 foreign import ccall "qtc_QListView_viewOptions" qtc_QListView_viewOptions :: Ptr (TQListView a) -> IO (Ptr (TQStyleOptionViewItem ())) instance QviewOptions (QListViewSc a) (()) where viewOptions x0 () = withQStyleOptionViewItemResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_viewOptions cobj_x0 instance QqvisualRect (QListView ()) ((QModelIndex t1)) where qvisualRect x0 (x1) = withQRectResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_visualRect_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_visualRect_h" qtc_QListView_visualRect_h :: Ptr (TQListView a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect ())) instance QqvisualRect (QListViewSc a) ((QModelIndex t1)) where qvisualRect x0 (x1) = withQRectResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_visualRect_h cobj_x0 cobj_x1 instance QvisualRect (QListView ()) ((QModelIndex t1)) where visualRect x0 (x1) = withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_visualRect_qth_h cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h foreign import ccall "qtc_QListView_visualRect_qth_h" qtc_QListView_visualRect_qth_h :: Ptr (TQListView a) -> Ptr (TQModelIndex t1) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO () instance QvisualRect (QListViewSc a) ((QModelIndex t1)) where visualRect x0 (x1) = withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_visualRect_qth_h cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h instance QvisualRegionForSelection (QListView ()) ((QItemSelection t1)) where visualRegionForSelection x0 (x1) = withQRegionResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_visualRegionForSelection cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_visualRegionForSelection" qtc_QListView_visualRegionForSelection :: Ptr (TQListView a) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion ())) instance QvisualRegionForSelection (QListViewSc a) ((QItemSelection t1)) where visualRegionForSelection x0 (x1) = withQRegionResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_visualRegionForSelection cobj_x0 cobj_x1 instance QwordWrap (QListView a) (()) where wordWrap x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_wordWrap cobj_x0 foreign import ccall "qtc_QListView_wordWrap" qtc_QListView_wordWrap :: Ptr (TQListView a) -> IO CBool qListView_delete :: QListView a -> IO () qListView_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_delete cobj_x0 foreign import ccall "qtc_QListView_delete" qtc_QListView_delete :: Ptr (TQListView a) -> IO () qListView_deleteLater :: QListView a -> IO () qListView_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_deleteLater cobj_x0 foreign import ccall "qtc_QListView_deleteLater" qtc_QListView_deleteLater :: Ptr (TQListView a) -> IO () instance QcloseEditor (QListView ()) ((QWidget t1, EndEditHint)) where closeEditor x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_closeEditor cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QListView_closeEditor" qtc_QListView_closeEditor :: Ptr (TQListView a) -> Ptr (TQWidget t1) -> CLong -> IO () instance QcloseEditor (QListViewSc a) ((QWidget t1, EndEditHint)) where closeEditor x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_closeEditor cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) instance QcommitData (QListView ()) ((QWidget t1)) where commitData x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_commitData cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_commitData" qtc_QListView_commitData :: Ptr (TQListView a) -> Ptr (TQWidget t1) -> IO () instance QcommitData (QListViewSc a) ((QWidget t1)) where commitData x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_commitData cobj_x0 cobj_x1 instance QdirtyRegionOffset (QListView ()) (()) where dirtyRegionOffset x0 () = withPointResult $ \cpoint_ret_x cpoint_ret_y -> withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_dirtyRegionOffset_qth cobj_x0 cpoint_ret_x cpoint_ret_y foreign import ccall "qtc_QListView_dirtyRegionOffset_qth" qtc_QListView_dirtyRegionOffset_qth :: Ptr (TQListView a) -> Ptr CInt -> Ptr CInt -> IO () instance QdirtyRegionOffset (QListViewSc a) (()) where dirtyRegionOffset x0 () = withPointResult $ \cpoint_ret_x cpoint_ret_y -> withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_dirtyRegionOffset_qth cobj_x0 cpoint_ret_x cpoint_ret_y instance QqdirtyRegionOffset (QListView ()) (()) where qdirtyRegionOffset x0 () = withQPointResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_dirtyRegionOffset cobj_x0 foreign import ccall "qtc_QListView_dirtyRegionOffset" qtc_QListView_dirtyRegionOffset :: Ptr (TQListView a) -> IO (Ptr (TQPoint ())) instance QqdirtyRegionOffset (QListViewSc a) (()) where qdirtyRegionOffset x0 () = withQPointResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_dirtyRegionOffset cobj_x0 instance QdoAutoScroll (QListView ()) (()) where doAutoScroll x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_doAutoScroll cobj_x0 foreign import ccall "qtc_QListView_doAutoScroll" qtc_QListView_doAutoScroll :: Ptr (TQListView a) -> IO () instance QdoAutoScroll (QListViewSc a) (()) where doAutoScroll x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_doAutoScroll cobj_x0 instance QdragEnterEvent (QListView ()) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_dragEnterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_dragEnterEvent_h" qtc_QListView_dragEnterEvent_h :: Ptr (TQListView a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent (QListViewSc a) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_dragEnterEvent_h cobj_x0 cobj_x1 instance QdropIndicatorPosition (QListView ()) (()) where dropIndicatorPosition x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_dropIndicatorPosition cobj_x0 foreign import ccall "qtc_QListView_dropIndicatorPosition" qtc_QListView_dropIndicatorPosition :: Ptr (TQListView a) -> IO CLong instance QdropIndicatorPosition (QListViewSc a) (()) where dropIndicatorPosition x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_dropIndicatorPosition cobj_x0 instance Qedit (QListView ()) ((QModelIndex t1, EditTrigger, QEvent t3)) (IO (Bool)) where edit x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QListView_edit cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) cobj_x3 foreign import ccall "qtc_QListView_edit" qtc_QListView_edit :: Ptr (TQListView a) -> Ptr (TQModelIndex t1) -> CLong -> Ptr (TQEvent t3) -> IO CBool instance Qedit (QListViewSc a) ((QModelIndex t1, EditTrigger, QEvent t3)) (IO (Bool)) where edit x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QListView_edit cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) cobj_x3 instance QeditorDestroyed (QListView ()) ((QObject t1)) where editorDestroyed x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_editorDestroyed cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_editorDestroyed" qtc_QListView_editorDestroyed :: Ptr (TQListView a) -> Ptr (TQObject t1) -> IO () instance QeditorDestroyed (QListViewSc a) ((QObject t1)) where editorDestroyed x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_editorDestroyed cobj_x0 cobj_x1 instance QexecuteDelayedItemsLayout (QListView ()) (()) where executeDelayedItemsLayout x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_executeDelayedItemsLayout cobj_x0 foreign import ccall "qtc_QListView_executeDelayedItemsLayout" qtc_QListView_executeDelayedItemsLayout :: Ptr (TQListView a) -> IO () instance QexecuteDelayedItemsLayout (QListViewSc a) (()) where executeDelayedItemsLayout x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_executeDelayedItemsLayout cobj_x0 instance QfocusInEvent (QListView ()) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_focusInEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_focusInEvent_h" qtc_QListView_focusInEvent_h :: Ptr (TQListView a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent (QListViewSc a) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_focusInEvent_h cobj_x0 cobj_x1 instance QfocusNextPrevChild (QListView ()) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_focusNextPrevChild cobj_x0 (toCBool x1) foreign import ccall "qtc_QListView_focusNextPrevChild" qtc_QListView_focusNextPrevChild :: Ptr (TQListView a) -> CBool -> IO CBool instance QfocusNextPrevChild (QListViewSc a) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_focusNextPrevChild cobj_x0 (toCBool x1) instance QfocusOutEvent (QListView ()) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_focusOutEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_focusOutEvent_h" qtc_QListView_focusOutEvent_h :: Ptr (TQListView a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent (QListViewSc a) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_focusOutEvent_h cobj_x0 cobj_x1 instance QhorizontalScrollbarAction (QListView ()) ((Int)) where horizontalScrollbarAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_horizontalScrollbarAction cobj_x0 (toCInt x1) foreign import ccall "qtc_QListView_horizontalScrollbarAction" qtc_QListView_horizontalScrollbarAction :: Ptr (TQListView a) -> CInt -> IO () instance QhorizontalScrollbarAction (QListViewSc a) ((Int)) where horizontalScrollbarAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_horizontalScrollbarAction cobj_x0 (toCInt x1) instance QhorizontalScrollbarValueChanged (QListView ()) ((Int)) where horizontalScrollbarValueChanged x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_horizontalScrollbarValueChanged cobj_x0 (toCInt x1) foreign import ccall "qtc_QListView_horizontalScrollbarValueChanged" qtc_QListView_horizontalScrollbarValueChanged :: Ptr (TQListView a) -> CInt -> IO () instance QhorizontalScrollbarValueChanged (QListViewSc a) ((Int)) where horizontalScrollbarValueChanged x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_horizontalScrollbarValueChanged cobj_x0 (toCInt x1) instance QhorizontalStepsPerItem (QListView ()) (()) where horizontalStepsPerItem x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_horizontalStepsPerItem cobj_x0 foreign import ccall "qtc_QListView_horizontalStepsPerItem" qtc_QListView_horizontalStepsPerItem :: Ptr (TQListView a) -> IO CInt instance QhorizontalStepsPerItem (QListViewSc a) (()) where horizontalStepsPerItem x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_horizontalStepsPerItem cobj_x0 instance QinputMethodEvent (QListView ()) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_inputMethodEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_inputMethodEvent" qtc_QListView_inputMethodEvent :: Ptr (TQListView a) -> Ptr (TQInputMethodEvent t1) -> IO () instance QinputMethodEvent (QListViewSc a) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_inputMethodEvent cobj_x0 cobj_x1 instance QinputMethodQuery (QListView ()) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QListView_inputMethodQuery_h" qtc_QListView_inputMethodQuery_h :: Ptr (TQListView a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery (QListViewSc a) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) instance QkeyPressEvent (QListView ()) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_keyPressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_keyPressEvent_h" qtc_QListView_keyPressEvent_h :: Ptr (TQListView a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent (QListViewSc a) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_keyPressEvent_h cobj_x0 cobj_x1 instance QkeyboardSearch (QListView ()) ((String)) where keyboardSearch x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QListView_keyboardSearch_h cobj_x0 cstr_x1 foreign import ccall "qtc_QListView_keyboardSearch_h" qtc_QListView_keyboardSearch_h :: Ptr (TQListView a) -> CWString -> IO () instance QkeyboardSearch (QListViewSc a) ((String)) where keyboardSearch x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QListView_keyboardSearch_h cobj_x0 cstr_x1 instance QmouseDoubleClickEvent (QListView ()) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_mouseDoubleClickEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_mouseDoubleClickEvent_h" qtc_QListView_mouseDoubleClickEvent_h :: Ptr (TQListView a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent (QListViewSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_mouseDoubleClickEvent_h cobj_x0 cobj_x1 instance QmousePressEvent (QListView ()) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_mousePressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_mousePressEvent_h" qtc_QListView_mousePressEvent_h :: Ptr (TQListView a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent (QListViewSc a) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_mousePressEvent_h cobj_x0 cobj_x1 instance QscheduleDelayedItemsLayout (QListView ()) (()) where scheduleDelayedItemsLayout x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_scheduleDelayedItemsLayout cobj_x0 foreign import ccall "qtc_QListView_scheduleDelayedItemsLayout" qtc_QListView_scheduleDelayedItemsLayout :: Ptr (TQListView a) -> IO () instance QscheduleDelayedItemsLayout (QListViewSc a) (()) where scheduleDelayedItemsLayout x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_scheduleDelayedItemsLayout cobj_x0 instance QscrollDirtyRegion (QListView ()) ((Int, Int)) where scrollDirtyRegion x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_scrollDirtyRegion cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QListView_scrollDirtyRegion" qtc_QListView_scrollDirtyRegion :: Ptr (TQListView a) -> CInt -> CInt -> IO () instance QscrollDirtyRegion (QListViewSc a) ((Int, Int)) where scrollDirtyRegion x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_scrollDirtyRegion cobj_x0 (toCInt x1) (toCInt x2) instance QselectAll (QListView ()) (()) where selectAll x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_selectAll_h cobj_x0 foreign import ccall "qtc_QListView_selectAll_h" qtc_QListView_selectAll_h :: Ptr (TQListView a) -> IO () instance QselectAll (QListViewSc a) (()) where selectAll x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_selectAll_h cobj_x0 instance QselectionCommand (QListView ()) ((QModelIndex t1)) where selectionCommand x0 (x1) = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_selectionCommand cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_selectionCommand" qtc_QListView_selectionCommand :: Ptr (TQListView a) -> Ptr (TQModelIndex t1) -> IO CLong instance QselectionCommand (QListViewSc a) ((QModelIndex t1)) where selectionCommand x0 (x1) = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_selectionCommand cobj_x0 cobj_x1 instance QselectionCommand (QListView ()) ((QModelIndex t1, QEvent t2)) where selectionCommand x0 (x1, x2) = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QListView_selectionCommand1 cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QListView_selectionCommand1" qtc_QListView_selectionCommand1 :: Ptr (TQListView a) -> Ptr (TQModelIndex t1) -> Ptr (TQEvent t2) -> IO CLong instance QselectionCommand (QListViewSc a) ((QModelIndex t1, QEvent t2)) where selectionCommand x0 (x1, x2) = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QListView_selectionCommand1 cobj_x0 cobj_x1 cobj_x2 instance QsetDirtyRegion (QListView ()) ((QRegion t1)) where setDirtyRegion x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_setDirtyRegion cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_setDirtyRegion" qtc_QListView_setDirtyRegion :: Ptr (TQListView a) -> Ptr (TQRegion t1) -> IO () instance QsetDirtyRegion (QListViewSc a) ((QRegion t1)) where setDirtyRegion x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_setDirtyRegion cobj_x0 cobj_x1 instance QsetHorizontalStepsPerItem (QListView ()) ((Int)) where setHorizontalStepsPerItem x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setHorizontalStepsPerItem cobj_x0 (toCInt x1) foreign import ccall "qtc_QListView_setHorizontalStepsPerItem" qtc_QListView_setHorizontalStepsPerItem :: Ptr (TQListView a) -> CInt -> IO () instance QsetHorizontalStepsPerItem (QListViewSc a) ((Int)) where setHorizontalStepsPerItem x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setHorizontalStepsPerItem cobj_x0 (toCInt x1) instance QsetModel (QListView ()) ((QAbstractItemModel t1)) where setModel x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_setModel_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_setModel_h" qtc_QListView_setModel_h :: Ptr (TQListView a) -> Ptr (TQAbstractItemModel t1) -> IO () instance QsetModel (QListViewSc a) ((QAbstractItemModel t1)) where setModel x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_setModel_h cobj_x0 cobj_x1 instance QsetSelectionModel (QListView ()) ((QItemSelectionModel t1)) where setSelectionModel x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_setSelectionModel_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_setSelectionModel_h" qtc_QListView_setSelectionModel_h :: Ptr (TQListView a) -> Ptr (TQItemSelectionModel t1) -> IO () instance QsetSelectionModel (QListViewSc a) ((QItemSelectionModel t1)) where setSelectionModel x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_setSelectionModel_h cobj_x0 cobj_x1 instance QsetState (QListView ()) ((QAbstractItemViewState)) where setState x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setState cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QListView_setState" qtc_QListView_setState :: Ptr (TQListView a) -> CLong -> IO () instance QsetState (QListViewSc a) ((QAbstractItemViewState)) where setState x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setState cobj_x0 (toCLong $ qEnum_toInt x1) instance QsetVerticalStepsPerItem (QListView ()) ((Int)) where setVerticalStepsPerItem x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setVerticalStepsPerItem cobj_x0 (toCInt x1) foreign import ccall "qtc_QListView_setVerticalStepsPerItem" qtc_QListView_setVerticalStepsPerItem :: Ptr (TQListView a) -> CInt -> IO () instance QsetVerticalStepsPerItem (QListViewSc a) ((Int)) where setVerticalStepsPerItem x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setVerticalStepsPerItem cobj_x0 (toCInt x1) instance QsizeHintForColumn (QListView ()) ((Int)) where sizeHintForColumn x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_sizeHintForColumn_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QListView_sizeHintForColumn_h" qtc_QListView_sizeHintForColumn_h :: Ptr (TQListView a) -> CInt -> IO CInt instance QsizeHintForColumn (QListViewSc a) ((Int)) where sizeHintForColumn x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_sizeHintForColumn_h cobj_x0 (toCInt x1) instance QsizeHintForRow (QListView ()) ((Int)) where sizeHintForRow x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_sizeHintForRow_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QListView_sizeHintForRow_h" qtc_QListView_sizeHintForRow_h :: Ptr (TQListView a) -> CInt -> IO CInt instance QsizeHintForRow (QListViewSc a) ((Int)) where sizeHintForRow x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_sizeHintForRow_h cobj_x0 (toCInt x1) instance QstartAutoScroll (QListView ()) (()) where startAutoScroll x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_startAutoScroll cobj_x0 foreign import ccall "qtc_QListView_startAutoScroll" qtc_QListView_startAutoScroll :: Ptr (TQListView a) -> IO () instance QstartAutoScroll (QListViewSc a) (()) where startAutoScroll x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_startAutoScroll cobj_x0 instance Qstate (QListView ()) (()) (IO (QAbstractItemViewState)) where state x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_state cobj_x0 foreign import ccall "qtc_QListView_state" qtc_QListView_state :: Ptr (TQListView a) -> IO CLong instance Qstate (QListViewSc a) (()) (IO (QAbstractItemViewState)) where state x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_state cobj_x0 instance QstopAutoScroll (QListView ()) (()) where stopAutoScroll x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_stopAutoScroll cobj_x0 foreign import ccall "qtc_QListView_stopAutoScroll" qtc_QListView_stopAutoScroll :: Ptr (TQListView a) -> IO () instance QstopAutoScroll (QListViewSc a) (()) where stopAutoScroll x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_stopAutoScroll cobj_x0 instance QupdateEditorData (QListView ()) (()) where updateEditorData x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_updateEditorData cobj_x0 foreign import ccall "qtc_QListView_updateEditorData" qtc_QListView_updateEditorData :: Ptr (TQListView a) -> IO () instance QupdateEditorData (QListViewSc a) (()) where updateEditorData x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_updateEditorData cobj_x0 instance QupdateEditorGeometries (QListView ()) (()) where updateEditorGeometries x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_updateEditorGeometries cobj_x0 foreign import ccall "qtc_QListView_updateEditorGeometries" qtc_QListView_updateEditorGeometries :: Ptr (TQListView a) -> IO () instance QupdateEditorGeometries (QListViewSc a) (()) where updateEditorGeometries x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_updateEditorGeometries cobj_x0 instance QverticalScrollbarAction (QListView ()) ((Int)) where verticalScrollbarAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_verticalScrollbarAction cobj_x0 (toCInt x1) foreign import ccall "qtc_QListView_verticalScrollbarAction" qtc_QListView_verticalScrollbarAction :: Ptr (TQListView a) -> CInt -> IO () instance QverticalScrollbarAction (QListViewSc a) ((Int)) where verticalScrollbarAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_verticalScrollbarAction cobj_x0 (toCInt x1) instance QverticalScrollbarValueChanged (QListView ()) ((Int)) where verticalScrollbarValueChanged x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_verticalScrollbarValueChanged cobj_x0 (toCInt x1) foreign import ccall "qtc_QListView_verticalScrollbarValueChanged" qtc_QListView_verticalScrollbarValueChanged :: Ptr (TQListView a) -> CInt -> IO () instance QverticalScrollbarValueChanged (QListViewSc a) ((Int)) where verticalScrollbarValueChanged x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_verticalScrollbarValueChanged cobj_x0 (toCInt x1) instance QverticalStepsPerItem (QListView ()) (()) where verticalStepsPerItem x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_verticalStepsPerItem cobj_x0 foreign import ccall "qtc_QListView_verticalStepsPerItem" qtc_QListView_verticalStepsPerItem :: Ptr (TQListView a) -> IO CInt instance QverticalStepsPerItem (QListViewSc a) (()) where verticalStepsPerItem x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_verticalStepsPerItem cobj_x0 instance QviewportEvent (QListView ()) ((QEvent t1)) where viewportEvent x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_viewportEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_viewportEvent_h" qtc_QListView_viewportEvent_h :: Ptr (TQListView a) -> Ptr (TQEvent t1) -> IO CBool instance QviewportEvent (QListViewSc a) ((QEvent t1)) where viewportEvent x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_viewportEvent_h cobj_x0 cobj_x1 instance QcontextMenuEvent (QListView ()) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_contextMenuEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_contextMenuEvent_h" qtc_QListView_contextMenuEvent_h :: Ptr (TQListView a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent (QListViewSc a) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_contextMenuEvent_h cobj_x0 cobj_x1 instance QqminimumSizeHint (QListView ()) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_minimumSizeHint_h cobj_x0 foreign import ccall "qtc_QListView_minimumSizeHint_h" qtc_QListView_minimumSizeHint_h :: Ptr (TQListView a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint (QListViewSc a) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_minimumSizeHint_h cobj_x0 instance QminimumSizeHint (QListView ()) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QListView_minimumSizeHint_qth_h" qtc_QListView_minimumSizeHint_qth_h :: Ptr (TQListView a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint (QListViewSc a) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance QsetViewportMargins (QListView ()) ((Int, Int, Int, Int)) where setViewportMargins x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setViewportMargins cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QListView_setViewportMargins" qtc_QListView_setViewportMargins :: Ptr (TQListView a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetViewportMargins (QListViewSc a) ((Int, Int, Int, Int)) where setViewportMargins x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setViewportMargins cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance QsetupViewport (QListView ()) ((QWidget t1)) where setupViewport x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_setupViewport cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_setupViewport" qtc_QListView_setupViewport :: Ptr (TQListView a) -> Ptr (TQWidget t1) -> IO () instance QsetupViewport (QListViewSc a) ((QWidget t1)) where setupViewport x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_setupViewport cobj_x0 cobj_x1 instance QqsizeHint (QListView ()) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_sizeHint_h cobj_x0 foreign import ccall "qtc_QListView_sizeHint_h" qtc_QListView_sizeHint_h :: Ptr (TQListView a) -> IO (Ptr (TQSize ())) instance QqsizeHint (QListViewSc a) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_sizeHint_h cobj_x0 instance QsizeHint (QListView ()) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QListView_sizeHint_qth_h" qtc_QListView_sizeHint_qth_h :: Ptr (TQListView a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint (QListViewSc a) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance QwheelEvent (QListView ()) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_wheelEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_wheelEvent_h" qtc_QListView_wheelEvent_h :: Ptr (TQListView a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent (QListViewSc a) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_wheelEvent_h cobj_x0 cobj_x1 instance QchangeEvent (QListView ()) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_changeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_changeEvent_h" qtc_QListView_changeEvent_h :: Ptr (TQListView a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent (QListViewSc a) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_changeEvent_h cobj_x0 cobj_x1 instance QdrawFrame (QListView ()) ((QPainter t1)) where drawFrame x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_drawFrame cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_drawFrame" qtc_QListView_drawFrame :: Ptr (TQListView a) -> Ptr (TQPainter t1) -> IO () instance QdrawFrame (QListViewSc a) ((QPainter t1)) where drawFrame x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_drawFrame cobj_x0 cobj_x1 instance QactionEvent (QListView ()) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_actionEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_actionEvent_h" qtc_QListView_actionEvent_h :: Ptr (TQListView a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent (QListViewSc a) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_actionEvent_h cobj_x0 cobj_x1 instance QaddAction (QListView ()) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_addAction cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_addAction" qtc_QListView_addAction :: Ptr (TQListView a) -> Ptr (TQAction t1) -> IO () instance QaddAction (QListViewSc a) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_addAction cobj_x0 cobj_x1 instance QcloseEvent (QListView ()) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_closeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_closeEvent_h" qtc_QListView_closeEvent_h :: Ptr (TQListView a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent (QListViewSc a) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_closeEvent_h cobj_x0 cobj_x1 instance Qcreate (QListView ()) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_create cobj_x0 foreign import ccall "qtc_QListView_create" qtc_QListView_create :: Ptr (TQListView a) -> IO () instance Qcreate (QListViewSc a) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_create cobj_x0 instance Qcreate (QListView ()) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_create1 cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_create1" qtc_QListView_create1 :: Ptr (TQListView a) -> Ptr (TQVoid t1) -> IO () instance Qcreate (QListViewSc a) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_create1 cobj_x0 cobj_x1 instance Qcreate (QListView ()) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_create2 cobj_x0 cobj_x1 (toCBool x2) foreign import ccall "qtc_QListView_create2" qtc_QListView_create2 :: Ptr (TQListView a) -> Ptr (TQVoid t1) -> CBool -> IO () instance Qcreate (QListViewSc a) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_create2 cobj_x0 cobj_x1 (toCBool x2) instance Qcreate (QListView ()) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) foreign import ccall "qtc_QListView_create3" qtc_QListView_create3 :: Ptr (TQListView a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO () instance Qcreate (QListViewSc a) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) instance Qdestroy (QListView ()) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_destroy cobj_x0 foreign import ccall "qtc_QListView_destroy" qtc_QListView_destroy :: Ptr (TQListView a) -> IO () instance Qdestroy (QListViewSc a) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_destroy cobj_x0 instance Qdestroy (QListView ()) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_destroy1 cobj_x0 (toCBool x1) foreign import ccall "qtc_QListView_destroy1" qtc_QListView_destroy1 :: Ptr (TQListView a) -> CBool -> IO () instance Qdestroy (QListViewSc a) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_destroy1 cobj_x0 (toCBool x1) instance Qdestroy (QListView ()) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_destroy2 cobj_x0 (toCBool x1) (toCBool x2) foreign import ccall "qtc_QListView_destroy2" qtc_QListView_destroy2 :: Ptr (TQListView a) -> CBool -> CBool -> IO () instance Qdestroy (QListViewSc a) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_destroy2 cobj_x0 (toCBool x1) (toCBool x2) instance QdevType (QListView ()) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_devType_h cobj_x0 foreign import ccall "qtc_QListView_devType_h" qtc_QListView_devType_h :: Ptr (TQListView a) -> IO CInt instance QdevType (QListViewSc a) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_devType_h cobj_x0 instance QenabledChange (QListView ()) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_enabledChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QListView_enabledChange" qtc_QListView_enabledChange :: Ptr (TQListView a) -> CBool -> IO () instance QenabledChange (QListViewSc a) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_enabledChange cobj_x0 (toCBool x1) instance QenterEvent (QListView ()) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_enterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_enterEvent_h" qtc_QListView_enterEvent_h :: Ptr (TQListView a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent (QListViewSc a) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_enterEvent_h cobj_x0 cobj_x1 instance QfocusNextChild (QListView ()) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_focusNextChild cobj_x0 foreign import ccall "qtc_QListView_focusNextChild" qtc_QListView_focusNextChild :: Ptr (TQListView a) -> IO CBool instance QfocusNextChild (QListViewSc a) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_focusNextChild cobj_x0 instance QfocusPreviousChild (QListView ()) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_focusPreviousChild cobj_x0 foreign import ccall "qtc_QListView_focusPreviousChild" qtc_QListView_focusPreviousChild :: Ptr (TQListView a) -> IO CBool instance QfocusPreviousChild (QListViewSc a) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_focusPreviousChild cobj_x0 instance QfontChange (QListView ()) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_fontChange cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_fontChange" qtc_QListView_fontChange :: Ptr (TQListView a) -> Ptr (TQFont t1) -> IO () instance QfontChange (QListViewSc a) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_fontChange cobj_x0 cobj_x1 instance QheightForWidth (QListView ()) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_heightForWidth_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QListView_heightForWidth_h" qtc_QListView_heightForWidth_h :: Ptr (TQListView a) -> CInt -> IO CInt instance QheightForWidth (QListViewSc a) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_heightForWidth_h cobj_x0 (toCInt x1) instance QhideEvent (QListView ()) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_hideEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_hideEvent_h" qtc_QListView_hideEvent_h :: Ptr (TQListView a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent (QListViewSc a) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_hideEvent_h cobj_x0 cobj_x1 instance QkeyReleaseEvent (QListView ()) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_keyReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_keyReleaseEvent_h" qtc_QListView_keyReleaseEvent_h :: Ptr (TQListView a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent (QListViewSc a) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_keyReleaseEvent_h cobj_x0 cobj_x1 instance QlanguageChange (QListView ()) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_languageChange cobj_x0 foreign import ccall "qtc_QListView_languageChange" qtc_QListView_languageChange :: Ptr (TQListView a) -> IO () instance QlanguageChange (QListViewSc a) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_languageChange cobj_x0 instance QleaveEvent (QListView ()) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_leaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_leaveEvent_h" qtc_QListView_leaveEvent_h :: Ptr (TQListView a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent (QListViewSc a) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_leaveEvent_h cobj_x0 cobj_x1 instance Qmetric (QListView ()) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_metric cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QListView_metric" qtc_QListView_metric :: Ptr (TQListView a) -> CLong -> IO CInt instance Qmetric (QListViewSc a) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_metric cobj_x0 (toCLong $ qEnum_toInt x1) instance Qmove (QListView ()) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_move1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QListView_move1" qtc_QListView_move1 :: Ptr (TQListView a) -> CInt -> CInt -> IO () instance Qmove (QListViewSc a) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_move1 cobj_x0 (toCInt x1) (toCInt x2) instance Qmove (QListView ()) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QListView_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QListView_move_qth" qtc_QListView_move_qth :: Ptr (TQListView a) -> CInt -> CInt -> IO () instance Qmove (QListViewSc a) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QListView_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y instance Qqmove (QListView ()) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_move cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_move" qtc_QListView_move :: Ptr (TQListView a) -> Ptr (TQPoint t1) -> IO () instance Qqmove (QListViewSc a) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_move cobj_x0 cobj_x1 instance QmoveEvent (QListView ()) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_moveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_moveEvent_h" qtc_QListView_moveEvent_h :: Ptr (TQListView a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent (QListViewSc a) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_moveEvent_h cobj_x0 cobj_x1 instance QpaintEngine (QListView ()) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_paintEngine_h cobj_x0 foreign import ccall "qtc_QListView_paintEngine_h" qtc_QListView_paintEngine_h :: Ptr (TQListView a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine (QListViewSc a) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_paintEngine_h cobj_x0 instance QpaletteChange (QListView ()) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_paletteChange cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_paletteChange" qtc_QListView_paletteChange :: Ptr (TQListView a) -> Ptr (TQPalette t1) -> IO () instance QpaletteChange (QListViewSc a) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_paletteChange cobj_x0 cobj_x1 instance Qrepaint (QListView ()) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_repaint cobj_x0 foreign import ccall "qtc_QListView_repaint" qtc_QListView_repaint :: Ptr (TQListView a) -> IO () instance Qrepaint (QListViewSc a) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_repaint cobj_x0 instance Qrepaint (QListView ()) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QListView_repaint2" qtc_QListView_repaint2 :: Ptr (TQListView a) -> CInt -> CInt -> CInt -> CInt -> IO () instance Qrepaint (QListViewSc a) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance Qrepaint (QListView ()) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_repaint1 cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_repaint1" qtc_QListView_repaint1 :: Ptr (TQListView a) -> Ptr (TQRegion t1) -> IO () instance Qrepaint (QListViewSc a) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_repaint1 cobj_x0 cobj_x1 instance QresetInputContext (QListView ()) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_resetInputContext cobj_x0 foreign import ccall "qtc_QListView_resetInputContext" qtc_QListView_resetInputContext :: Ptr (TQListView a) -> IO () instance QresetInputContext (QListViewSc a) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_resetInputContext cobj_x0 instance Qresize (QListView ()) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_resize1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QListView_resize1" qtc_QListView_resize1 :: Ptr (TQListView a) -> CInt -> CInt -> IO () instance Qresize (QListViewSc a) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_resize1 cobj_x0 (toCInt x1) (toCInt x2) instance Qqresize (QListView ()) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_resize cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_resize" qtc_QListView_resize :: Ptr (TQListView a) -> Ptr (TQSize t1) -> IO () instance Qqresize (QListViewSc a) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_resize cobj_x0 cobj_x1 instance Qresize (QListView ()) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QListView_resize_qth cobj_x0 csize_x1_w csize_x1_h foreign import ccall "qtc_QListView_resize_qth" qtc_QListView_resize_qth :: Ptr (TQListView a) -> CInt -> CInt -> IO () instance Qresize (QListViewSc a) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QListView_resize_qth cobj_x0 csize_x1_w csize_x1_h instance QsetGeometry (QListView ()) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QListView_setGeometry1" qtc_QListView_setGeometry1 :: Ptr (TQListView a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QListViewSc a) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance QqsetGeometry (QListView ()) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_setGeometry cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_setGeometry" qtc_QListView_setGeometry :: Ptr (TQListView a) -> Ptr (TQRect t1) -> IO () instance QqsetGeometry (QListViewSc a) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_setGeometry cobj_x0 cobj_x1 instance QsetGeometry (QListView ()) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QListView_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h foreign import ccall "qtc_QListView_setGeometry_qth" qtc_QListView_setGeometry_qth :: Ptr (TQListView a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QListViewSc a) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QListView_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h instance QsetMouseTracking (QListView ()) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setMouseTracking cobj_x0 (toCBool x1) foreign import ccall "qtc_QListView_setMouseTracking" qtc_QListView_setMouseTracking :: Ptr (TQListView a) -> CBool -> IO () instance QsetMouseTracking (QListViewSc a) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setMouseTracking cobj_x0 (toCBool x1) instance QsetVisible (QListView ()) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setVisible_h cobj_x0 (toCBool x1) foreign import ccall "qtc_QListView_setVisible_h" qtc_QListView_setVisible_h :: Ptr (TQListView a) -> CBool -> IO () instance QsetVisible (QListViewSc a) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_setVisible_h cobj_x0 (toCBool x1) instance QshowEvent (QListView ()) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_showEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_showEvent_h" qtc_QListView_showEvent_h :: Ptr (TQListView a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent (QListViewSc a) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_showEvent_h cobj_x0 cobj_x1 instance QtabletEvent (QListView ()) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_tabletEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_tabletEvent_h" qtc_QListView_tabletEvent_h :: Ptr (TQListView a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent (QListViewSc a) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_tabletEvent_h cobj_x0 cobj_x1 instance QupdateMicroFocus (QListView ()) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_updateMicroFocus cobj_x0 foreign import ccall "qtc_QListView_updateMicroFocus" qtc_QListView_updateMicroFocus :: Ptr (TQListView a) -> IO () instance QupdateMicroFocus (QListViewSc a) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_updateMicroFocus cobj_x0 instance QwindowActivationChange (QListView ()) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_windowActivationChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QListView_windowActivationChange" qtc_QListView_windowActivationChange :: Ptr (TQListView a) -> CBool -> IO () instance QwindowActivationChange (QListViewSc a) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_windowActivationChange cobj_x0 (toCBool x1) instance QchildEvent (QListView ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_childEvent" qtc_QListView_childEvent :: Ptr (TQListView a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QListViewSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QListView ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QListView_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QListView_connectNotify" qtc_QListView_connectNotify :: Ptr (TQListView a) -> CWString -> IO () instance QconnectNotify (QListViewSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QListView_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QListView ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QListView_customEvent" qtc_QListView_customEvent :: Ptr (TQListView a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QListViewSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QListView_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QListView ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QListView_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QListView_disconnectNotify" qtc_QListView_disconnectNotify :: Ptr (TQListView a) -> CWString -> IO () instance QdisconnectNotify (QListViewSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QListView_disconnectNotify cobj_x0 cstr_x1 instance QeventFilter (QListView ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QListView_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QListView_eventFilter_h" qtc_QListView_eventFilter_h :: Ptr (TQListView a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QListViewSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QListView_eventFilter_h cobj_x0 cobj_x1 cobj_x2 instance Qreceivers (QListView ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QListView_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QListView_receivers" qtc_QListView_receivers :: Ptr (TQListView a) -> CWString -> IO CInt instance Qreceivers (QListViewSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QListView_receivers cobj_x0 cstr_x1 instance Qsender (QListView ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_sender cobj_x0 foreign import ccall "qtc_QListView_sender" qtc_QListView_sender :: Ptr (TQListView a) -> IO (Ptr (TQObject ())) instance Qsender (QListViewSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QListView_sender cobj_x0
keera-studios/hsQt
Qtc/Gui/QListView.hs
bsd-2-clause
93,114
0
15
14,993
30,241
15,340
14,901
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-| Module : Network.Spotify.Api.Types.ExternalId Description : External ID for some Spotify Content. Stability : experimental -} module Network.Spotify.Api.Types.ExternalId where import Data.Aeson (FromJSON (parseJSON), ToJSON, object, toJSON, withObject, (.=)) import Data.Aeson.Types (Pair, Parser, Value) import qualified Data.HashMap.Strict as HM import Data.Text (Text, pack, unpack) -- | An external ID for some Spotify Content. data ExternalId = ExternalId { externalIds :: [ExternalIdEntry] -- ^ List of external identifiers } -- | A single external identifier for some Spotify Content. data ExternalIdEntry = ExternalIdEntry { idType :: ExternalIdType -- ^ The identifier type , idValue :: Text -- ^ An external identifier for the object. } instance FromJSON ExternalId where parseJSON = withObject "external ID" $ \o -> do result <- if not (null o) then do parsedExternalIds <- parseExternalIds o return $ Right ExternalId { externalIds = parsedExternalIds } else return $ Left "no fields" case result of Left err -> fail err Right exteranlId -> return exteranlId parseExternalIds :: HM.HashMap Text Value -> Parser [ExternalIdEntry] parseExternalIds obj = mapM parseExternalIdEntry (HM.toList obj) where parseExternalIdEntry :: (Text, Value) -> Parser ExternalIdEntry parseExternalIdEntry (key, val) = do parsedValue <- parseJSON val return ExternalIdEntry { idType = externalIdTypeFromText key , idValue = parsedValue } instance ToJSON ExternalId where toJSON p = object $ colateExternalIds (externalIds p) colateExternalIds :: [ExternalIdEntry] -> [Pair] colateExternalIds entries = let headEntry = head entries type_ = pack $ show (idType headEntry) value = idValue headEntry entry = type_ .= value in entry : colateExternalIds (tail entries) -- | The type of an external ID for some object. data ExternalIdType = ISRC -- ^ International Standard Recording Code | EAN -- ^ International Article Number | UPC -- ^ Universal Product Code | Other Text -- ^ Some other exteranl ID for the object. instance Show ExternalIdType where show externalIdType = case externalIdType of ISRC -> "isrc" EAN -> "ean" UPC -> "upc" Other otherIdType -> unpack otherIdType externalIdTypeFromText :: Text -> ExternalIdType externalIdTypeFromText externalIdType = case externalIdType of "isrc" -> ISRC "ean" -> EAN "upc" -> UPC otherIdType -> Other otherIdType
chances/servant-spotify
src/Network/Spotify/Api/Types/ExternalId.hs
bsd-3-clause
2,927
0
17
883
588
318
270
58
4
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Hans.Message.Ip4 where import Hans.Address.IP4 (IP4) import Hans.Utils import Hans.Utils.Checksum import Control.Monad (unless) import Data.Serialize (Serialize(..)) import Data.Serialize.Get (Get,getWord8,getWord16be,getByteString,isolate,label) import Data.Serialize.Put (runPut,runPutM,putWord8,putWord16be,putByteString) import Data.Bits (Bits((.&.),(.|.),testBit,setBit,shiftR,shiftL,bit)) import Data.Word (Word8,Word16) import qualified Data.ByteString as S -- IP4 Pseudo Header ----------------------------------------------------------- -- 0 7 8 15 16 23 24 31 -- +--------+--------+--------+--------+ -- | source address | -- +--------+--------+--------+--------+ -- | destination address | -- +--------+--------+--------+--------+ -- | zero |protocol| length | -- +--------+--------+--------+--------+ mkIP4PseudoHeader :: IP4 -> IP4 -> IP4Protocol -> MkPseudoHeader mkIP4PseudoHeader src dst prot len = runPut $ do put src put dst putWord8 0 >> put prot >> putWord16be (fromIntegral len) -- IP4 Packets ----------------------------------------------------------------- newtype Ident = Ident { getIdent :: Word16 } deriving (Eq,Ord,Num,Show,Serialize,Integral,Real,Enum) newtype IP4Protocol = IP4Protocol { getIP4Protocol :: Word8 } deriving (Eq,Ord,Num,Show,Serialize) data IP4Packet = IP4Packet { ip4Header :: !IP4Header , ip4Payload :: S.ByteString } deriving Show data IP4Header = IP4Header { ip4Version :: !Word8 , ip4TypeOfService :: !Word8 , ip4Ident :: !Ident , ip4MayFragment :: Bool , ip4MoreFragments :: Bool , ip4FragmentOffset :: !Word16 , ip4TimeToLive :: !Word8 , ip4Protocol :: !IP4Protocol , ip4Checksum :: !Word16 , ip4SourceAddr :: !IP4 , ip4DestAddr :: !IP4 , ip4Options :: [IP4Option] } deriving Show emptyIP4Header :: IP4Protocol -> IP4 -> IP4 -> IP4Header emptyIP4Header prot src dst = IP4Header { ip4Version = 4 , ip4TypeOfService = 0 , ip4Ident = 0 , ip4MayFragment = False , ip4MoreFragments = False , ip4FragmentOffset = 0 , ip4TimeToLive = 127 , ip4Protocol = prot , ip4Checksum = 0 , ip4SourceAddr = src , ip4DestAddr = dst , ip4Options = [] } noMoreFragments :: IP4Header -> IP4Header noMoreFragments hdr = hdr { ip4MoreFragments = False } moreFragments :: IP4Header -> IP4Header moreFragments hdr = hdr { ip4MoreFragments = True } addOffset :: Word16 -> IP4Header -> IP4Header addOffset off hdr = hdr { ip4FragmentOffset = ip4FragmentOffset hdr + off } setIdent :: Ident -> IP4Header -> IP4Header setIdent i hdr = hdr { ip4Ident = i } -- | Calculate the size of an IP4 packet ip4PacketSize :: IP4Packet -> Int ip4PacketSize (IP4Packet hdr bs) = ip4HeaderSize hdr + fromIntegral (S.length bs) -- | Calculate the size of an IP4 header ip4HeaderSize :: IP4Header -> Int ip4HeaderSize hdr = 20 + sum (map ip4OptionSize (ip4Options hdr)) -- | Fragment a single IP packet into one or more, given an MTU to fit into. splitPacket :: Int -> IP4Packet -> [IP4Packet] splitPacket mtu pkt | ip4PacketSize pkt > mtu = fragmentPacket mtu' pkt | otherwise = [pkt] where mtu' = fromIntegral (mtu - ip4HeaderSize (ip4Header pkt)) -- | Given a fragment size and a packet, fragment the packet into multiple -- smaller ones. fragmentPacket :: Int -> IP4Packet -> [IP4Packet] fragmentPacket mtu pkt@(IP4Packet hdr bs) | payloadLen <= mtu = [pkt { ip4Header = noMoreFragments hdr }] | otherwise = frag : fragmentPacket mtu pkt' where payloadLen = S.length bs (as,rest) = S.splitAt mtu bs alen = fromIntegral (S.length as) pkt' = pkt { ip4Header = hdr', ip4Payload = rest } hdr' = addOffset alen hdr frag = pkt { ip4Header = moreFragments hdr, ip4Payload = as } -- 0 1 2 3 -- 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -- +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -- |Version| IHL |Type of Service| Total Length | -- +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -- | Identification |Flags| Fragment Offset | -- +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -- | Time to Live | Protocol | Header Checksum | -- +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -- | Source Address | -- +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -- | Destination Address | -- +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ parseIP4Packet :: Get (IP4Header, Int, Int) parseIP4Packet = do b0 <- getWord8 let ver = b0 `shiftR` 4 let ihl = fromIntegral ((b0 .&. 0xf) * 4) label "IP4 Header" $ isolate (ihl - 1) $ do tos <- getWord8 len <- getWord16be ident <- get b1 <- getWord16be let flags = b1 `shiftR` 13 let off = b1 .&. 0x1fff ttl <- getWord8 prot <- get cs <- getWord16be source <- get dest <- get let optlen = ihl - 20 opts <- label "IP4 Options" $ isolate optlen $ getOptions $ fromIntegral optlen let hdr = IP4Header { ip4Version = ver , ip4TypeOfService = tos , ip4Ident = ident , ip4MayFragment = flags `testBit` 1 , ip4MoreFragments = flags `testBit` 0 , ip4FragmentOffset = off * 8 , ip4TimeToLive = ttl , ip4Protocol = prot , ip4Checksum = cs , ip4SourceAddr = source , ip4DestAddr = dest , ip4Options = opts } return (hdr, fromIntegral ihl, fromIntegral len) -- | The final step to render an IP header and its payload out as a bytestring. renderIP4Packet :: IP4Packet -> IO Packet renderIP4Packet (IP4Packet hdr pkt) = do let (len,bs) = runPutM $ do let (optbs,optlen) = renderOptions (ip4Options hdr) let ihl = 20 + optlen putWord8 (ip4Version hdr `shiftL` 4 .|. (ihl `div` 4)) putWord8 (ip4TypeOfService hdr) putWord16be (fromIntegral (S.length pkt) + fromIntegral ihl) put (ip4Ident hdr) let frag | ip4MayFragment hdr = (`setBit` 1) | otherwise = id let morefrags | ip4MoreFragments hdr = (`setBit` 0) | otherwise = id let flags = frag (morefrags 0) let off = ip4FragmentOffset hdr `div` 8 putWord16be (flags `shiftL` 13 .|. off .&. 0x1fff) putWord8 (ip4TimeToLive hdr) put (ip4Protocol hdr) putWord16be 0 -- (ip4Checksum hdr) put (ip4SourceAddr hdr) put (ip4DestAddr hdr) putByteString optbs putByteString pkt return ihl let cs = computeChecksum 0 (S.take (fromIntegral len) bs) pokeChecksum cs bs 10 -- IP4 Options ----------------------------------------------------------------- renderOptions :: [IP4Option] -> (S.ByteString,Word8) renderOptions opts = case optlen `mod` 4 of 0 -> (optbs,fromIntegral optlen) -- pad with no-ops n -> (optbs `S.append` S.replicate n 0x1, fromIntegral (optlen + n)) where optbs = runPut (mapM_ put opts) optlen = S.length optbs getOptions :: Int -> Get [IP4Option] getOptions len | len <= 0 = return [] | otherwise = do o <- get rest <- getOptions (len - ip4OptionSize o) return $! (o : rest) data IP4Option = IP4Option { ip4OptionCopied :: !Bool , ip4OptionClass :: !Word8 , ip4OptionNum :: !Word8 , ip4OptionData :: S.ByteString } deriving Show ip4OptionSize :: IP4Option -> Int ip4OptionSize opt = case ip4OptionNum opt of 0 -> 1 1 -> 1 _ -> 2 + fromIntegral (S.length (ip4OptionData opt)) instance Serialize IP4Option where get = do b <- getWord8 let optCopied = testBit b 7 let optClass = (b `shiftR` 5) .&. 0x3 let optNum = b .&. 0x1f bs <- case optNum of 0 -> return S.empty 1 -> return S.empty _ -> do len <- getWord8 unless (len >= 2) (fail "Option length parameter is to small") getByteString (fromIntegral (len - 2)) return $! IP4Option { ip4OptionCopied = optCopied , ip4OptionClass = optClass , ip4OptionNum = optNum , ip4OptionData = bs } put opt = do let copied | ip4OptionCopied opt = bit 7 | otherwise = 0 putWord8 (copied .|. ((ip4OptionClass opt .&. 0x3) `shiftL` 5) .|. ip4OptionNum opt .&. 0x1f) case ip4OptionNum opt of 0 -> return () 1 -> return () _ -> do putWord8 (fromIntegral (S.length (ip4OptionData opt))) putByteString (ip4OptionData opt)
Tener/HaNS
src/Hans/Message/Ip4.hs
bsd-3-clause
9,100
0
19
2,572
2,436
1,290
1,146
222
3
{-# LANGUAGE OverloadedStrings, FlexibleContexts #-} module MNIST where import qualified Data.Binary.Get as Bin import Control.Lens import DeepBanana import DeepBanana.Prelude import Codec.Compression.GZip import qualified Data.Attoparsec.ByteString as AP import qualified Network.Wreq as Wreq import System.Directory import System.FilePath (takeDirectory) import Vision.Image as VI hiding (index) import qualified Vision.Primitive as VP loadOrDownload :: (MonadIO m, MonadError String m) => Maybe String -> FilePath -> m ByteString loadOrDownload murl fpath = do dirExists <- liftIO $ doesDirectoryExist $ takeDirectory fpath when (not dirExists) $ throwError $ "Directory does not exist: " ++ show (takeDirectory fpath) fileExists <- liftIO $ doesFileExist fpath case (fileExists, murl) of (False, Nothing) -> throwError $ "File not found and no download URL provided: " ++ fpath (False, Just url) -> liftIO $ do putStrLn $ "File not found: " ++ pack fpath ++ "\nDownloading from: " ++ pack url resp <- Wreq.get url writeFile fpath $ resp ^. Wreq.responseBody putStrLn "Finished downloading." return $ toStrict $ decompress $ resp ^. Wreq.responseBody _ -> liftIO $ fmap (toStrict . decompress) $ readFile fpath parseInt :: AP.Parser Int parseInt = fmap (fromIntegral . Bin.runGet Bin.getWord32be . fromStrict) $ AP.take 4 ubyte_images :: AP.Parser [Grey] ubyte_images = do magic_number <- parseInt when (magic_number /= 2051) $ fail $ "Invalid magic number: " ++ show magic_number ++ ". Should be 2051 for image ubyte files. Did you try to parse a label file?" nb_images <- parseInt nb_rows <- parseInt nb_cols <- parseInt replicateM nb_images $ do imgbstring <- AP.take (nb_rows * nb_cols) return $ (fromFunction (VP.Z VP.:. nb_rows VP.:. nb_cols) $ \(VP.Z VP.:. i VP.:. j) -> GreyPixel $ unsafeIndex imgbstring (fromIntegral $ j + i * nb_cols)) :: AP.Parser Grey ubyte_labels :: AP.Parser [Int] ubyte_labels = do magic_number <- parseInt when (magic_number /= 2049) $ fail $ "Invalid magic number: " ++ show magic_number ++ ". Should be 2049 for image ubyte files. Did you try to parse an image file?" nb_labels <- parseInt replicateM nb_labels $ fmap fromIntegral $ AP.anyWord8 load_mnist :: (MonadIO m, MonadError String m) => Maybe String -> Maybe String -> FilePath -> FilePath -> Producer (Grey, Int) m () load_mnist mimgurl mlabelurl imgfpath labelfpath = do images_ubyte <- loadOrDownload mimgurl imgfpath labels_ubyte <- loadOrDownload mlabelurl labelfpath images <- case AP.parse ubyte_images images_ubyte of AP.Fail _ ctxs err -> throwError $ "Failed to parse ubyte images:\nContext: " ++ show ctxs ++ "\nError: " ++ err AP.Done _ i -> return i labels <- case AP.parse ubyte_labels labels_ubyte of AP.Fail _ ctxs err -> throwError $ "Failed to parse ubyte images:\nContext: " ++ show ctxs ++ "\nError: " ++ err AP.Done _ l -> return l forM_ (zip images labels) $ yield return ()
alexisVallet/deep-banana
examples/mnist/MNIST.hs
bsd-3-clause
3,254
0
19
804
938
464
474
70
3
{- The XML files are parsed as if they were X Protocol description files used by XCB. The internal data-structures created from the parsing are pretty-printed to a file per input file. Antoine Latter [email protected] -} import Data.XCB import System.IO import System.Environment import System.Exit import System.FilePath main = do out:fps <- getArgs xheaders <- fromFiles fps writeHeaders out xheaders writeHeaders :: FilePath -> [XHeader] -> IO () writeHeaders out = sequence_ . map (writeHeader out) writeHeader :: FilePath -> XHeader -> IO () writeHeader outdir xhd = let fname = outdir </> xname <.> "out" xname = xheader_header xhd outString = pretty xhd in writeFile fname outString
aslatter/xhb
build-utils/Parse.hs
bsd-3-clause
744
0
10
160
171
85
86
17
1
module Main where import Test.DocTest main :: IO () main = doctest [ "src/Streaming/Eversion.hs", "src/Streaming/Eversion/Pipes.hs" ]
danidiaz/streaming-eversion
tests/doctests.hs
bsd-3-clause
161
0
6
43
33
19
14
7
1
module MinIR.Dictionary ( Dictionary , empty , lookupKey, lookupTerm , getKey ) where import qualified Data.HashMap.Strict as HM import Data.HashMap.Strict (HashMap) import qualified Data.IntMap.Strict as IM import Data.IntMap.Strict (IntMap) import Data.Hashable import Data.Binary import Control.Applicative ((<$>)) import Data.List (foldl') data Dictionary key term = Dict { next :: !key , rev :: !(IntMap term) , fwd :: !(HashMap term key) } deriving (Show) instance (Hashable term, Eq term, Binary term, Enum key) => Binary (Dictionary key term) where put (Dict next rev _) = put (fromEnum next) >> put (IM.toList rev) get = do next <- get xs <- get let (rev, fwd) = foldl' (\(f,r) (k,v)->(IM.insert k v f, HM.insert v (toEnum k) r)) (IM.empty, HM.empty) xs return $ Dict (toEnum next) rev fwd empty :: key -> Dictionary key term empty k = Dict k IM.empty HM.empty lookupKey :: (Hashable term, Eq term) => term -> Dictionary key term -> Maybe key lookupKey term (Dict _ _ fwd) = HM.lookup term fwd getKey :: (Hashable term, Eq term, Enum key) => term -> Dictionary key term -> (key, Dictionary key term) getKey term dict@(Dict k' rev fwd) | Just k <- lookupKey term dict = (k, dict) | otherwise = let dict' = Dict (succ k') (IM.insert (fromEnum k') term rev) (HM.insert term k' fwd) in (k', dict') lookupTerm :: Enum key => key -> Dictionary key term -> Maybe term lookupTerm key (Dict _ rev _) = IM.lookup (fromEnum key) rev
bgamari/minir
MinIR/Dictionary.hs
bsd-3-clause
1,819
0
17
632
680
358
322
44
1
{-#LANGUAGE NoImplicitPrelude#-} module LibMu.Execute where import Prelude (IO, String, length, fromIntegral, ($)) import LibMu.MuApi import LibMu.Refimpl import Foreign import Foreign.C.String runBundle :: String -> IO () runBundle file = do mvm <- mu_refimpl2_new ctx <- newContext mvm withCString file $ \fileStr -> do loadBundle ctx fileStr (fromIntegral $ length file) withCString "@main" $ \main_name -> do main_id <- ctxIdOf ctx main_name func <- handleFromFunc ctx (fromIntegral main_id) stack <- newStack ctx func _ <- newThread ctx stack muRebindPassValues nullPtr muThreadExit nullPtr execute mvm closeContext ctx
andrew-m-h/libmu-HS
src/LibMu/Execute.hs
bsd-3-clause
669
0
14
129
211
104
107
20
1
module SandBox.Text.CSS ( module SandBox.Text.CSS.Parser, module SandBox.Text.CSS.Types ) where import SandBox.Text.CSS.Parser import SandBox.Text.CSS.Types
hnakamur/haskell-sandbox
sandbox-css/SandBox/Text/CSS.hs
bsd-3-clause
168
0
5
24
39
28
11
5
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} module API where import Network.Wai import Network.Wai.Handler.Warp import Servant import Servant.API.ContentTypes import Servant.Server import Util import Control.DeepSeq import Control.Applicative import BackTracker.BackTracker import Data.Aeson import System.TimeIt import Control.Monad.IO.Class import Data.Matrix hiding ((<|>)) type BackTrackerAPI = "solve" :> Capture "puzzle" String :> Get '[JSON] (Maybe [Int]) :<|> "time" :> Capture "puzzle" String :> Get '[JSON] Double :<|> "analyze" :> Capture "n" Int :> Capture "puzzle" String :> Get '[JSON] Double solve p= return $ (map value . toList) <$> runBackTracker p time p = liftIO $ fst <$> (timeItT $ return $ force $runBackTracker p) analyze n p= liftIO $ fst <$> (analyzeSolver n p) server:: Server BackTrackerAPI server = solve :<|> time :<|> analyze sudokuAPI::Proxy BackTrackerAPI sudokuAPI = Proxy app::Application app = serve sudokuAPI server runServer = run 8081 app
octopuscabbage/genetic-sudoku
src/API.hs
bsd-3-clause
1,074
0
16
193
329
178
151
30
1
{-# LANGUAGE OverloadedStrings #-} -- Label has an instance of IsString, so we can use String literals for labels -- | -- Module : IpTcpDns -- Description : Exported API for HBPF -- Copyright : (c) Matt Denton and Andrew Duffy, 2016 -- License : BSD3 -- Stability : experimental -- Portability : unknown -- -- Example module using the interface provided by HBPF -- to create a set of composable filters for IP/TCP/UDP -- port matching. -- module IpTcpDns ( isIpPacket , isTcpPacket , isArpPacket , isUdpPacket , isSrcPort , isDstPort , isPort ) where import Data.Monoid ((<>)) -- Using mappend, we can chain instructions together with a clean syntax import HBPF -- * Constants for our filters ethertype_off = 12 :: Offset -- ^ Offset has an instance of Num (thanks to -XGeneralizedNewtypeDeriving) transport_off = 23 :: Offset ethertype_ipv4 = 0x800 :: Literal -- ^ ... and so does Literal ethertype_arp = 0x806 :: Literal transport_udp = 0x11 :: Literal transport_tcp = 0x06 :: Literal -- | Filter that checks if is an IP packet. isIpPacket :: Filter isIpPacket = newFilter $ ldx (LoadAddrLiteral 0) <> stx (StoreAddrIndexedRegister M15) <> ldh (LoadAddrByteOff ethertype_off) <> jneq (ConditionalJmpAddrLiteralTrue ethertype_ipv4 "label1") <> ldx (LoadAddrLiteral 65535) <> stx (StoreAddrIndexedRegister M15) <> label "label1" isArpPacket :: Filter isArpPacket = newFilter $ ldx (LoadAddrLiteral 0) <> stx (StoreAddrIndexedRegister M15) <> ldh (LoadAddrByteOff ethertype_off) <> jneq (ConditionalJmpAddrLiteralTrue (ethertype_arp) "label1") <> ldx (LoadAddrLiteral 65535) <> stx (StoreAddrIndexedRegister M15) <> label "label1" isUdpPacket :: Filter isUdpPacket = newFilter $ ldx (LoadAddrLiteral 0) <> stx (StoreAddrIndexedRegister M15) <> ldh (LoadAddrByteOff transport_off) <> jneq (ConditionalJmpAddrLiteralTrue (transport_udp) "label1") <> ldx (LoadAddrLiteral 65535) <> stx (StoreAddrIndexedRegister M15) <> label "label1" isTcpPacket :: Filter isTcpPacket = newFilter $ ldx (LoadAddrLiteral 0) <> stx (StoreAddrIndexedRegister M15) <> ldh (LoadAddrByteOff transport_off) <> jneq (ConditionalJmpAddrLiteralTrue (transport_tcp) "label1") <> ldx (LoadAddrLiteral 65535) <> stx (StoreAddrIndexedRegister M15) <> label "label1" ipPacketLengthField = Offset 14 sourcePortOffset = Offset 14 destPortOffset = Offset 16 isPort :: Int -> Filter isPort port' = newFilter $ ldx (LoadAddrLiteral 0) <> stx (StoreAddrIndexedRegister M15) <> ldxb (LoadAddrNibble ipPacketLengthField) -- skip IP header <> ldh (LoadAddrOffFromX sourcePortOffset) <> jneq (ConditionalJmpAddrLiteralTrue port "label1") <> ldh (LoadAddrOffFromX destPortOffset) <> jneq (ConditionalJmpAddrLiteralTrue port "label1") <> ldx (LoadAddrLiteral 65535) <> stx (StoreAddrIndexedRegister M15) <> label "label1" where port = fromIntegral port' isSrcPort :: Int -> Filter isSrcPort port' = newFilter $ ldx (LoadAddrLiteral 0) <> stx (StoreAddrIndexedRegister M15) <> ldxb (LoadAddrNibble ipPacketLengthField) -- skip IP header <> ldh (LoadAddrOffFromX sourcePortOffset) <> jneq (ConditionalJmpAddrLiteralTrue port "label1") <> ldx (LoadAddrLiteral 65535) <> stx (StoreAddrIndexedRegister M15) <> label "label1" where port = fromIntegral port' isDstPort :: Int -> Filter isDstPort port' = newFilter $ ldx (LoadAddrLiteral 0) <> stx (StoreAddrIndexedRegister M15) <> ldxb (LoadAddrNibble ipPacketLengthField) -- skip IP header <> ldh (LoadAddrOffFromX destPortOffset) <> jneq (ConditionalJmpAddrLiteralTrue port "label1") <> ldx (LoadAddrLiteral 65535) <> stx (StoreAddrIndexedRegister M15) <> label "label1" where port = fromIntegral port'
hBPF/hBPF
app/IpTcpDns.hs
bsd-3-clause
4,469
0
17
1,352
942
475
467
92
1