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
{- Merch.Race.Top.MapGen - Map generator screen. Copyright 2013 Alan Manuel K. Gloria This file is part of Merchant's Race. Merchant's Race 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. Merchant's Race 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 Merchant's Race. If not, see <http://www.gnu.org/licenses/>. -} {- Map generator screen. -} module Merch.Race.Top.MapGen ( mapgenScreen ) where import Merch.Race.Control.Background import Merch.Race.Data.TMap import Merch.Race.GameResources import Merch.Race.Hex import Merch.Race.MapGen import Merch.Race.Ruleset import Merch.Race.UI.Button import Merch.Race.UI.Drawing import Merch.Race.UI.DrawingCombinators import Merch.Race.UI.Minimap import Control.Monad.Reader import Control.Monad.State import Control.Monad.Trans import Data.IORef import Data.Monoid import qualified Data.Set as Set import System.Random newtype MGX a = MGX {run :: ReaderT GameResources (BackM (String, Rational, MTMap)) a} instance Monad MGX where return = MGX . return fail = MGX . fail ma >>= f = MGX $ run ma >>= run . f instance MapGenM MGX where mgMapBounds = MGX $ do (s, p, m) <- get liftIO $ boundsMTMap m mgGetTerrain h = MGX $ do (s, p, m) <- get (t, _) <- liftIO $ readMTMap m h return t mgPutTerrain h t = MGX $ do (s, p, m) <- get (_, r) <- liftIO $ readMTMap m h liftIO $ writeMTMap m h (t, r) put (s, p, m) mgGetRoad h = MGX $ do (s, p, m) <- get (_, r) <- liftIO $ readMTMap m h return r mgPutRoad h r = MGX $ do (s, p, m) <- get (t, _) <- liftIO $ readMTMap m h liftIO $ writeMTMap m h (t, r) put (s, p, m) mgAddSettlement s st h = MGX $ do (step, p, m) <- get liftIO $ addSettlementMTMap m s st h put (step, p, m) mgPutDistance s1 s2 d = MGX $ do (step, p, m) <- get liftIO $ writeDistanceMTMap m s1 s2 d put (step, p, m) mgStep s = MGX $ do (_, p, m) <- get put (s, p, m) mgProgress p = MGX $ do (s, _, m) <- get put (s, p, m) mgRandom = MGX $ liftIO $ randomIO mgNameGenerator = MGX $ do gr <- ask return $ nameGenerator $ grRuleset gr mgSettlementGenerator = MGX $ do gr <- ask return $ settlementGenerator $ grRuleset gr mgRequiredTerrain st = MGX $ do gr <- ask return $ terrain (grRuleset gr) st mapSize = (256, 256) mapgenScreen :: GameResources -> (TMap -> Screen) -> Screen -> Screen mapgenScreen gr onFinish onCancel _ _ = do mtm <- newMTMap (fromOffset (0, 0), fromOffset (fst mapSize - 1, snd mapSize - 1)) let freeze (s,p,mtm) = do tm <- freezeMTMap mtm return (s,p,tm) startingState = ("Starting", 0, mtm) drawvar <- newIORef mempty bg <- runBackM freeze (runReaderT (run mapgen) gr) startingState return $ SetScreen $ runScreen gr onFinish onCancel bg drawvar runScreen :: GameResources -> (TMap -> Screen) -- on success -> Screen -- on fail (user cancelled or aborted) -> Background (String, Rational, TMap) -- background map generation -> IORef Drawing -- variable used internally -> Screen -- screen to display runScreen gr onFinish onCancel bg drawvar aspect = core where screenHeight | aspect < 1 = 1 / aspect | otherwise = 1 screenWidth | aspect > 1 = aspect | otherwise = 1 core ReDo = redraw core Idle = do mt <- completedBackground bg case mt of Just (_, _, tm) -> return $ SetScreen $ onFinish tm Nothing -> do mt <- sampleBackground bg case mt of Just v -> do updateDrawing v redraw Nothing -> return NoTopReaction core (KeyDown _ '\ESC') = return $ SetScreen $ abortScreen bc = mkButtonConfig [ ButtonFont $ grFont gr , ButtonWidth $ 0.8 , ButtonHeight $ 0.12 * screenHeight , ButtonTextHeight $ 0.04 * screenHeight ] cancelButton = button bc (0, negate $ 0.9 * screenHeight) "Cancel" abortScreen redraw = do im <- readIORef drawvar return $ SetDrawing $ cancelButton `mappend` im progressHeight = 0.06 * screenHeight progressWidth = screenWidth progressY = negate $ 0.76 * screenHeight progressFontHeight = 0.04 mapBottom = 0.7 * screenHeight mapHeight = (screenHeight + mapBottom) / 2 mapMove = screenHeight - mapHeight updateDrawing (step, progress, tmap) = do let im = mconcat [ progressText , progressBar , forceSample (Any False) $ minimapImage ] minimapImage = translate (0, mapMove) %% scale mapHeight mapHeight %% minimap tmap Set.empty progressBar = tint (Color 0.1 1 0.1 1) $ rectangle (lx, ly) (ux, uy) where lx = negate progressWidth ux = 2 * progressWidth * realToFrac progress - progressWidth ly = progressY - progressHeight uy = progressY + progressHeight progressText = mconcat [ translate (x, y) , scale adjust adjust , translate (centering, negate 0.7) ] %% text (grFont gr) step where w = textWidth (grFont gr) step x = 0 y = progressY - progressFontHeight * 0.4 adjust = progressFontHeight centering = negate w / 2 writeIORef drawvar $ drawingStatic im abortScreen _ _ = do abortBackground bg return $ SetScreen onCancel
AmkG/merchants-race
Merch/Race/Top/MapGen.hs
gpl-3.0
5,975
0
19
1,720
1,837
958
879
153
5
-- Copyright (C) 2015 Michael Alan Dorman <[email protected]> -- This file is not part of GNU Emacs. -- 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 3 of the License, or (at your option) any later -- version. -- This program is distributed in the hope that it will be useful, but WITHOUT -- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -- FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -- details. -- You should have received a copy of the GNU General Public License along with -- this program. If not, see <http://www.gnu.org/licenses/>. {-# LANGUAGE CPP #-} module Main (main) where #if __GLASGOW_HASKELL__ >= 800 #define Cabal2 MIN_VERSION_Cabal(2,0,0) #else -- Hack - we may actually be using Cabal 2.0 with e.g. 7.8 GHC. But -- that's not likely to occur for average user who's relying on -- packages bundled with GHC. The 2.0 Cabal is bundled starting with 8.2.1. #define Cabal2 0 #endif import Data.Version (Version (Version)) import Distribution.Simple.Utils (cabalVersion) import System.Environment (getArgs) #if Cabal2 import qualified Distribution.Version as CabalVersion #endif data Mode = GHC | HLint define :: Mode -> String -> String define GHC def = "-D" ++ def define HLint def = "--cpp-define=" ++ def legacyFlags :: Mode -> [String] legacyFlags mode = [define mode "USE_COMPILER_ID"] isLegacyCabal :: Bool isLegacyCabal = cabalVersion < targetVersion where targetVersion = #if Cabal2 CabalVersion.mkVersion' $ #endif Version [1, 22] [] getMode :: [String] -> Mode getMode ("hlint":_) = HLint getMode _ = GHC main :: IO () main = do args <- getArgs mapM_ putStrLn (flags (getMode args)) where flags mode = if isLegacyCabal then legacyFlags mode else []
mrkkrp/flycheck-haskell
get-flags.hs
gpl-3.0
1,967
0
11
390
292
170
122
28
2
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP #-} {-# LANGUAGE RebindableSyntax, NoMonomorphismRestriction #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE ConstraintKinds #-} module YAPP ( -- * Standard types, classes and related functions -- ** Basic data types Bool(False, True), (&&), (||), not, otherwise, Maybe(Nothing, Just), maybe, Either(Left, Right), either, Ordering(LT, EQ, GT), Char, String, -- *** Tuples fst, snd, curry, uncurry, -- ** Basic type classes Eq((==), (/=)), Ord(compare, (<), (<=), (>=), (>), max, min), Enum(succ, pred, toEnum, fromEnum, enumFrom, enumFromThen, enumFromTo, enumFromThenTo), Bounded(minBound, maxBound), -- ** Numbers -- *** Numeric types Int, Integer, Float, Double, Rational, -- *** Numeric type classes Num((+), (-), (*), negate, abs, signum, fromInteger), Real(toRational), Integral(quot, rem, div, mod, quotRem, divMod, toInteger), Fractional((/), recip, fromRational), Floating(pi, exp, log, sqrt, (**), logBase, sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh), RealFrac(properFraction, truncate, round, ceiling, floor), RealFloat(floatRadix, floatDigits, floatRange, decodeFloat, encodeFloat, exponent, significand, scaleFloat, isNaN, isInfinite, isDenormalized, isIEEE, isNegativeZero, atan2), -- *** Numeric functions subtract, even, odd, gcd, lcm, (^), (^^), fromIntegral, realToFrac, -- * Converting to and from @String@ -- ** Converting to @String@ ShowS, Show(showsPrec, showList, show), shows, showChar, showString, showParen, -- ** Converting from @String@ ReadS, Read(readsPrec, readList), reads, readParen, read, lex, -- * Basic Input and output IO, -- ** Simple I\/O operations -- All I/O functions defined here are character oriented. The -- treatment of the newline character will vary on different systems. -- For example, two characters of input, return and linefeed, may -- read as a single newline character. These functions cannot be -- used portably for binary I/O. -- *** Output functions putChar, putStr, putStrLn, print, -- *** Input functions getChar, getLine, getContents, interact, -- *** Files FilePath, readFile, writeFile, appendFile, readIO, readLn, -- ** Exception handling in the I\/O monad IOError, ioError, userError, -- * Listy operations map, (++), filter, head, last, tail, init, null, length, (!!), reverse, -- ** Reducing lists (folds) foldl, foldl1, foldr, foldr1, -- *** Special folds and, or, any, all, sum, product, concat, concatMap, maximum, minimum, -- ** Building lists -- *** Scans scanl, scanl1, scanr, scanr1, -- *** Infinite lists iterate, repeat, replicate, cycle, -- ** Sublists take, drop, splitAt, takeWhile, dropWhile, span, break, -- ** Searching lists elem, notElem, lookup, -- ** Zipping and unzipping lists zip, zip3, zipWith, zipWith3, unzip, unzip3, -- ** Functions on strings lines, words, unlines, unwords, Foldable (), toList, toApplicMonoid, Traversable (), -- addded fold, foldMap, foldl', foldr', traverse, sequenceA, traverse_, sequenceA_, -- added headS, lastS, tailS, initS, length', iterate', iterateN, iterateN', -- added cycle', cycleN, cycleN', -- added -- ** Miscellaneous functions id, const, (.), flip, ($), until, asTypeOf, error, undefined, seq, ($!), (<<<), (>>>), ifThenElse, ifte, -- added -- ** Monads and functors and semigroupoids, oh my! -- changed severely Functor ((<$)), (<$>), (<$$>), ($>), void, -- map, Apply (), (<*>), (<**>), (<*), (*>), Alt (some, many), (<|>), Plus (), mplus, mzero, Applicative (), WrappedApplicative (WrapApplicative, unwrapApplicative), (~<*>~), Alternative (), WrappedMonad (WrapMonad, unwrapMonad), (~>>=~), Bind (join), (>>=), (=<<), (>>), (<<), (>=>), (<=<), Monad (fail), return, MonadPlus, returning, apDefault, guard, ap, mapM, mapM_, sequence, sequence_, ABMonad, APAlternative, ABPMonadPlus, Semigroupoid (), Category (), (~.~), SCategory, -- Category (id), WrappedCategory (WrapCategory, unwrapCategory), Semi (Semi, getSemi), Semigroup ((<>), sconcat, times1p), timesN, -- (++) WrappedMonoid (WrapMonoid, unwrapMonoid), (~++~), SMonoid, ApplicSemigroup, ApplicMonoid, ApplicSMonoid, Monoid (mempty), Option (Option, getOption), option, ) where import GHC.Base ( Bool (False, True), (&&), (||), not, otherwise , Ordering (LT, EQ, GT) , Char, String , Eq ((==), (/=)) , Ord (compare, (<), (<=), (>=), (>), max, min) , Int , const, flip, ($), until, asTypeOf , error, undefined , seq ) import Text.Read () import GHC.Enum (Enum (succ, pred, toEnum, fromEnum, enumFrom, enumFromThen, enumFromTo, enumFromThenTo) ,Bounded (minBound, maxBound) ) import GHC.Num ( Integer, Num ((+), (-), (*), negate, abs, signum, fromInteger) , subtract ) import GHC.Real ( Rational, Real (toRational) , Integral (quot, rem, div, mod, quotRem, divMod, toInteger) , Fractional ((/), recip, fromRational) , RealFrac (properFraction, truncate, round, ceiling, floor) , even, odd, gcd, lcm, (^), (^^), fromIntegral, realToFrac ) import GHC.Float ( Float, Double , Floating ( pi, exp, log, sqrt, (**), logBase, sin, cos, tan, asin, acos, atan , sinh, cosh, tanh, asinh, acosh, atanh ) , RealFloat ( floatRadix, floatDigits, floatRange, decodeFloat, encodeFloat , exponent, significand, scaleFloat, isNaN, isInfinite, isDenormalized , isIEEE, isNegativeZero, atan2 ) ) import GHC.Show ( ShowS, Show (showsPrec, showList, show) , shows, showChar, showString, showParen ) import Text.Read ( ReadS, Read (readsPrec, readList) , reads, readParen, read, lex ) import qualified Text.ParserCombinators.ReadPrec (ReadPrec) import Data.Either (Either (Left, Right), either) import Data.Maybe (Maybe (Nothing, Just), maybe) import Data.Tuple (fst, snd, curry, uncurry) import System.IO ( IO, putChar, putStr, putStrLn, print , getChar, getLine, getContents, interact , FilePath, readFile, writeFile, appendFile, readIO, readLn ) import System.IO.Error (IOError, ioError, userError) import Prelude (($!)) import Data.Foldable ( Foldable, Foldable (fold, foldMap, foldr, foldr', foldl, foldl' , foldr1, foldl1), mapM_, sequence_, and, or, any, all, sum, product , toList, concat, concatMap, maximum, minimum, elem, notElem , traverse_, sequenceA_ ) import Data.Traversable ( Traversable, Traversable () , traverse, sequenceA , mapM, sequence ) import Data.List ( filter, (!!), reverse , scanl, scanl1, scanr, scanr1 , take, drop, splitAt, takeWhile, dropWhile, span , break, lookup, zip, zip3, zipWith, zipWith3, unzip, unzip3, lines, words ) import qualified Data.Semigroupoid (Semigroupoid (o)) import Data.Semigroupoid (Semigroupoid, WrappedCategory, WrappedCategory (WrapCategory, unwrapCategory), Semi, Semi (Semi, getSemi)) import Control.Category (Category (id)) import Data.Semigroup ( Semigroup, Semigroup ((<>), sconcat, times1p), timesN, WrappedMonoid , WrappedMonoid (WrapMonoid, unwrapMonoid), Monoid , Monoid (mempty), Option, Option (Option, getOption) , option ) import qualified Data.Functor (Functor (fmap)) import Data.Functor (Functor, Functor ((<$)), ($>), (<$>), void) import qualified Data.Functor.Apply (Apply ((<.>), (.>), (<.)), (<..>)) import Data.Functor.Apply (Apply, WrappedApplicative, WrappedApplicative (WrapApplicative, unwrapApplicative)) import qualified Data.Functor.Alt (Alt ((<!>))) import Data.Functor.Alt (Alt, Alt (some, many)) import qualified Data.Functor.Plus (Plus (zero)) import Data.Functor.Plus (Plus) import qualified Control.Applicative (Applicative (pure)) import Control.Applicative (Applicative, Alternative, WrappedMonad, WrappedMonad (WrapMonad, unwrapMonad)) import qualified Data.Functor.Bind (Bind ((>>-)), (-<<), (-<-), (->-)) import Data.Functor.Bind (Bind, Bind (join), returning, apDefault) import Control.Monad (Monad, Monad (fail), MonadPlus) ifThenElse :: Bool -> a -> a -> a ifThenElse p t f = case p of True -> t False -> f ifte :: Bool -> a -> a -> a ifte = ifThenElse type SCategory c = (Semigroupoid c, Category c) infixr 9 . (.) :: Semigroupoid c => c j k -> c i j -> c i k (.) = Data.Semigroupoid.o infixr 9 ~.~ (~.~) :: Category c => c j k -> c i j -> c i k (WrapCategory -> x) ~.~ (WrapCategory -> y) = unwrapCategory $ x . y infixr 1 >>>, <<< (<<<) :: Semigroupoid c => c j k -> c i j -> c i k (<<<) = (.) (>>>) :: Semigroupoid c => c i j -> c j k -> c i k (>>>) = flip (.) type SMonoid m = (Semigroup m, Monoid m) infixr 5 ++ (++) :: Semigroup s => s -> s -> s (++) = (<>) infixr 5 ~++~ (~++~) :: Monoid m => m -> m -> m (WrapMonoid -> x) ~++~ (WrapMonoid -> y) = unwrapMonoid $ x ++ y type ApplicSemigroup t a = (Applicative t, Semigroup (t a)) type ApplicMonoid t a = (Applicative t, Monoid (t a)) type ApplicSMonoid t a = (Applicative t, SMonoid (t a)) type ABMonad m = (Applicative m, Bind m) type APAlternative f = (Applicative f, Plus f) type ABPMonadPlus m = (Applicative m, Bind m, Plus m) map :: Functor f => (a -> b) -> f a -> f b map = Data.Functor.fmap infixl 4 <$$> (<$$>) :: Functor f => f a -> (a -> b) -> f b (<$$>) = flip (<$>) infixl 4 <*>, ~<*>~, <*, *>, <**> (<*>) :: Apply f => f (a -> b) -> f a -> f b (<*>) = (Data.Functor.Apply.<.>) (~<*>~) :: Applicative f => f (a -> b) -> f a -> f b (WrapApplicative -> f) ~<*>~ (WrapApplicative -> x) = unwrapApplicative $ f <*> x (<*) :: Apply f => f a -> f b -> f a (<*) = (Data.Functor.Apply.<.) (*>) :: Apply f => f a -> f b -> f b (*>) = (Data.Functor.Apply..>) (<**>) :: Apply f => f a -> f (a -> b) -> f b (<**>) = (Data.Functor.Apply.<..>) infixl 3 <|> (<|>) :: Alt f => f a -> f a -> f a (<|>) = (Data.Functor.Alt.<!>) mplus :: Alt f => f a -> f a -> f a mplus = (<|>) mzero :: Plus f => f a mzero = Data.Functor.Plus.zero infixl 1 >>, >>=, ~>>=~, <<, =<< (>>=) :: Bind f => f a -> (a -> f b) -> f b (>>=) = (Data.Functor.Bind.>>-) (~>>=~) :: Monad m => m a -> (a -> m b) -> m b (WrapMonad -> x) ~>>=~ ((WrapMonad .) -> f) = unwrapMonad $ x >>= f (=<<) :: Bind f => (a -> f b) -> f a -> f b (=<<) = (Data.Functor.Bind.-<<) (<<) :: Apply f => f a -> f b -> f a (<<) = (<*) (>>) :: Apply f => f a -> f b -> f b (>>) = (*>) infixr 1 <=<, >=> (<=<) :: Bind f => (b -> f c) -> (a -> f b) -> (a -> f c) (<=<) = (Data.Functor.Bind.-<-) (>=>) :: Bind f => (a -> f b) -> (b -> f c) -> (a -> f c) (>=>) = (Data.Functor.Bind.->-) return :: Applicative f => a -> f a return = Control.Applicative.pure guard :: (Alternative f, Plus f) => Bool -> f () guard p = if p then return () else mzero ap :: Apply f => f (a -> b) -> f a -> f b ap = (<*>) toApplicMonoid :: (ApplicSMonoid m i, Foldable t) => t i -> m i toApplicMonoid = foldr ((++) . return) mempty head :: Foldable t => t a -> a head = foldr const (errorEmptyFoldable "head") headS :: Foldable t => t a -> Maybe a headS = foldr (const . Just) Nothing last :: Foldable t => t a -> a last = foldl' (flip const) (errorEmptyFoldable "last") lastS :: Foldable t => t a -> Maybe a lastS = foldl' (const Just) Nothing tail :: (ApplicSMonoid f a, Foldable t) => t a -> f a tail = snd . foldr (\x (p, _) -> (return x ++ p, p)) (mempty, errorEmptyFoldable "tail") tailS :: (ApplicSMonoid f a, Foldable t) => t a -> Maybe (f a) tailS = snd . foldr (\x (p, _) -> (Just (return x) ++ p, p)) (Just mempty, Nothing) init :: (ApplicSMonoid f a, Foldable t) => t a -> f a init = snd . foldl' (\(p, _) x -> (p ++ return x, p)) (mempty, errorEmptyFoldable "init") initS :: (ApplicSMonoid f a, Foldable t) => t a -> Maybe (f a) initS = snd . foldl' (\(p, _) x -> (p ++ Just (return x), p)) (Just mempty, Nothing) null :: Foldable t => t a -> Bool null (headS -> Nothing) = True null _ = False length :: Foldable t => t a -> Integer length = foldr (const (+1)) 0 length' :: (Num n, Foldable t) => t a -> n length' = foldr (const (+1)) 0 iterate :: ApplicSemigroup t (a -> a) => (a -> a) -> a -> t a iterate f x = ($ x) <$> iterate' f id iterate' :: (Semigroupoid c, ApplicSemigroup t (c a b)) => c b b -> c a b -> t (c a b) iterate' f x = return x ++ iterate' f (f . x) iterateN :: ApplicSMonoid t (a -> a) => (a -> a) -> Integer -> a -> t a iterateN f n x = ($ x) <$> iterateN' f n id iterateN' :: (Semigroupoid c, ApplicSMonoid t (c a b)) => c b b -> Integer -> c a b -> t (c a b) iterateN' _ 0 _ = mempty iterateN' f n x = return x ++ iterateN' f (n - 1) (f . x) repeat :: ApplicSemigroup t a => a -> t a repeat x = return x ++ repeat x replicate :: ApplicSMonoid t a => Integer -> a -> t a replicate 0 _ = mempty replicate n x = return x ++ replicate (n - 1) x cycle :: (Semigroup (t a), Foldable t) => t a -> t a cycle (null -> True) = errorEmptyFoldable "cycle" cycle tx = tx ++ cycle tx cycle' :: (Semigroup (t a), Foldable t) => t a -> t a cycle' tx@(null -> True) = tx cycle' tx = tx ++ cycle' tx cycleN :: (SMonoid (t a), Foldable t) => Integer -> t a -> t a cycleN 0 _ = mempty cycleN _ (null -> True) = errorEmptyFoldable "cycleN" cycleN n tx = tx ++ cycleN (n - 1) tx cycleN' :: (SMonoid (t a), Foldable t) => Integer -> t a -> t a cycleN' 0 _ = mempty cycleN' _ tx@(null -> True) = tx cycleN' n tx = tx ++ cycleN' (n - 1) tx errorEmptyFoldable :: String -> a errorEmptyFoldable f = error $ "YAPP."++f++": empty Foldable" unlines :: Foldable t => t String -> String unlines = concatMap (++"\n") unwords :: Foldable t => t String -> String unwords (null -> True) = "" unwords ws = foldr1 (\w s -> w ++ ' ':s) ws instance Apply Text.ParserCombinators.ReadPrec.ReadPrec where (<.>) = (<*>) instance Bind Text.ParserCombinators.ReadPrec.ReadPrec where (>>-) = (>>=) -- From the normal Prelude #ifdef __HADDOCK__ -- | The value of @'seq' a b@ is bottom if @a@ is bottom, and otherwise -- equal to @b@. 'seq' is usually introduced to improve performance by -- avoiding unneeded laziness. seq :: a -> b -> b seq _ y = y #endif
bb010g/yapp
src/YAPP.hs
gpl-3.0
14,898
0
13
3,637
5,534
3,436
2,098
-1
-1
module Main where import Control.Monad (when) import System.Exit import Test.Tasty import ScopeTest import TypeCheckerTest import TemplTest import OperatorTest main :: IO () main = defaultMain $ testGroup "Tests" [ testGroup "Unit Tests" [ scopeTests , typeCheckerTests ] , testGroup "Integration Tests" [ operatorTests , templTests ] ]
ikuehne/craeft-hs
test/Main.hs
gpl-3.0
416
0
9
126
88
51
37
14
1
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} module Model.Identity.TypesTest where -- import Hedgehog -- import qualified Hedgehog.Gen as Gen -- import qualified Hedgehog.Range as Range import Test.Tasty.HUnit import Model.Identity.Types -- import Model.Party.TypesTest -- import Model.Token.TypesTest unit_extractFromIdentifiedSessOrDefault :: Assertion unit_extractFromIdentifiedSessOrDefault = do -- example runExtractFromIdentifiedSessOrDefault NotLoggedIn @?= Default -- typical runExtractFromIdentifiedSessOrDefault IdentityNotNeeded @?= Default runExtractFromIdentifiedSessOrDefault (ReIdentified undefined) @?= Default runExtractFromIdentifiedSessOrDefault (Identified undefined) @?= Extracted runExtractFromIdentifiedSessOrDefault :: Identity -> Result runExtractFromIdentifiedSessOrDefault = extractFromIdentifiedSessOrDefault Default (const Extracted) data Result = Default | Extracted deriving (Eq, Show) unit_identitySuperuser :: Assertion unit_identitySuperuser = do -- typical identitySuperuser (ReIdentified undefined) @? "reidentified is superuser" -- why True? is this because transcoding needs higher privileges to update asset?
databrary/databrary
test/Model/Identity/TypesTest.hs
agpl-3.0
1,201
0
10
151
163
89
74
16
1
module Data.GI.GIR.Function ( Function(..) , parseFunction ) where import Data.Text (Text) import Data.GI.GIR.Callable (Callable(..), parseCallable) import Data.GI.GIR.Parser data Function = Function { fnSymbol :: Text , fnMovedTo :: Maybe Text , fnCallable :: Callable } deriving Show parseFunction :: Parser (Name, Function) parseFunction = do name <- parseName shadows <- queryAttr "shadows" let exposedName = case shadows of Just n -> name {name = n} Nothing -> name callable <- parseCallable symbol <- getAttrWithNamespace CGIRNS "identifier" movedTo <- queryAttr "moved-to" return $ (exposedName, Function { fnSymbol = symbol , fnCallable = callable , fnMovedTo = movedTo })
ford-prefect/haskell-gi
lib/Data/GI/GIR/Function.hs
lgpl-2.1
838
0
14
254
223
126
97
26
2
-- Copyright 2014 Google Inc. All rights reserved. -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- http://www.apache.org/licenses/LICENSE-2.0 -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- This module takes a JSAST and gives each vertex a unique integer label. The label counter is simply -- threaded through the tree. Traversal is depth first. It's all fairly straight-forward. -- -- Top level function is -- (label (jsastListWSMakeSourceFragments (getJSASTWithSource (parseTree program file) file) span)) module LabelJSAST ( ASTChild , ExprChild , IndexChild , JSASTLabel , LabelledExpression(..) , LabelledJSAST(..) , LabelledPropertyName(..) , LabelledValue(..) , OpChild , PropertyNameChild , ValueChild , VarChild , childGetLabel , childGetSource , childWSGetLabel , label ) where import ParseJS import ResolveSourceFragments import System.Environment -- A type for the labels. type JSASTLabel = Int -- A Variable and a label. type VarChild = (Variable, JSASTLabel) -- An Operator and a label. type OpChild = (Operator, JSASTLabel) -- An Index and a label. type IndexChild = (Index, JSASTLabel) -- A VarChild or IndexChild wrapped in a LabelledPropertyName, and a label. Added long after the -- original code was written. -- -- TODO: Test. type PropertyNameChild = (LabelledPropertyName, JSASTLabel) -- A value wrapped as a LabelledValue, and a label. Most LabelledValues contain only the value and -- no label. type ValueChild = (LabelledValue, JSASTLabel) -- A LabelledExpression (which is a labelled subtree) and a label. type ExprChild = (LabelledExpression, JSASTLabel, SourceFragment) -- A LabelledJSAST (which is a labelled subree) an a label. type ASTChild = (LabelledJSAST, JSASTLabel, SourceFragment) -- A wrapper for a VarChild or IndexChild that identifies it as a name for a an object property. data LabelledPropertyName = LabIndexProperty IndexChild | LabVariableProperty VarChild deriving (Show) -- A labelled representation of a literal. LabelledValues representing primitives contain only the -- value and no label. LabelledValues representing objects and arrays are labelled recursively. -- LabUndefined and LabNull have no value or label. data LabelledValue = LabArray [ExprChild] | LabBool Bool | LabDQString String | LabFloat Double | LabInt Int | LabNull | LabObject [ExprChild] | LabString String | LabUndefined deriving (Show) -- FIXME: Some of these contain Maybe *Child values. "Nothing" has no label. Is that a problem? -- -- A recursively labelled subtree, rooted at a LabelledExpression. data LabelledExpression = LabArguments [ExprChild] | LabAssignment OpChild ExprChild ExprChild | LabBinary OpChild ExprChild ExprChild | LabBreak (Maybe VarChild) | LabCall ExprChild ExprChild | LabCallExpression ExprChild OpChild ExprChild | LabContinue (Maybe VarChild) | LabFunctionExpression (Maybe VarChild) [VarChild] ASTChild | LabIdentifier VarChild | LabIndex ExprChild ExprChild | LabList [ExprChild] | LabNew ExprChild | LabParenExpression ExprChild | LabPropNameValue PropertyNameChild ExprChild | LabReference ExprChild ExprChild | LabTernary ExprChild ExprChild ExprChild | LabThrow ExprChild | LabUnaryPost OpChild ExprChild | LabUnaryPre OpChild ExprChild | LabValue ValueChild | LabVarDeclaration VarChild (Maybe ExprChild) deriving (Show) -- A recursively labelled subrtree, rooted at a LabelledJSAST. data LabelledJSAST = LabBlock [ASTChild] | LabCase ExprChild ASTChild | LabCatch VarChild (Maybe ExprChild) ASTChild | LabDefault ASTChild | LabDoWhile ASTChild ExprChild | LabFinally ASTChild | LabFor (Maybe ExprChild) (Maybe ExprChild) (Maybe ExprChild) ASTChild | LabForIn [VarChild] ExprChild ASTChild | LabForVar [ExprChild] (Maybe ExprChild) (Maybe ExprChild) ASTChild | LabForVarIn ExprChild ExprChild ASTChild | LabFunctionBody [ASTChild] | LabFunctionDeclaration VarChild [VarChild] ASTChild | LabIf ExprChild ASTChild | LabIfElse ExprChild ASTChild ASTChild | LabLabelled VarChild ASTChild | LabReturn ExprChild | LabStatement ExprChild | LabSwitch ExprChild ASTChild | LabTry ASTChild ASTChild | LabWhile ExprChild ASTChild deriving (Show) -- Takes an unlabelled AST and labels the whole thing. label :: [JSASTWithSourceFragment] -> [ASTChild] label list = labelJSASTList list 0 -- Extract the JSASTLabel from a VarChild, IndexChild etc. childGetLabel :: (a, JSASTLabel) -> JSASTLabel childGetLabel (child, lab) = lab -- Extract the JSASTLabel from a ASTChild, ExprChild etc. childWSGetLabel :: (a, JSASTLabel, b) -> JSASTLabel childWSGetLabel (_, lab, _) = lab childGetSource :: (a, b, SourceFragment) -> SourceFragment childGetSource (_, _, sf) = sf -- Extract the labels from a list of VarChild, IndexChild etc. listGetLabels :: [(a, JSASTLabel)] -> [JSASTLabel] listGetLabels [] = [] listGetLabels (c:cs) = ((childGetLabel c):(listGetLabels cs)) -- Extract the labels from a list of ASTChild, ExprChild etc. listWSGetLabels :: [(a, JSASTLabel, b)] -> [JSASTLabel] listWSGetLabels [] = [] listWSGetLabels (c:cs) = ((childWSGetLabel c):(listWSGetLabels cs)) -- Find the greater of the label on a Maybe *Child and a given value. maxMaybeLabel :: (Maybe (a, JSASTLabel)) -> JSASTLabel -> JSASTLabel -- If the Maybe *Child is nothing then the given value is the greatest. maxMaybeLabel Nothing v = v maxMaybeLabel (Just e) v = max (childGetLabel e) v -- Find the greater of the label on a Maybe *Child and a given value. maxMaybeWSLabel :: (Maybe (a, JSASTLabel, b)) -> JSASTLabel -> JSASTLabel -- If the Maybe *Child is nothing then the given value is the greatest. maxMaybeWSLabel Nothing v = v maxMaybeWSLabel (Just e) v = max (childWSGetLabel e) v -- Label a list of Varialbes. labelVarList :: [Variable] -> JSASTLabel -> [VarChild] labelVarList [] _ = [] labelVarList (v:vx) n = (v, n + 1):(labelVarList vx (n + 1)) -- Label a list of Expressions. labelExpressionList :: [ExprWithSourceFragment] -> JSASTLabel -> [ExprChild] labelExpressionList [] _ = [] labelExpressionList (e:ex) n = let (le, m, sf) = labelExpression e n in ((le, m, sf):(labelExpressionList ex m)) -- Label a list of JSASTs. labelJSASTList :: [JSASTWithSourceFragment] -> JSASTLabel -> [ASTChild] labelJSASTList [] _ = [] labelJSASTList (a:ax) n = let (la, m, sf) = labelJSAST a n in ((la, m, sf):(labelJSASTList ax m)) -- Label a Varialble. labelVariable :: Variable -> JSASTLabel -> VarChild labelVariable var n = (var, n + 1) -- Label a Maybe Variable if it is not Nothing. labelMaybeVar :: (Maybe Variable) -> JSASTLabel -> (Maybe VarChild) labelMaybeVar Nothing n = Nothing labelMaybeVar (Just var) n = Just (labelVariable var n) -- Label an Operator. labelOperator :: Operator -> JSASTLabel -> OpChild labelOperator op n = (op, n + 1) -- Label an Index. labelIndex :: Index -> JSASTLabel -> IndexChild labelIndex ix n = (ix, n + 1) -- Label a PropertyName. -- -- TODO: Unit test? labelPropertyName :: PropertyName -> JSASTLabel -> PropertyNameChild labelPropertyName (IndexProperty ix) n = (LabIndexProperty field1, (childGetLabel field1) + 1) where field1 = labelIndex ix n labelPropertyName (VariableProperty var) n = (LabVariableProperty field1, (childGetLabel field1) + 1) where field1 = labelVariable var n -- Label a Value. Recursively process any child fields. labelValue :: ValueWithSourceFragment -> JSASTLabel -> ValueChild labelValue (WSInt i) n = (LabInt i, n + 1) labelValue (WSFloat x) n = (LabFloat x, n + 1) labelValue (WSString s) n = (LabString s, n + 1) labelValue (WSBool b) n = (LabBool b, n + 1) labelValue (WSDQString s) n = (LabDQString s, n + 1) labelValue (WSObject props) n = (LabObject field1, (maximum ((listWSGetLabels field1) ++ [n])) + 1) where field1 = labelExpressionList props n labelValue (WSArray el) n = (LabArray field1, (maximum ((listWSGetLabels field1) ++ [n])) + 1) where field1 = labelExpressionList el n labelValue (WSUndefined) n = (LabUndefined, n + 1) labelValue (WSNull) n = (LabNull, n + 1) -- Label an Expression. Recursively process any child fields. labelExpression :: ExprWithSourceFragment -> JSASTLabel -> ExprChild labelExpression (EWSF (WSList ex) sourceFragment) n = ((LabList (field1)), (maximum ((listWSGetLabels field1) ++ [n])) + 1, sourceFragment) where field1 = labelExpressionList ex n labelExpression (EWSF (WSBinary op ex1 ex2) sourceFragment) n = ((LabBinary field1 field2 field3), (childWSGetLabel field3) + 1, sourceFragment) where field1 = labelOperator op n field2 = labelExpression ex1 (childGetLabel field1) field3 = labelExpression ex2 (childWSGetLabel field2) labelExpression (EWSF (WSUnaryPost op ex) sourceFragment) n = ((LabUnaryPost field1 field2), (childWSGetLabel field2) + 1, sourceFragment) where field1 = labelOperator op n field2 = labelExpression ex (childGetLabel field1) labelExpression (EWSF (WSUnaryPre op ex) sourceFragment) n = ((LabUnaryPre field1 field2), (childWSGetLabel field2) + 1, sourceFragment) where field1 = labelOperator op n field2 = labelExpression ex (childGetLabel field1) labelExpression (EWSF (WSTernary ex1 ex2 ex3) sourceFragment) n = ((LabTernary field1 field2 field3), (childWSGetLabel field3) + 1, sourceFragment) where field1 = labelExpression ex1 n field2 = labelExpression ex2 (childWSGetLabel field1) field3 = labelExpression ex3 (childWSGetLabel field2) labelExpression (EWSF (WSAssignment op ex1 ex2) sourceFragment) n = ((LabAssignment field1 field2 field3), (childWSGetLabel field3) + 1, sourceFragment) where field1 = labelOperator op n field2 = labelExpression ex1 (childGetLabel field1) field3 = labelExpression ex2 (childWSGetLabel field2) labelExpression (EWSF (WSIdentifier ident) sourceFragment) n = ((LabIdentifier field1), (childGetLabel field1) + 1, sourceFragment) where field1 = labelVariable ident n labelExpression (EWSF (WSReference ex1 ex2) sourceFragment) n = ((LabReference field1 field2), (childWSGetLabel field2) + 1, sourceFragment) where field1 = labelExpression ex1 n field2 = labelExpression ex2 (childWSGetLabel field1) labelExpression (EWSF (WSIndex ex1 ex2) sourceFragment) n = ((LabIndex field1 field2), (childWSGetLabel field2) + 1, sourceFragment) where field1 = labelExpression ex1 n field2 = labelExpression ex2 (childWSGetLabel field1) labelExpression (EWSF (WSValue val) sourceFragment) n = ((LabValue field1), (childGetLabel field1) + 1, sourceFragment) where field1 = labelValue val n labelExpression (EWSF (WSPropNameValue name ex) sourceFragment) n = ((LabPropNameValue field1 field2), (childWSGetLabel field2) + 1, sourceFragment) where field1 = labelPropertyName name n field2 = labelExpression ex (childGetLabel field1) labelExpression (EWSF (WSCall ex1 ex2) sourceFragment) n = ((LabCall field1 field2), (childWSGetLabel field2) + 1, sourceFragment) where field1 = labelExpression ex1 n field2 = labelExpression ex2 (childWSGetLabel field1) labelExpression (EWSF (WSArguments args) sourceFragment) n = ((LabArguments (field1)), (maximum ((listWSGetLabels field1) ++ [n])) + 1, sourceFragment) where field1 = labelExpressionList args n labelExpression (EWSF (WSParenExpression ex) sourceFragment) n = ((LabParenExpression field1), (childWSGetLabel field1) + 1, sourceFragment) where field1 = labelExpression ex n labelExpression (EWSF (WSBreak vars) sourceFragment) n = ((LabBreak field1), (maxMaybeLabel field1 n) + 1, sourceFragment) where field1 = labelMaybeVar vars n labelExpression (EWSF (WSContinue vars) sourceFragment) n = ((LabContinue field1), (maxMaybeLabel field1 n) + 1, sourceFragment) where field1 = labelMaybeVar vars n labelExpression (EWSF (WSThrow ex) sourceFragment) n = ((LabThrow field1), (childWSGetLabel field1) + 1, sourceFragment) where field1 = labelExpression ex n labelExpression (EWSF (WSCallExpression ex1 op ex2) sourceFragment) n = ((LabCallExpression field1 field2 field3), (childWSGetLabel field3) + 1, sourceFragment) where field1 = labelExpression ex1 n field2 = labelOperator op (childWSGetLabel field1) field3 = labelExpression ex2 (childGetLabel field2) labelExpression (EWSF (WSFunctionExpression var vars ast) sourceFragment) n = ((LabFunctionExpression field1 field2 field3), (childWSGetLabel field3) + 1, sourceFragment) where field1 = labelMaybeVar var n field2 = labelVarList vars (maxMaybeLabel field1 n) field3 = labelJSAST ast (maximum ((listGetLabels field2) ++ [n])) labelExpression (EWSF (WSVarDeclaration var ex) sourceFragment) n = ((LabVarDeclaration field1 field2), (maxMaybeWSLabel field2 (childGetLabel field1)) + 1, sourceFragment) where field1 = labelVariable var n field2 = labelMaybeExpression ex (childGetLabel field1) labelExpression (EWSF (WSNew ex) sourceFragment) n = ((LabNew field1), (childWSGetLabel field1) + 1, sourceFragment) where field1 = labelExpression ex n -- Label a Maybe Expression if it is not Nothing. labelMaybeExpression :: (Maybe ExprWithSourceFragment) -> JSASTLabel -> (Maybe ExprChild) labelMaybeExpression Nothing n = Nothing labelMaybeExpression (Just ex) n = Just $ labelExpression ex n -- Label a JSAST. Recursively process any child fields. labelJSAST :: JSASTWithSourceFragment -> JSASTLabel -> ASTChild labelJSAST (AWSF (WSBlock jsastLs) sourceFragment) n = ((LabBlock field1), (maximum ((listWSGetLabels field1) ++ [n])) + 1, sourceFragment) where field1 = labelJSASTList jsastLs n labelJSAST (AWSF (WSFunctionBody jsastLs) sourceFragment) n = ((LabFunctionBody field1), (maximum ((listWSGetLabels field1) ++ [n])) + 1, sourceFragment) where field1 = labelJSASTList jsastLs n labelJSAST (AWSF (WSFunctionDeclaration var args body) sourceFragment) n = ((LabFunctionDeclaration field1 field2 field3), (childWSGetLabel field3) + 1, sourceFragment) where field1 = labelVariable var n field2 = labelVarList args (childGetLabel field1) field3 = labelJSAST body $ maximum ((listGetLabels field2) ++ [childGetLabel field1]) labelJSAST (AWSF (WSLabelled var body) sourceFragment) n = ((LabLabelled field1 field2), (childWSGetLabel field2) + 1, sourceFragment) where field1 = labelVariable var n field2 = labelJSAST body (childGetLabel field1) labelJSAST (AWSF (WSForVar ex1 ex2 ex3 body) sourceFragment) n = ((LabForVar field1 field2 field3 field4), (childWSGetLabel field4) + 1, sourceFragment) where field1 = labelExpressionList ex1 n field2 = labelMaybeExpression ex2 $ maximum ((listWSGetLabels field1) ++ [n]) field3 = labelMaybeExpression ex3 $ maximum ((listWSGetLabels field1) ++ [maxMaybeWSLabel field2 n]) field4 = labelJSAST body $ maximum ((listWSGetLabels field1) ++ [maxMaybeWSLabel field2 n] ++ [maxMaybeWSLabel field3 n]) labelJSAST (AWSF (WSFor ex1 ex2 ex3 body) sourceFragment) n = ((LabFor field1 field2 field3 field4), (childWSGetLabel field4) + 1, sourceFragment) where field1 = labelMaybeExpression ex1 n field2 = labelMaybeExpression ex2 (maxMaybeWSLabel field1 n) field3 = labelMaybeExpression ex3 $ max (maxMaybeWSLabel field1 n) (maxMaybeWSLabel field2 n) field4 = labelJSAST body $ maximum ([maxMaybeWSLabel field1 n] ++ [maxMaybeWSLabel field2 n] ++ [maxMaybeWSLabel field3 n]) labelJSAST (AWSF (WSForIn vars ex body) sourceFragment) n = ((LabForIn field1 field2 field3), (childWSGetLabel field3) + 1, sourceFragment) where field1 = labelVarList vars n field2 = labelExpression ex $ maximum ((listGetLabels field1) ++ [n]) field3 = labelJSAST body (childWSGetLabel field2) labelJSAST (AWSF (WSForVarIn ex1 ex2 body) sourceFragment) n = ((LabForVarIn field1 field2 field3), (childWSGetLabel field3) + 1, sourceFragment) where field1 = labelExpression ex1 n field2 = labelExpression ex2 (childWSGetLabel field1) field3 = labelJSAST body (childWSGetLabel field2) labelJSAST (AWSF (WSWhile ex body) sourceFragment) n = ((LabWhile field1 field2), (childWSGetLabel field2) + 1, sourceFragment) where field1 = labelExpression ex n field2 = labelJSAST body (childWSGetLabel field1) labelJSAST (AWSF (WSDoWhile body ex) sourceFragment) n = ((LabDoWhile field1 field2), (childWSGetLabel field2) + 1, sourceFragment) where field1 = labelJSAST body n field2 = labelExpression ex (childWSGetLabel field1) labelJSAST (AWSF (WSIf ex body) sourceFragment) n = ((LabIf field1 field2), (childWSGetLabel field2) + 1, sourceFragment) where field1 = labelExpression ex n field2 = labelJSAST body (childWSGetLabel field1) labelJSAST (AWSF (WSIfElse ex bodyT bodyF) sourceFragment) n = ((LabIfElse field1 field2 field3), (childWSGetLabel field3) + 1, sourceFragment) where field1 = labelExpression ex n field2 = labelJSAST bodyT (childWSGetLabel field1) field3 = labelJSAST bodyF (childWSGetLabel field2) labelJSAST (AWSF (WSSwitch ex cs) sourceFragment) n = ((LabSwitch field1 field2), (childWSGetLabel field2) + 1, sourceFragment) where field1 = labelExpression ex n field2 = labelJSAST cs (childWSGetLabel field1) labelJSAST (AWSF (WSCase ex body) sourceFragment) n = ((LabCase field1 field2), (childWSGetLabel field2) + 1, sourceFragment) where field1 = labelExpression ex n field2 = labelJSAST body (childWSGetLabel field1) labelJSAST (AWSF (WSDefault body) sourceFragment) n = ((LabDefault field1), (childWSGetLabel field1) + 1, sourceFragment) where field1 = labelJSAST body n labelJSAST (AWSF (WSTry body ctch) sourceFragment) n = ((LabTry field1 field2), (childWSGetLabel field2) + 1, sourceFragment) where field1 = labelJSAST body n field2 = labelJSAST ctch (childWSGetLabel field1) labelJSAST (AWSF (WSCatch var ex body) sourceFragment) n = ((LabCatch field1 field2 field3), (childWSGetLabel field3) + 1, sourceFragment) where field1 = labelVariable var n field2 = labelMaybeExpression ex (childGetLabel field1) field3 = labelJSAST body (maxMaybeWSLabel field2 (childGetLabel field1)) labelJSAST (AWSF (WSFinally body) sourceFragment) n = ((LabFinally field1), (childWSGetLabel field1) + 1, sourceFragment) where field1 = labelJSAST body n labelJSAST (AWSF (WSReturn ex) sourceFragment) n = ((LabReturn field1), (childWSGetLabel field1) + 1, sourceFragment) where field1 = labelExpression ex n labelJSAST (AWSF (WSStatement ex) sourceFragment) n = ((LabStatement field1), (childWSGetLabel field1) + 1, sourceFragment) where field1 = labelExpression ex n
rjwright/js-typeomatic
LabelJSAST.hs
apache-2.0
19,939
0
13
4,070
5,621
3,019
2,602
327
1
repeat' :: a -> [a] repeat' x = x : repeat' x
Oscarzhao/haskell
learnyouahaskell/repeat.hs
apache-2.0
46
0
6
12
28
14
14
2
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QMessageBox_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:21 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QMessageBox_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 (QMessageBox ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QMessageBox_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QMessageBox_unSetUserMethod" qtc_QMessageBox_unSetUserMethod :: Ptr (TQMessageBox a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QMessageBoxSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QMessageBox_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QMessageBox ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QMessageBox_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QMessageBoxSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QMessageBox_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QMessageBox ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QMessageBox_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QMessageBoxSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QMessageBox_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QMessageBox ()) (QMessageBox x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QMessageBox setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QMessageBox_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QMessageBox_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQMessageBox 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_QMessageBox_setUserMethod" qtc_QMessageBox_setUserMethod :: Ptr (TQMessageBox a) -> CInt -> Ptr (Ptr (TQMessageBox x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QMessageBox :: (Ptr (TQMessageBox x0) -> IO ()) -> IO (FunPtr (Ptr (TQMessageBox x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QMessageBox_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QMessageBoxSc a) (QMessageBox x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QMessageBox setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QMessageBox_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QMessageBox_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQMessageBox 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 (QMessageBox ()) (QMessageBox x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QMessageBox setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QMessageBox_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QMessageBox_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQMessageBox 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_QMessageBox_setUserMethodVariant" qtc_QMessageBox_setUserMethodVariant :: Ptr (TQMessageBox a) -> CInt -> Ptr (Ptr (TQMessageBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QMessageBox :: (Ptr (TQMessageBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQMessageBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QMessageBox_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QMessageBoxSc a) (QMessageBox x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QMessageBox setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QMessageBox_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QMessageBox_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQMessageBox 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 (QMessageBox ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QMessageBox_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QMessageBox_unSetHandler" qtc_QMessageBox_unSetHandler :: Ptr (TQMessageBox a) -> CWString -> IO (CBool) instance QunSetHandler (QMessageBoxSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QMessageBox_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr 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_QMessageBox_setHandler1" qtc_QMessageBox_setHandler1 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox1 :: (Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QMessageBox1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr 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 QchangeEvent_h (QMessageBox ()) ((QEvent t1)) where changeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_changeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_changeEvent" qtc_QMessageBox_changeEvent :: Ptr (TQMessageBox a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent_h (QMessageBoxSc a) ((QEvent t1)) where changeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_changeEvent cobj_x0 cobj_x1 instance QcloseEvent_h (QMessageBox ()) ((QCloseEvent t1)) where closeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_closeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_closeEvent" qtc_QMessageBox_closeEvent :: Ptr (TQMessageBox a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent_h (QMessageBoxSc a) ((QCloseEvent t1)) where closeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_closeEvent cobj_x0 cobj_x1 instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr 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_QMessageBox_setHandler2" qtc_QMessageBox_setHandler2 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox2 :: (Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QMessageBox2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr 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 (QMessageBox ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_event cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_event" qtc_QMessageBox_event :: Ptr (TQMessageBox a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QMessageBoxSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_event cobj_x0 cobj_x1 instance QkeyPressEvent_h (QMessageBox ()) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_keyPressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_keyPressEvent" qtc_QMessageBox_keyPressEvent :: Ptr (TQMessageBox a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent_h (QMessageBoxSc a) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_keyPressEvent cobj_x0 cobj_x1 instance QresizeEvent_h (QMessageBox ()) ((QResizeEvent t1)) where resizeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_resizeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_resizeEvent" qtc_QMessageBox_resizeEvent :: Ptr (TQMessageBox a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent_h (QMessageBoxSc a) ((QResizeEvent t1)) where resizeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_resizeEvent cobj_x0 cobj_x1 instance QshowEvent_h (QMessageBox ()) ((QShowEvent t1)) where showEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_showEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_showEvent" qtc_QMessageBox_showEvent :: Ptr (TQMessageBox a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent_h (QMessageBoxSc a) ((QShowEvent t1)) where showEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_showEvent cobj_x0 cobj_x1 instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qMessageBoxFromPtr 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_QMessageBox_setHandler3" qtc_QMessageBox_setHandler3 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox3 :: (Ptr (TQMessageBox x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQMessageBox x0) -> IO (Ptr (TQSize t0)))) foreign import ccall "wrapper" wrapSetHandler_QMessageBox3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qMessageBoxFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QqsizeHint_h (QMessageBox ()) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_sizeHint cobj_x0 foreign import ccall "qtc_QMessageBox_sizeHint" qtc_QMessageBox_sizeHint :: Ptr (TQMessageBox a) -> IO (Ptr (TQSize ())) instance QqsizeHint_h (QMessageBoxSc a) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_sizeHint cobj_x0 instance QsizeHint_h (QMessageBox ()) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QMessageBox_sizeHint_qth" qtc_QMessageBox_sizeHint_qth :: Ptr (TQMessageBox a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint_h (QMessageBoxSc a) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO () setHandlerWrapper x0 = do x0obj <- qMessageBoxFromPtr 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_QMessageBox_setHandler4" qtc_QMessageBox_setHandler4 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox4 :: (Ptr (TQMessageBox x0) -> IO ()) -> IO (FunPtr (Ptr (TQMessageBox x0) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QMessageBox4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO () setHandlerWrapper x0 = do x0obj <- qMessageBoxFromPtr 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 (QMessageBox ()) (()) where accept_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_accept cobj_x0 foreign import ccall "qtc_QMessageBox_accept" qtc_QMessageBox_accept :: Ptr (TQMessageBox a) -> IO () instance Qaccept_h (QMessageBoxSc a) (()) where accept_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_accept cobj_x0 instance QcontextMenuEvent_h (QMessageBox ()) ((QContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_contextMenuEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_contextMenuEvent" qtc_QMessageBox_contextMenuEvent :: Ptr (TQMessageBox a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent_h (QMessageBoxSc a) ((QContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_contextMenuEvent cobj_x0 cobj_x1 instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> Int -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> CInt -> IO () setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr 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_QMessageBox_setHandler5" qtc_QMessageBox_setHandler5 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox5 :: (Ptr (TQMessageBox x0) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQMessageBox x0) -> CInt -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QMessageBox5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> Int -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> CInt -> IO () setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr 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 (QMessageBox ()) ((Int)) where done_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_done cobj_x0 (toCInt x1) foreign import ccall "qtc_QMessageBox_done" qtc_QMessageBox_done :: Ptr (TQMessageBox a) -> CInt -> IO () instance Qdone_h (QMessageBoxSc a) ((Int)) where done_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_done cobj_x0 (toCInt x1) instance QqminimumSizeHint_h (QMessageBox ()) (()) where qminimumSizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_minimumSizeHint cobj_x0 foreign import ccall "qtc_QMessageBox_minimumSizeHint" qtc_QMessageBox_minimumSizeHint :: Ptr (TQMessageBox a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint_h (QMessageBoxSc a) (()) where qminimumSizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_minimumSizeHint cobj_x0 instance QminimumSizeHint_h (QMessageBox ()) (()) where minimumSizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QMessageBox_minimumSizeHint_qth" qtc_QMessageBox_minimumSizeHint_qth :: Ptr (TQMessageBox a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint_h (QMessageBoxSc a) (()) where minimumSizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance Qreject_h (QMessageBox ()) (()) where reject_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_reject cobj_x0 foreign import ccall "qtc_QMessageBox_reject" qtc_QMessageBox_reject :: Ptr (TQMessageBox a) -> IO () instance Qreject_h (QMessageBoxSc a) (()) where reject_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_reject cobj_x0 instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> Bool -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> CBool -> IO () setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr 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_QMessageBox_setHandler6" qtc_QMessageBox_setHandler6 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox6 :: (Ptr (TQMessageBox x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQMessageBox x0) -> CBool -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QMessageBox6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> Bool -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> CBool -> IO () setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr 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 (QMessageBox ()) ((Bool)) where setVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_setVisible cobj_x0 (toCBool x1) foreign import ccall "qtc_QMessageBox_setVisible" qtc_QMessageBox_setVisible :: Ptr (TQMessageBox a) -> CBool -> IO () instance QsetVisible_h (QMessageBoxSc a) ((Bool)) where setVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_setVisible cobj_x0 (toCBool x1) instance QactionEvent_h (QMessageBox ()) ((QActionEvent t1)) where actionEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_actionEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_actionEvent" qtc_QMessageBox_actionEvent :: Ptr (TQMessageBox a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent_h (QMessageBoxSc a) ((QActionEvent t1)) where actionEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_actionEvent cobj_x0 cobj_x1 instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qMessageBoxFromPtr 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_QMessageBox_setHandler7" qtc_QMessageBox_setHandler7 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox7 :: (Ptr (TQMessageBox x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQMessageBox x0) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QMessageBox7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qMessageBoxFromPtr 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 (QMessageBox ()) (()) where devType_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_devType cobj_x0 foreign import ccall "qtc_QMessageBox_devType" qtc_QMessageBox_devType :: Ptr (TQMessageBox a) -> IO CInt instance QdevType_h (QMessageBoxSc a) (()) where devType_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_devType cobj_x0 instance QdragEnterEvent_h (QMessageBox ()) ((QDragEnterEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_dragEnterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_dragEnterEvent" qtc_QMessageBox_dragEnterEvent :: Ptr (TQMessageBox a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent_h (QMessageBoxSc a) ((QDragEnterEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_dragEnterEvent cobj_x0 cobj_x1 instance QdragLeaveEvent_h (QMessageBox ()) ((QDragLeaveEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_dragLeaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_dragLeaveEvent" qtc_QMessageBox_dragLeaveEvent :: Ptr (TQMessageBox a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent_h (QMessageBoxSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_dragLeaveEvent cobj_x0 cobj_x1 instance QdragMoveEvent_h (QMessageBox ()) ((QDragMoveEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_dragMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_dragMoveEvent" qtc_QMessageBox_dragMoveEvent :: Ptr (TQMessageBox a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent_h (QMessageBoxSc a) ((QDragMoveEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_dragMoveEvent cobj_x0 cobj_x1 instance QdropEvent_h (QMessageBox ()) ((QDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_dropEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_dropEvent" qtc_QMessageBox_dropEvent :: Ptr (TQMessageBox a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent_h (QMessageBoxSc a) ((QDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_dropEvent cobj_x0 cobj_x1 instance QenterEvent_h (QMessageBox ()) ((QEvent t1)) where enterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_enterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_enterEvent" qtc_QMessageBox_enterEvent :: Ptr (TQMessageBox a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent_h (QMessageBoxSc a) ((QEvent t1)) where enterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_enterEvent cobj_x0 cobj_x1 instance QfocusInEvent_h (QMessageBox ()) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_focusInEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_focusInEvent" qtc_QMessageBox_focusInEvent :: Ptr (TQMessageBox a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent_h (QMessageBoxSc a) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_focusInEvent cobj_x0 cobj_x1 instance QfocusOutEvent_h (QMessageBox ()) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_focusOutEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_focusOutEvent" qtc_QMessageBox_focusOutEvent :: Ptr (TQMessageBox a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent_h (QMessageBoxSc a) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_focusOutEvent cobj_x0 cobj_x1 instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr 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_QMessageBox_setHandler8" qtc_QMessageBox_setHandler8 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox8 :: (Ptr (TQMessageBox x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQMessageBox x0) -> CInt -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QMessageBox8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr 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 (QMessageBox ()) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_heightForWidth cobj_x0 (toCInt x1) foreign import ccall "qtc_QMessageBox_heightForWidth" qtc_QMessageBox_heightForWidth :: Ptr (TQMessageBox a) -> CInt -> IO CInt instance QheightForWidth_h (QMessageBoxSc a) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_heightForWidth cobj_x0 (toCInt x1) instance QhideEvent_h (QMessageBox ()) ((QHideEvent t1)) where hideEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_hideEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_hideEvent" qtc_QMessageBox_hideEvent :: Ptr (TQMessageBox a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent_h (QMessageBoxSc a) ((QHideEvent t1)) where hideEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_hideEvent cobj_x0 cobj_x1 instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> InputMethodQuery -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr 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_QMessageBox_setHandler9" qtc_QMessageBox_setHandler9 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox9 :: (Ptr (TQMessageBox x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQMessageBox x0) -> CLong -> IO (Ptr (TQVariant t0)))) foreign import ccall "wrapper" wrapSetHandler_QMessageBox9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> InputMethodQuery -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr 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 (QMessageBox ()) ((InputMethodQuery)) where inputMethodQuery_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QMessageBox_inputMethodQuery" qtc_QMessageBox_inputMethodQuery :: Ptr (TQMessageBox a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery_h (QMessageBoxSc a) ((InputMethodQuery)) where inputMethodQuery_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) instance QkeyReleaseEvent_h (QMessageBox ()) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_keyReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_keyReleaseEvent" qtc_QMessageBox_keyReleaseEvent :: Ptr (TQMessageBox a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent_h (QMessageBoxSc a) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_keyReleaseEvent cobj_x0 cobj_x1 instance QleaveEvent_h (QMessageBox ()) ((QEvent t1)) where leaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_leaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_leaveEvent" qtc_QMessageBox_leaveEvent :: Ptr (TQMessageBox a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent_h (QMessageBoxSc a) ((QEvent t1)) where leaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_leaveEvent cobj_x0 cobj_x1 instance QmouseDoubleClickEvent_h (QMessageBox ()) ((QMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_mouseDoubleClickEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_mouseDoubleClickEvent" qtc_QMessageBox_mouseDoubleClickEvent :: Ptr (TQMessageBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent_h (QMessageBoxSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_mouseDoubleClickEvent cobj_x0 cobj_x1 instance QmouseMoveEvent_h (QMessageBox ()) ((QMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_mouseMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_mouseMoveEvent" qtc_QMessageBox_mouseMoveEvent :: Ptr (TQMessageBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent_h (QMessageBoxSc a) ((QMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_mouseMoveEvent cobj_x0 cobj_x1 instance QmousePressEvent_h (QMessageBox ()) ((QMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_mousePressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_mousePressEvent" qtc_QMessageBox_mousePressEvent :: Ptr (TQMessageBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent_h (QMessageBoxSc a) ((QMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_mousePressEvent cobj_x0 cobj_x1 instance QmouseReleaseEvent_h (QMessageBox ()) ((QMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_mouseReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_mouseReleaseEvent" qtc_QMessageBox_mouseReleaseEvent :: Ptr (TQMessageBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent_h (QMessageBoxSc a) ((QMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_mouseReleaseEvent cobj_x0 cobj_x1 instance QmoveEvent_h (QMessageBox ()) ((QMoveEvent t1)) where moveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_moveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_moveEvent" qtc_QMessageBox_moveEvent :: Ptr (TQMessageBox a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent_h (QMessageBoxSc a) ((QMoveEvent t1)) where moveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_moveEvent cobj_x0 cobj_x1 instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> IO (QPaintEngine t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO (Ptr (TQPaintEngine t0)) setHandlerWrapper x0 = do x0obj <- qMessageBoxFromPtr 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_QMessageBox_setHandler10" qtc_QMessageBox_setHandler10 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox10 :: (Ptr (TQMessageBox x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQMessageBox x0) -> IO (Ptr (TQPaintEngine t0)))) foreign import ccall "wrapper" wrapSetHandler_QMessageBox10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> IO (QPaintEngine t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO (Ptr (TQPaintEngine t0)) setHandlerWrapper x0 = do x0obj <- qMessageBoxFromPtr 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 (QMessageBox ()) (()) where paintEngine_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_paintEngine cobj_x0 foreign import ccall "qtc_QMessageBox_paintEngine" qtc_QMessageBox_paintEngine :: Ptr (TQMessageBox a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine_h (QMessageBoxSc a) (()) where paintEngine_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_paintEngine cobj_x0 instance QpaintEvent_h (QMessageBox ()) ((QPaintEvent t1)) where paintEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_paintEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_paintEvent" qtc_QMessageBox_paintEvent :: Ptr (TQMessageBox a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent_h (QMessageBoxSc a) ((QPaintEvent t1)) where paintEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_paintEvent cobj_x0 cobj_x1 instance QtabletEvent_h (QMessageBox ()) ((QTabletEvent t1)) where tabletEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_tabletEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_tabletEvent" qtc_QMessageBox_tabletEvent :: Ptr (TQMessageBox a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent_h (QMessageBoxSc a) ((QTabletEvent t1)) where tabletEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_tabletEvent cobj_x0 cobj_x1 instance QwheelEvent_h (QMessageBox ()) ((QWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_wheelEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_wheelEvent" qtc_QMessageBox_wheelEvent :: Ptr (TQMessageBox a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent_h (QMessageBoxSc a) ((QWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_wheelEvent cobj_x0 cobj_x1
uduki/hsQt
Qtc/Gui/QMessageBox_h.hs
bsd-2-clause
60,194
0
18
12,814
19,725
9,511
10,214
-1
-1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE RecordWildCards #-} module Data.CRF.Chain2.Pair.FeatMap ( FeatMap (..) ) where import Control.Applicative ((<$>), (<*>)) import Control.Monad (guard) import Data.List (foldl1') import Data.Maybe (catMaybes) import Data.Ix (Ix, inRange, range) import Data.Binary (Binary, put, get) import qualified Data.Array.Unboxed as A import qualified Data.Map as M import Data.CRF.Chain2.Pair.Base import Data.CRF.Chain2.Generic.Internal (FeatIx(..)) import qualified Data.CRF.Chain2.Generic.FeatMap as C -- | Dummy feature index. dummy :: FeatIx dummy = FeatIx (-1) {-# INLINE dummy #-} data FeatMap a = FeatMap { trMap3'1 :: A.UArray (Lb1, Lb1, Lb1) FeatIx , trMap3'2 :: A.UArray (Lb2, Lb2, Lb2) FeatIx , otherMap :: M.Map Feat FeatIx } (!?) :: (Ix i, A.IArray a b) => a i b -> i -> Maybe b m !? x = if inRange (A.bounds m) x then Just (m A.! x) else Nothing {-# INLINE (!?) #-} instance C.FeatMap FeatMap Feat where featIndex (TFeat3'1 x y z) (FeatMap m _ _) = do ix <- m !? (x, y, z) guard (ix /= dummy) return ix featIndex (TFeat3'2 x y z) (FeatMap _ m _) = do ix <- m !? (x, y, z) guard (ix /= dummy) return ix featIndex x (FeatMap _ _ m) = M.lookup x m mkFeatMap xs = FeatMap (mkArray (catMaybes $ map getTFeat3'1 xs)) (mkArray (catMaybes $ map getTFeat3'2 xs)) (M.fromList (filter (isOther . fst) xs)) where getTFeat3'1 (TFeat3'1 x y z, v) = Just ((x, y, z), v) getTFeat3'1 _ = Nothing getTFeat3'2 (TFeat3'2 x y z, v) = Just ((x, y, z), v) getTFeat3'2 _ = Nothing isOther (TFeat3'1 _ _ _) = False isOther (TFeat3'2 _ _ _) = False isOther _ = True mkArray ys = let p = foldl1' updateMin (map fst ys) q = foldl1' updateMax (map fst ys) updateMin (x, y, z) (x', y', z') = (min x x', min y y', min z z') updateMax (x, y, z) (x', y', z') = (max x x', max y y', max z z') zeroed pq = A.array pq [(k, dummy) | k <- range pq] in zeroed (p, q) A.// ys instance Binary (FeatMap Feat) where put FeatMap{..} = put trMap3'1 >> put trMap3'2 >> put otherMap get = FeatMap <$> get <*> get <*> get
kawu/crf-chain2-generic
Data/CRF/Chain2/Pair/FeatMap.hs
bsd-2-clause
2,514
0
16
793
985
540
445
62
2
{-# LANGUAGE RecordWildCards #-} module Node ( rules , Node.FreeSurfer.FreeSurfer (FreeSurfer) , Node.FsInDwi.FsInDwi (FsInDwi) , Node.UKFTractography.UKFTractography (UKFTractography) , Node.WmqlTracts.WmqlTracts (WmqlTracts) , Node.TractMeasures.TractMeasures (..) , Node.Dwi.Dwi (Dwi) ,pathsTractMeasures ,pathsWmql ) where import qualified Node.Software.TractQuerier import qualified Node.Software.BrainsTools import qualified Node.Software.UKFTractography import qualified Node.FreeSurfer import qualified Node.FsInDwi import qualified Node.Dwi import qualified Node.DwiMask import qualified Node.T1w import qualified Node.T2w import qualified Node.T1wMask import qualified Node.T2wMask import qualified Node.Software.TractQuerier import qualified Node.UKFTractography import qualified Node.HCP import qualified Node.WmqlTracts import qualified Node.TractMeasures import Shake.BuildNode (path, (</>)) import Node.Types pathsTractMeasures :: FilePath -> Int -> Node.TractMeasures.TractMeasures -> [(String,FilePath)] pathsTractMeasures projdir idx n@(Node.TractMeasures.TractMeasures{..}) = [("tractmeasures" ++ show idx,projdir </> path n)] ++ pathsWmql projdir idx Node.WmqlTracts.WmqlTracts {..} pathsFsInDwi projdir idx n@(Node.FsInDwi.FsInDwi{..}) = let fs = Node.FreeSurfer.FreeSurfer{..} dwi = Node.Dwi.Dwi{..} dwimask = Node.DwiMask.DwiMask{..} in [("fsindwi" ++ show idx, projdir </> path n)] ++ pathsFs projdir idx fs ++ pathsDwi projdir idx dwi pathsDwi projdir idx n@(Node.Dwi.Dwi{..}) = [("dwi" ++ show idx,projdir </> path n)] pathsDwiMask projdir idx n@(Node.DwiMask.DwiMask{..}) = [("dwimask" ++ show idx,projdir </> path n)] pathsFs projdir idx n@(Node.FreeSurfer.FreeSurfer{..}) = [("fs" ++ show idx,projdir </> path n)] ++ more where more = case fstype of FreeSurferGiven -> [] (FreeSurferUsingMask t1type t1masktype) -> pathsT1w projdir idx Node.T1w.T1w{..} pathsT1w projdir idx n@(Node.T1w.T1w{..}) = [("t1" ++ show idx,projdir </> path n)] pathsWmql projdir idx n@(Node.WmqlTracts.WmqlTracts{..}) = [("wmql" ++ show idx, projdir </> path n)] ++ pathsFs projdir idx Node.FreeSurfer.FreeSurfer{..} ++ pathsDwi projdir idx Node.Dwi.Dwi{..} ++ pathsDwiMask projdir idx Node.DwiMask.DwiMask{..} rules = do Node.FreeSurfer.rules Node.FsInDwi.rules Node.Dwi.rules Node.DwiMask.rules Node.T1w.rules Node.T2w.rules Node.T1wMask.rules Node.T2wMask.rules Node.UKFTractography.rules Node.WmqlTracts.rules Node.TractMeasures.rules Node.Software.UKFTractography.rules Node.Software.TractQuerier.rules Node.Software.BrainsTools.rules Node.HCP.rules
reckbo/ppl
pipeline-lib/Node.hs
bsd-3-clause
2,755
0
12
453
868
494
374
86
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} -- | Utilities for running stack commands. module Stack.Runners ( withGlobalConfigAndLock , withConfigAndLock , withMiniConfigAndLock , withBuildConfigAndLock , withBuildConfig , withBuildConfigExt , loadConfigWithOpts , loadCompilerVersion , withUserFileLock , munlockFile ) where import Control.Monad hiding (forM) import Control.Monad.Logger import Control.Exception.Lifted as EL import Control.Monad.IO.Class import Control.Monad.Trans.Control import Data.IORef import Data.Traversable import Network.HTTP.Client import Path import Path.IO import Stack.Config import qualified Stack.Docker as Docker import qualified Stack.Nix as Nix import Stack.Setup import Stack.Types.Compiler (CompilerVersion) import Stack.Types.Config import Stack.Types.StackT import System.Environment (getEnvironment) import System.IO import System.FileLock loadCompilerVersion :: Manager -> GlobalOpts -> LoadConfig (StackLoggingT IO) -> IO CompilerVersion loadCompilerVersion manager go lc = do bconfig <- runStackLoggingTGlobal manager go $ lcLoadBuildConfig lc (globalCompiler go) return $ bcWantedCompiler bconfig -- | Enforce mutual exclusion of every action running via this -- function, on this path, on this users account. -- -- A lock file is created inside the given directory. Currently, -- stack uses locks per-snapshot. In the future, stack may refine -- this to an even more fine-grain locking approach. -- withUserFileLock :: (MonadBaseControl IO m, MonadIO m) => GlobalOpts -> Path Abs Dir -> (Maybe FileLock -> m a) -> m a withUserFileLock go@GlobalOpts{} dir act = do env <- liftIO getEnvironment let toLock = lookup "STACK_LOCK" env == Just "true" if toLock then do let lockfile = $(mkRelFile "lockfile") let pth = dir </> lockfile ensureDir dir -- Just in case of asynchronous exceptions, we need to be careful -- when using tryLockFile here: EL.bracket (liftIO $ tryLockFile (toFilePath pth) Exclusive) (maybe (return ()) (liftIO . unlockFile)) (\fstTry -> case fstTry of Just lk -> EL.finally (act $ Just lk) (liftIO $ unlockFile lk) Nothing -> do let chatter = globalLogLevel go /= LevelOther "silent" when chatter $ liftIO $ hPutStrLn stderr $ "Failed to grab lock ("++show pth++ "); other stack instance running. Waiting..." EL.bracket (liftIO $ lockFile (toFilePath pth) Exclusive) (liftIO . unlockFile) (\lk -> do when chatter $ liftIO $ hPutStrLn stderr "Lock acquired, proceeding." act $ Just lk)) else act Nothing withConfigAndLock :: GlobalOpts -> StackT Config IO () -> IO () withConfigAndLock go@GlobalOpts{..} inner = do (manager, lc) <- loadConfigWithOpts go withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk -> runStackTGlobal manager (lcConfig lc) go $ Docker.reexecWithOptionalContainer (lcProjectRoot lc) Nothing (runStackTGlobal manager (lcConfig lc) go inner) Nothing (Just $ munlockFile lk) -- | Loads global config, ignoring any configuration which would be -- loaded due to $PWD. withGlobalConfigAndLock :: GlobalOpts -> StackT Config IO () -> IO () withGlobalConfigAndLock go@GlobalOpts{..} inner = do manager <- newTLSManager lc <- runStackLoggingTGlobal manager go $ loadConfigMaybeProject globalConfigMonoid Nothing Nothing withUserFileLock go (configStackRoot $ lcConfig lc) $ \_lk -> runStackTGlobal manager (lcConfig lc) go inner -- For now the non-locking version just unlocks immediately. -- That is, there's still a serialization point. withBuildConfig :: GlobalOpts -> StackT EnvConfig IO () -> IO () withBuildConfig go inner = withBuildConfigAndLock go (\lk -> do munlockFile lk inner) withBuildConfigAndLock :: GlobalOpts -> (Maybe FileLock -> StackT EnvConfig IO ()) -> IO () withBuildConfigAndLock go inner = withBuildConfigExt go Nothing inner Nothing withBuildConfigExt :: GlobalOpts -> Maybe (StackT Config IO ()) -- ^ Action to perform before the build. This will be run on the host -- OS even if Docker is enabled for builds. The build config is not -- available in this action, since that would require build tools to be -- installed on the host OS. -> (Maybe FileLock -> StackT EnvConfig IO ()) -- ^ Action that uses the build config. If Docker is enabled for builds, -- this will be run in a Docker container. -> Maybe (StackT Config IO ()) -- ^ Action to perform after the build. This will be run on the host -- OS even if Docker is enabled for builds. The build config is not -- available in this action, since that would require build tools to be -- installed on the host OS. -> IO () withBuildConfigExt go@GlobalOpts{..} mbefore inner mafter = do (manager, lc) <- loadConfigWithOpts go withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk0 -> do -- A local bit of state for communication between callbacks: curLk <- newIORef lk0 let inner' lk = -- Locking policy: This is only used for build commands, which -- only need to lock the snapshot, not the global lock. We -- trade in the lock here. do dir <- installationRootDeps -- Hand-over-hand locking: withUserFileLock go dir $ \lk2 -> do liftIO $ writeIORef curLk lk2 liftIO $ munlockFile lk $logDebug "Starting to execute command inside EnvConfig" inner lk2 let inner'' lk = do bconfig <- runStackLoggingTGlobal manager go $ lcLoadBuildConfig lc globalCompiler envConfig <- runStackTGlobal manager bconfig go (setupEnv Nothing) runStackTGlobal manager envConfig go (inner' lk) compilerVersion <- loadCompilerVersion manager go lc runStackTGlobal manager (lcConfig lc) go $ Docker.reexecWithOptionalContainer (lcProjectRoot lc) mbefore (runStackTGlobal manager (lcConfig lc) go $ Nix.reexecWithOptionalShell (lcProjectRoot lc) compilerVersion (inner'' lk0)) mafter (Just $ liftIO $ do lk' <- readIORef curLk munlockFile lk') -- | Load the configuration with a manager. Convenience function used -- throughout this module. loadConfigWithOpts :: GlobalOpts -> IO (Manager,LoadConfig (StackLoggingT IO)) loadConfigWithOpts go@GlobalOpts{..} = do manager <- newTLSManager mstackYaml <- forM globalStackYaml resolveFile' lc <- runStackLoggingTGlobal manager go $ do lc <- loadConfig globalConfigMonoid globalResolver mstackYaml -- If we have been relaunched in a Docker container, perform in-container initialization -- (switch UID, etc.). We do this after first loading the configuration since it must -- happen ASAP but needs a configuration. case globalDockerEntrypoint of Just de -> Docker.entrypoint (lcConfig lc) de Nothing -> return () return lc return (manager,lc) withMiniConfigAndLock :: GlobalOpts -> StackT MiniConfig IO () -> IO () withMiniConfigAndLock go@GlobalOpts{..} inner = do manager <- newTLSManager miniConfig <- runStackLoggingTGlobal manager go $ do lc <- loadConfigMaybeProject globalConfigMonoid globalResolver Nothing loadMiniConfig manager (lcConfig lc) runStackTGlobal manager miniConfig go inner -- | Unlock a lock file, if the value is Just munlockFile :: MonadIO m => Maybe FileLock -> m () munlockFile Nothing = return () munlockFile (Just lk) = liftIO $ unlockFile lk
Blaisorblade/stack
src/Stack/Runners.hs
bsd-3-clause
9,018
0
25
2,984
1,793
892
901
174
3
{-# LANGUAGE FlexibleContexts #-} module Obsidian.MonadObsidian.API ((->-), (->>-), threadID, idM, riffle, unriffle, -- oeSplit , -- shuffle, rep, -- iter, -- iter2, fmap, cache, wb, -- two, ilv, parl, -- evens, evens2, odds, riffevens2, -- initS, endS, sort2, cmpSwap, swap, mini,maxi -- module BasicAPI ) where import Obsidian.MonadObsidian.PureAPI import Obsidian.MonadObsidian.Exp import Obsidian.MonadObsidian.Arr import Obsidian.MonadObsidian.AbsC import Obsidian.MonadObsidian.Syncable import Obsidian.MonadObsidian.GPUMonad import Control.Monad import Obsidian.MonadObsidian.Tools -- helper fromInt = fromInteger . toInteger -- binding power instance Functor (Arr s) where fmap f (Arr (ixf,n)) = Arr (f . ixf, n) infixl 8 ->>- (->-) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c (->-) = (>=>) cache :: GArr a -> GPU (SArr a) cache arr = return $ mkArray (\ix -> arr ! ix) (len arr) wb :: SArr a -> GPU (GArr a) wb arr = return $ mkArray (\ix -> arr ! ix) (len arr) threads_maximum = 1024 threadID :: CArr (Exp Int) threadID = mkArray (\ix -> ix) threads_maximum -- pure f a = return $ f a {- evens :: Choice a => ((a,a) -> (a,a)) -> Arr s a -> GPU (Arr s a) evens f arr = let n = len arr in return $ mkArray (\ix -> ifThenElse ((modi ix 2) ==* 0) (ifThenElse ((ix + 1) <* (fromInt n)) (fst (f (arr ! ix,arr ! (ix + 1)))) (arr ! ix)) (ifThenElse (ix <* (fromInt n)) (snd (f (arr ! (ix - 1),arr ! ix))) (arr ! ix))) n -} -- requires even length, or will produce faulty answers evens2 :: Choice a => ((a,a) -> (a,a)) -> Arr s a -> GPU (Arr s a) evens2 f arr = let n = len arr nhalf = (n `div` 2) in return $ mkArray (\ix -> ifThenElse ((ix `modi` 2) ==* 0) (fst (f (arr ! ix,arr ! (ix + 1)))) (snd (f (arr ! (ix - 1),arr ! ix)))) n riffevens2 :: Choice a => ((a,a) -> (a,a)) -> Arr s a -> GPU (Arr s a) riffevens2 f arr = let n = len arr in return $ mkArray (\ix -> ifThenElse ((ix `modi` 2) ==* 0 ) (fst (f (arr ! ix,arr ! ((ix + 1) * 2)))) (fst (f (arr ! (ix `divi` 2),arr ! ix)))) n {- odds :: Choice a => ((a,a) -> (a,a)) -> Arr s a -> GPU (Arr s a) odds f = endS 1 (pure (evens f)) -} {- endS, applies a program to an end segment of an array Todo: #2: look into the type. parhaps its possible to make it more beautiful. -} endS :: Choice a => Int -> (Arr s a -> GPU (Arr s a)) -> Arr s a -> GPU (Arr s a) endS m p arr = do let n = len arr let (a,b) = split m arr (arr1,_) <- local (idM a) (arr2,_) <- local (p b) return $ mkArray ((\ix -> ifThenElse (ix <* (fromInt m)) (arr1 ! ix) (arr2 ! (ix - (fromInt m))))) n {- initS, applies a program to a initial segment of an array -} initS :: Choice a => Int -> (Arr s a -> GPU (Arr s a)) -> Arr s a -> GPU (Arr s a) initS m p arr = do let n = len arr let (a,b) = split m arr (arr1,_) <- local (p a) (arr2,_) <- local (idM b) return $ mkArray ((\ix -> ifThenElse (ix <* (fromInt m)) (arr1 ! ix) (arr2 ! (ix - (fromInt m))))) n -- Longest Even length Initial Segment leis :: Choice a => (Arr s a -> GPU (Arr s a)) -> Arr s a -> GPU (Arr s a) leis p arr = let n = len arr l = if (mod n 2 == 0) then n else (n-1) in initS l p arr {- parl :: Choice b => (Arr a -> W (Arr b)) -> (Arr a -> W (Arr b)) -> Arr a -> W (Arr b) parl p1 p2 arr = do (a,b) <- halve arr (arr1@(ixf,_),c1) <- local (p1 a) (arr2@(ixf',_),c2) <- local (p2 b) --INSPECT C1 and C2 let inspect = (c1 (variable "X" Int),c2 (variable "X" Int)) n = len arr1 n' = len arr2 case inspect of ([Skip],[Skip]) -> return $ mkArray ((\ix -> ifThenElse (ix <* n) (ixf ix) (ixf' (ix - n)))) (n+n') (_,_) -> do write (\ix -> [IfThenElse (unE (ix <* n)) (c1 ix) (c2 (ix - n))] return $ mkArray ((\ix -> ifThenElse (ix <* n) (ixf ix) (ixf' (ix - n)))) (n+n') -} {- The Following functions are an attempt to enable working with Odd lengts (in riffles etc) -} riffle :: Choice a => Arr s a -> GPU (Arr s a) riffle = pure (shuffle . halve) unriffle :: Choice a => Arr s a -> GPU (Arr s a) unriffle = pure (conc . oeSplit) --ilv :: Program (Exp a) (Exp b) -> Program (Exp a) (Exp b) --ilv f = unriffle ->- two f ->- riffle idM :: a -> GPU a idM a = return a {- CMPSWAP AND SWAP, Used in sorters -} cmpSwap :: Choice (a,a) => (a -> a -> Exp Bool) -> (a,a) -> (a,a) cmpSwap op (a,b) = ifThenElse (op a b) (a,b) (b,a) mini (x,y) = ifThenElse (x <* y) x y maxi (x,y) = ifThenElse (x >* y) x y swap (a,b) = (b,a) {- version of riffle limited to even length arrays -} riffle2 :: Choice a => Arr s a -> GPU (Arr s a) riffle2 = leis$ pure (unpair . zipp . halve) {- version of unriffle limited to even length arrays -} unriffle2 :: Choice a => Arr s a -> GPU (Arr s a) unriffle2 = leis$ pure (conc . unzipp . pair) {- sort2 operates on the longest even length initial segment -} sort2 :: Arr s (Exp a) -> GPU (Arr s (Exp a)) sort2 = leis$ pure (unpair . fmap (cmpSwap (<*)) . pair) --swapPairs :: Choice a => Program a a swapPairs :: Choice a => Arr s a -> GPU (Arr s a) swapPairs = leis (pure (unpair . fmap swap . pair)) --two :: Choice b => (Arr a -> W (Arr b)) -> Arr a -> W (Arr b) --two f = parl f f {- version of ilv limited to even length arrays -} --ilv2 :: Program (Exp a) (Exp b) -> Program (Exp a) (Exp b) --ilv2 f = unriffle2 ->- two f ->- riffle2 -- EXPERIMENTAL.. (->>-) a b = a ->- sync ->- b iter :: Int -> (Arr s a -> GPU (Arr s a)) -> Arr s a -> GPU(Arr s a) iter 0 f arr = return arr iter n f arr = do arr' <- f arr iter (n-1) f arr' iter2 :: Monad m => Int -> (a -> m a) -> a -> m a iter2 0 f a = return a iter2 n f a = do a' <- f a iter2 (n-1) f a' rep = iter
svenssonjoel/MonadObsidian
Obsidian/MonadObsidian/API.hs
bsd-3-clause
7,049
0
21
2,765
2,131
1,123
1,008
108
2
module Data.Minecraft.Release18 ( module Data.Minecraft.Release18.Protocol , module Data.Minecraft.Release18.Version ) where import Data.Minecraft.Release18.Protocol import Data.Minecraft.Release18.Version
oldmanmike/hs-minecraft-protocol
src/Data/Minecraft/Release18.hs
bsd-3-clause
213
0
5
21
39
28
11
5
0
{- | Module : SAWScript.SBVParser Description : Parser for .sbv file format. License : BSD3 Maintainer : huffman Stability : provisional -} {-# LANGUAGE ImplicitParams #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} module SAWScript.SBVParser ( loadSBV , parseSBVPgm , UnintMap , Typ(..) , typOf ) where import Prelude hiding (mapM) import Control.Monad.State hiding (mapM) import Data.List (intercalate) import Data.Map (Map) import qualified Data.Map as Map import qualified Data.Text as Text import Data.Traversable (mapM) import Numeric.Natural (Natural) import Verifier.SAW.TypedAST import Verifier.SAW.SharedTerm import qualified SAWScript.SBVModel as SBV import SAWScript.Options type NodeCache = Map SBV.NodeId Term parseSBV :: SharedContext -> NodeCache -> SBV.SBV -> IO (Natural, Term) parseSBV sc _ (SBV.SBV size (Left num)) = do t <- scBvConst sc (fromInteger size) num return (fromInteger size, t) parseSBV _ nodes (SBV.SBV size (Right nodeid)) = case Map.lookup nodeid nodes of Just t -> return (fromIntegral size, t) Nothing -> fail "parseSBV" type UnintMap = String -> Typ -> Maybe Term parseSBVExpr :: Options -> SharedContext -> UnintMap -> NodeCache -> Natural -> SBV.SBVExpr -> IO Term parseSBVExpr _opts sc _unint nodes _size (SBV.SBVAtom sbv) = liftM snd $ parseSBV sc nodes sbv parseSBVExpr opts sc unint nodes size (SBV.SBVApp operator sbvs) = case operator of SBV.BVAdd -> binop scBvAdd sbvs SBV.BVSub -> binop scBvSub sbvs SBV.BVMul -> binop scBvMul sbvs SBV.BVDiv _loc -> binop (error "bvDiv") sbvs SBV.BVMod _loc -> binop (error "bvMod") sbvs SBV.BVPow -> binop (error "bvPow") sbvs SBV.BVIte -> case sbvs of [sbv1, sbv2, sbv3] -> do (_size1, arg1) <- parseSBV sc nodes sbv1 (_size2, arg2) <- parseSBV sc nodes sbv2 (_size3, arg3) <- parseSBV sc nodes sbv3 -- assert size1 == 1 && size2 == size && size3 == size s <- scBitvector sc size cond <- scBv1ToBool sc arg1 scIte sc s cond arg2 arg3 _ -> fail "parseSBVExpr: wrong number of arguments for if-then-else" SBV.BVShl -> shiftop scBvShiftL sbvs SBV.BVShr -> shiftop scBvShiftR sbvs SBV.BVRol -> shiftop scBvRotateL sbvs SBV.BVRor -> shiftop scBvRotateR sbvs SBV.BVExt hi lo | lo >= 0 && hi >= lo -> case sbvs of [sbv1] -> do (size1, arg1) <- parseSBV sc nodes sbv1 unless (size == fromInteger (hi + 1 - lo)) (fail $ "parseSBVExpr BVExt: size mismatch " ++ show (size, hi, lo)) b <- scBoolType sc s1 <- scNat sc (size1 - 1 - fromInteger hi) s2 <- scNat sc size s3 <- scNat sc (fromInteger lo) -- SBV indexes bits starting with 0 = lsb. scSlice sc b s1 s2 s3 arg1 _ -> fail "parseSBVExpr: wrong number of arguments for extract" SBV.BVExt{} -> fail "parseSBVExpr: BVExt bad arguments" SBV.BVAnd -> binop scBvAnd sbvs SBV.BVOr -> binop scBvOr sbvs SBV.BVXor -> binop scBvXor sbvs SBV.BVNot -> case sbvs of [sbv1] -> do (size1, arg1) <- parseSBV sc nodes sbv1 s1 <- scNat sc size1 unless (size == size1) (fail $ "parseSBVExpr BVNot: size mismatch " ++ show (size, size1)) scBvNot sc s1 arg1 _ -> fail "parseSBVExpr: wrong number of arguments for Not" SBV.BVEq -> binrel scBvEq sbvs SBV.BVGeq -> binrel scBvUGe sbvs SBV.BVLeq -> binrel scBvULe sbvs SBV.BVGt -> binrel scBvUGt sbvs SBV.BVLt -> binrel scBvULt sbvs SBV.BVApp -> case sbvs of [sbv1, sbv2] -> do (size1, arg1) <- parseSBV sc nodes sbv1 (size2, arg2) <- parseSBV sc nodes sbv2 s1 <- scNat sc size1 s2 <- scNat sc size2 unless (size == size1 + size2) (fail $ "parseSBVExpr BVApp: size mismatch " ++ show (size, size1, size2)) b <- scBoolType sc -- SBV append takes the most-significant argument -- first, as SAWCore does. scAppend sc s1 s2 b arg1 arg2 _ -> fail "parseSBVExpr: wrong number of arguments for append" SBV.BVLkUp indexSize resultSize -> do (size1 : inSizes, arg1 : args) <- liftM unzip $ mapM (parseSBV sc nodes) sbvs unless (size1 == fromInteger indexSize && all (== (fromInteger resultSize)) inSizes) (fail $ "parseSBVExpr BVLkUp: size mismatch") e <- scBitvector sc (fromInteger resultSize) scMultiMux sc (fromInteger indexSize) e arg1 args SBV.BVUnint _loc _codegen (name, irtyp) -> do let typ = parseIRType irtyp t <- case unint name typ of Just t -> return t Nothing -> do printOutLn opts Warn ("WARNING: unknown uninterpreted function " ++ show (name, typ, size)) printOutLn opts Info ("Using Prelude." ++ name) scGlobalDef sc (mkIdent preludeName (Text.pack name)) args <- mapM (parseSBV sc nodes) sbvs let inSizes = map fst args (TFun inTyp outTyp) = typ unless (sum (typSizes inTyp) == sum (map fromIntegral inSizes)) $ do printOutLn opts Error ("ERROR parseSBVPgm: input size mismatch in " ++ name) printOutFn opts Error (show inTyp) printOutFn opts Error (show inSizes) argument <- combineOutputs sc inTyp args result <- scApply sc t argument results <- splitInputs sc outTyp result let outSizes = typSizes outTyp -- Append bitvector components of result value in lsb order scAppendAll sc (reverse (zip results outSizes)) where -- | scMkOp : (n : Nat) -> Vec n Bool -> Vec n Bool -> Vec n Bool; binop scMkOp [sbv1, sbv2] = do (size1, arg1) <- parseSBV sc nodes sbv1 (size2, arg2) <- parseSBV sc nodes sbv2 unless (size1 == size && size2 == size) (fail $ "parseSBVExpr binop: size mismatch " ++ show (size, size1, size2)) s <- scNat sc size scMkOp sc s arg1 arg2 binop _ _ = fail "parseSBVExpr: wrong number of arguments for binop" -- | scMkRel : (n : Nat) -> Vec n Bool -> Vec n Bool -> Bool; binrel scMkRel [sbv1, sbv2] = do (size1, arg1) <- parseSBV sc nodes sbv1 (size2, arg2) <- parseSBV sc nodes sbv2 unless (size == 1 && size1 == size2) (fail $ "parseSBVExpr binrel: size mismatch " ++ show (size, size1, size2)) s <- scNat sc size1 t <- scMkRel sc s arg1 arg2 scBoolToBv1 sc t binrel _ _ = fail "parseSBVExpr: wrong number of arguments for binrel" -- | scMkOp : (n : Nat) -> Vec n Bool -> Nat -> Vec n Bool; shiftop scMkOp [sbv1, sbv2] = do (size1, arg1) <- parseSBV sc nodes sbv1 (size2, arg2) <- parseSBV sc nodes sbv2 unless (size1 == size) (fail "parseSBVExpr shiftop: size mismatch") s1 <- scNat sc size1 s2 <- scNat sc size2 c <- scBool sc False boolTy <- scBoolType sc scMkOp s1 boolTy s2 c arg1 arg2 shiftop _ _ = fail "parseSBVExpr: wrong number of arguments for binop" scBvShiftL n ty w c v amt = scGlobalApply sc "Prelude.bvShiftL" [n, ty, w, c, v, amt] scBvShiftR n ty w c v amt = scGlobalApply sc "Prelude.bvShiftR" [n, ty, w, c, v, amt] scBvRotateL n ty w _ v amt = scGlobalApply sc "Prelude.bvRotateL" [n, ty, w, v, amt] scBvRotateR n ty w _ v amt = scGlobalApply sc "Prelude.bvRotateR" [n, ty, w, v, amt] ---------------------------------------------------------------------- data SBVAssign = SBVAssign SBV.Size SBV.NodeId SBV.SBVExpr deriving Show data SBVInput = SBVInput SBV.Size SBV.NodeId deriving Show type SBVOutput = SBV.SBV partitionSBVCommands :: [SBV.SBVCommand] -> ([SBVAssign], [SBVInput], [SBVOutput]) partitionSBVCommands = foldr select ([], [], []) where select cmd (assigns, inputs, outputs) = case cmd of SBV.Decl _ (SBV.SBV _ (Left _)) _ -> error "invalid SBV command: ground value on lhs" SBV.Decl _ (SBV.SBV size (Right nodeid)) Nothing -> (assigns, SBVInput size nodeid : inputs, outputs) SBV.Decl _ (SBV.SBV size (Right nodeid)) (Just expr) -> (SBVAssign size nodeid expr : assigns, inputs, outputs) SBV.Output sbv -> (assigns, inputs, sbv : outputs) -- TODO: Should I use a state monad transformer? parseSBVAssign :: Options -> SharedContext -> UnintMap -> NodeCache -> SBVAssign -> IO NodeCache parseSBVAssign opts sc unint nodes (SBVAssign size nodeid expr) = do term <- parseSBVExpr opts sc unint nodes (fromInteger size) expr return (Map.insert nodeid term nodes) ---------------------------------------------------------------------- data Typ = TBool | TFun Typ Typ | TVec SBV.Size Typ | TTuple [Typ] | TRecord [(FieldName, Typ)] instance Show Typ where show TBool = "." show (TFun t1 t2) = "(" ++ show t1 ++ " -> " ++ show t2 ++ ")" show (TVec size t) = "[" ++ show size ++ "]" ++ show t show (TTuple ts) = "(" ++ intercalate "," (map show ts) ++ ")" show (TRecord fields) = "{" ++ intercalate "," (map showField fields) ++ "}" where showField (s, t) = Text.unpack s ++ ":" ++ show t parseIRType :: SBV.IRType -> Typ parseIRType (SBV.TApp "." []) = TBool parseIRType (SBV.TApp "->" [a, b]) = TFun (parseIRType a) (parseIRType b) parseIRType (SBV.TApp ":" [SBV.TInt n, a]) = TVec n (parseIRType a) parseIRType (SBV.TApp c ts) | c == "(" ++ replicate (length ts - 1) ',' ++ ")" = TTuple (map parseIRType ts) parseIRType (SBV.TRecord fields) = TRecord [ (Text.pack name, parseIRType t) | (name, SBV.Scheme [] [] [] t) <- fields ] parseIRType t = error ("parseIRType: " ++ show t) typSizes :: Typ -> [SBV.Size] typSizes TBool = [1] typSizes (TTuple ts) = concatMap typSizes ts typSizes (TVec n TBool) = [n] typSizes (TVec n t) = concat (replicate (fromIntegral n) (typSizes t)) typSizes (TRecord fields) = concatMap (typSizes . snd) fields typSizes (TFun _ _) = error "typSizes: not a first-order type" scTyp :: SharedContext -> Typ -> IO Term scTyp sc TBool = scBoolType sc scTyp sc (TFun a b) = do s <- scTyp sc a t <- scTyp sc b scFun sc s t scTyp sc (TVec n TBool) = do scBitvector sc (fromInteger n) scTyp sc (TVec n t) = do ty <- scTyp sc t ntm <- scNat sc (fromInteger n) scVecType sc ntm ty scTyp sc (TTuple as) = do ts <- mapM (scTyp sc) as scTupleType sc ts scTyp sc (TRecord fields) = do tm <- mapM (\(f,t) -> (f,) <$> scTyp sc t) fields scRecordType sc tm -- | projects all the components out of the input term -- TODO: rename to splitInput? splitInputs :: SharedContext -> Typ -> Term -> IO [Term] splitInputs _sc TBool x = return [x] splitInputs sc (TTuple ts) x = do xs <- mapM (\i -> scTupleSelector sc x i (length ts)) [1 .. length ts] yss <- sequence (zipWith (splitInputs sc) ts xs) return (concat yss) splitInputs _ (TVec _ TBool) x = return [x] splitInputs sc (TVec n t) x = do nt <- scNat sc (fromIntegral n) idxs <- mapM (scNat sc . fromIntegral) [0 .. (n - 1)] ty <- scTyp sc t xs <- mapM (scAt sc nt ty x) idxs yss <- mapM (splitInputs sc t) xs return (concat yss) splitInputs _ (TFun _ _) _ = error "splitInputs TFun: not a first-order type" splitInputs sc (TRecord fields) x = do let (names, ts) = unzip fields xs <- mapM (scRecordSelect sc x) names yss <- sequence (zipWith (splitInputs sc) ts xs) return (concat yss) ---------------------------------------------------------------------- -- | Combines outputs into a data structure according to Typ combineOutputs :: SharedContext -> Typ -> [(Natural, Term)] -> IO Term combineOutputs sc ty xs0 = do (z, ys) <- runStateT (go ty) xs0 unless (null ys) (fail $ "combineOutputs: too many outputs: " ++ show (length ys) ++ " remaining") return z where pop :: StateT [(Natural, Term)] IO (Natural, Term) pop = do xs <- get case xs of [] -> fail "combineOutputs: too few outputs" y : ys -> put ys >> return y go :: Typ -> StateT [(Natural, Term)] IO Term go TBool = do (_, x) <- pop lift (scBv1ToBool sc x) go (TTuple ts) = do xs <- mapM go ts lift (scTuple sc xs) -- | SBV files may encode values of type '[n]Bool' in one of two -- ways: as a single n-bit word, or as a list of n 1-bit words. go (TVec n TBool) = do (n', x) <- pop case () of () | n' == fromIntegral n -> return x | n' == 1 -> do (sizes, xs) <- fmap unzip $ replicateM (fromIntegral n - 1) pop unless (all (== 1) sizes) $ fail $ "combineOutputs: can't read SBV bitvector: " ++ show sizes ++ " doesn't equal " ++ show n -- Append 1-bit words, lsb first (TODO: is this right?) lift $ scAppendAll sc $ reverse [ (t, 1) | t <- x : xs ] | otherwise -> fail $ "combineOutputs: can't read SBV bitvector from " ++ show n' ++ " arguments" go (TVec n t) = do xs <- replicateM (fromIntegral n) (go t) ety <- lift (scTyp sc t) lift (scVector sc ety xs) go (TRecord fields) = do let (names, ts) = unzip fields xs <- mapM go ts lift (scRecord sc (Map.fromList (zip names xs))) go (TFun _ _) = fail "combineOutputs: not a first-order type" ---------------------------------------------------------------------- parseSBVPgm :: Options -> SharedContext -> UnintMap -> SBV.SBVPgm -> IO Term parseSBVPgm opts sc unint (SBV.SBVPgm (_version, irtype, revcmds, _vcs, _warnings, _uninterps)) = do let (TFun inTyp outTyp) = parseIRType irtype let cmds = reverse revcmds let (assigns, inputs, outputs) = partitionSBVCommands cmds let inSizes = [ size | SBVInput size _ <- inputs ] let inNodes = [ node | SBVInput _ node <- inputs ] unless (typSizes inTyp == inSizes) (fail "parseSBVPgm: input size mismatch") inputType <- scTyp sc inTyp inputVar <- scLocalVar sc 0 inputTerms <- splitInputs sc inTyp inputVar let nodes0 = Map.fromList (zip inNodes inputTerms) nodes <- foldM (parseSBVAssign opts sc unint) nodes0 assigns outputTerms <- mapM (parseSBV sc nodes) outputs outputTerm <- combineOutputs sc outTyp outputTerms scLambda sc "x" inputType outputTerm ---------------------------------------------------------------------- -- New SharedContext operations; should eventually move to SharedTerm.hs. -- | bv1ToBool : Vec 1 Bool -> Bool -- bv1ToBool x = bvAt 1 Bool 1 x (bv 1 0) scBv1ToBool :: SharedContext -> Term -> IO Term scBv1ToBool sc x = do n0 <- scNat sc 0 n1 <- scNat sc 1 b <- scBoolType sc bv <- scBvNat sc n1 n0 scBvAt sc n1 b n1 x bv -- | boolToBv1 :: Bool -> Vec 1 Bool scBoolToBv1 :: SharedContext -> Term -> IO Term scBoolToBv1 sc x = do b <- scBoolType sc scSingle sc b x -- see if it's the same error scMultiMux :: SharedContext -> Natural -> Term -> Term -> [Term] -> IO Term scMultiMux sc iSize e i args = do vec <- scVector sc e args w <- scNat sc iSize m <- scNat sc (fromIntegral (length args)) scBvAt sc m e w vec i scAppendAll :: SharedContext -> [(Term, Integer)] -> IO Term scAppendAll _ [] = error "scAppendAll: unimplemented" scAppendAll _ [(x, _)] = return x scAppendAll sc ((x, size1) : xs) = do let size2 = sum (map snd xs) b <- scBoolType sc s1 <- scNat sc (fromInteger size1) s2 <- scNat sc (fromInteger size2) y <- scAppendAll sc xs scAppend sc s1 s2 b x y typOf :: SBV.SBVPgm -> Typ typOf (SBV.SBVPgm (_, irtype, _, _, _, _)) = parseIRType irtype loadSBV :: FilePath -> IO SBV.SBVPgm loadSBV = SBV.loadSBV
GaloisInc/saw-script
src/SAWScript/SBVParser.hs
bsd-3-clause
16,812
0
23
5,160
5,666
2,789
2,877
328
33
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE RecordWildCards #-} module ANTPlus.DeviceProfile.HeartRateMonitor where import ANTPlus.Network import Control.Monad import Control.Concurrent.Async (withAsync) import Control.Concurrent.STM import Data.Bits import Data.Word import qualified ANTPlus import qualified Data.ByteString as BS data HeartRateMonitor = HeartRateMonitor {heartRatePages :: !(TChan HeartRatePage)} data HeartRatePage = HeartRatePage {hrmPage :: !PageDetails ,hrmHeartBeatEventTime :: !Word64 ,hrmHeartBeatCount :: !Word8 ,hrmComputedHeartRate :: !Word8} deriving (Show) data PageDetails = PageZero | PageOperatingTime !OperatingTime | PageIdentification !Identification | PageVersion !Version | PagePreviousHeartBeatTime !PreviousHeartBeatTime | PageUnknown deriving (Show) data OperatingTime = OperatingTime {operatingTime :: !Word64} deriving (Show) data Identification = Identification {identificationManufacturer :: !Word8 ,identificationSerialNumber :: !Word16} deriving (Show) data Version = Version {versionHardware :: !Word8 ,versionSoftware :: !Word8 ,versionModel :: !Word8} deriving (Show) data PreviousHeartBeatTime = PreviousHeartBeatTime {previousHeartBeatManufacturerSSpecific :: !Word8 ,previousHeartBeatTime :: !Word16} deriving (Show) withHeartRateMonitor :: Network -> (HeartRateMonitor -> IO a) -> IO a withHeartRateMonitor network m = withChannel network 0 (\c -> do setChannelId c (ANTPlus.DeviceNumber 0) False 120 0 setChannelRFFreq c 57 setChannelPeriod c 8070 openChannel c pages <- newBroadcastTChanIO withReader (networkAnt network) (isHRMMessage c) (\hrmMsgs -> withAsync (forever (do bytes <- atomically (readTBQueue hrmMsgs) case parsePage bytes of Just page -> atomically (writeTChan pages page) Nothing -> putStrLn ("Unknown HRM packet: " ++ show bytes))) (\_ -> m (HeartRateMonitor pages)))) where isHRMMessage Channel{..} = \case ANTPlus.BroadcastData ANTPlus.BroadcastDataPayload{..} | broadcastDataChannelNumber == channelNumber -> Just broadcastDataData ANTPlus.AcknowledgedData ANTPlus.AcknowledgedDataPayload{..} | acknowledgedDataChannelNumber == channelNumber -> Just acknowledgedDataData ANTPlus.BurstData ANTPlus.BurstDataPayload{..} | burstDataChannelNumber == channelNumber -> Just burstDataData _ -> Nothing pattern PAGE_TOGGLE = 0x80 parsePage :: BS.ByteString -> Maybe HeartRatePage parsePage bytes = case BS.unpack bytes of [pageNumber,a,b,c,eventTimeLsb,eventTimeMsb,beatCount,heartRate] -> Just (HeartRatePage (case pageNumber .&. complement PAGE_TOGGLE of 0 -> PageZero 1 -> PageOperatingTime (OperatingTime (fromIntegral a .|. shiftL (fromIntegral b) 8 .|. shiftL (fromIntegral c) 16)) 2 -> PageIdentification (Identification a (fromIntegral b .|. shiftL (fromIntegral c) 8)) 3 -> PageVersion (Version a b c) 4 -> PagePreviousHeartBeatTime (PreviousHeartBeatTime a (fromIntegral b .|. shiftL (fromIntegral c) 8)) _ -> PageUnknown) (fromIntegral eventTimeLsb .|. shiftL (fromIntegral eventTimeMsb) 8) beatCount heartRate) _ -> Nothing newHeartRatePageReader :: HeartRateMonitor -> IO (STM HeartRatePage) newHeartRatePageReader (HeartRateMonitor broadcast) = do pages <- atomically (dupTChan broadcast) pure (readTChan pages)
ocharles/ant-plus
src/ANTPlus/DeviceProfile/HeartRateMonitor.hs
bsd-3-clause
4,487
0
25
1,618
977
496
481
152
7
----------------------------------------------------------------------------- -- | -- Module : TestSuite.Puzzles.PowerSet -- Copyright : (c) Levent Erkok -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- -- Test suite for Examples.Puzzles.PowerSet ----------------------------------------------------------------------------- module TestSuite.Puzzles.PowerSet(tests) where import Utils.SBVTestFramework tests :: TestTree tests = testGroup "Puzzles.PowerSet" [ testCase ("powerSet " ++ show i) (assert (pSet i)) | i <- [0 .. 7] ] pSet :: Int -> IO Bool pSet n = do cnt <- numberOfModels $ do _ <- mapM (\i -> sBool ("e" ++ show i)) [1..n] -- Look ma! No constraints! return (true :: SBool) return (cnt == 2^n)
josefs/sbv
SBVTestSuite/TestSuite/Puzzles/PowerSet.hs
bsd-3-clause
860
0
18
219
185
101
84
10
1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} -- | -- Module : Data.Binary.Serialise.CBOR -- Copyright : (c) Duncan Coutts 2015 -- License : BSD3-style (see LICENSE.txt) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- This module provides functions to serialise and deserialise Haskell -- values for storage or transmission, to and from lazy -- @'Data.ByteString.Lazy.ByteString'@s. It also provides a type class -- and utilities to help you make your types serialisable. -- -- For a full tutorial on using this module, see -- "Data.Binary.Serialise.CBOR.Tutorial". -- module Data.Binary.Serialise.CBOR ( -- * High level, one-shot API -- $highlevel serialise , deserialise , deserialiseOrFail -- * Deserialisation exceptions , DeserialiseFailure(..) -- * Incremental encoding interface -- $primitives , serialiseIncremental , deserialiseIncremental -- * The @'Serialise'@ class , Serialise(..) -- * IO operations -- | Convenient utilities for basic @'IO'@ operations. -- ** @'FilePath'@ API , writeFileSerialise , readFileDeserialise -- ** @'Handle'@ API , hPutSerialise ) where #include "cbor.h" import System.IO (Handle, IOMode (..), withFile) import Data.Typeable (Typeable) import Control.Exception (Exception(..), throw, throwIO) import qualified Data.Binary.Get as Bin import qualified Data.ByteString.Builder as BS import qualified Data.ByteString.Lazy as BS import qualified Data.ByteString.Lazy.Internal as BS import Data.Binary.Serialise.CBOR.Class import qualified Data.Binary.Serialise.CBOR.Read as CBOR.Read import qualified Data.Binary.Serialise.CBOR.Write as CBOR.Write -------------------------------------------------------------------------------- -- $primitives -- The following API allows you to encode or decode CBOR values incrementally, -- which is useful for large structures that require you to stream values in -- over time. -- -- | Serialise a Haskell value to an external binary representation. -- -- The output is represented as a 'BS.Builder' and is constructed incrementally. -- The representation as a 'BS.Builder' allows efficient concatenation with -- other data. serialiseIncremental :: Serialise a => a -> BS.Builder serialiseIncremental = CBOR.Write.toBuilder . encode -- | Deserialise a Haskell value from the external binary representation. -- -- This allows /input/ data to be provided incrementally, rather than all in one -- go. It also gives an explicit representation of deserialisation errors. -- -- Note that the incremental behaviour is only for the input data, not the -- output value: the final deserialised value is constructed and returned as a -- whole, not incrementally. deserialiseIncremental :: Serialise a => Bin.Decoder a deserialiseIncremental = CBOR.Read.deserialiseIncremental decode -------------------------------------------------------------------------------- -- $highlevel -- The following API exposes a high level interface allowing you to quickly -- convert between arbitrary Haskell values (which are an instance of -- @'Serialise'@) and lazy @'BS.ByteString'@s. -- -- | Serialise a Haskell value to an external binary representation. -- -- The output is represented as a lazy 'BS.ByteString' and is constructed -- incrementally. serialise :: Serialise a => a -> BS.ByteString serialise = CBOR.Write.toLazyByteString . encode -- | Deserialise a Haskell value from the external binary representation -- (which must have been made using 'serialise' or related function). -- -- /Throws/: @'DeserialiseFailure'@ if the given external representation is -- invalid or does not correspond to a value of the expected type. deserialise :: Serialise a => BS.ByteString -> a deserialise = supplyAllInput deserialiseIncremental where supplyAllInput (Bin.Done _ _ x) _bs = x supplyAllInput (Bin.Partial k) bs = case bs of BS.Chunk chunk bs' -> supplyAllInput (k (Just chunk)) bs' BS.Empty -> supplyAllInput (k Nothing) BS.Empty supplyAllInput (Bin.Fail _ off msg) _ = throw (DeserialiseFailure off msg) -- | An exception type that may be returned (by pure functions) or -- thrown (by IO actions) that fail to deserialise a given input. data DeserialiseFailure = DeserialiseFailure Bin.ByteOffset String deriving (Show, Typeable) instance Exception DeserialiseFailure where #if MIN_VERSION_base(4,8,0) displayException (DeserialiseFailure off msg) = "Data.Binary.Serialise.CBOR: deserialising failed at offset " ++ show off ++ " : " ++ msg #endif -- | Deserialise a Haskell value from the external binary representation, -- or get back a @'DeserialiseFailure'@. deserialiseOrFail :: Serialise a => BS.ByteString -> Either DeserialiseFailure a deserialiseOrFail = supplyAllInput deserialiseIncremental where supplyAllInput (Bin.Done _ _ x) _bs = Right x supplyAllInput (Bin.Partial k) bs = case bs of BS.Chunk chunk bs' -> supplyAllInput (k (Just chunk)) bs' BS.Empty -> supplyAllInput (k Nothing) BS.Empty supplyAllInput (Bin.Fail _ offset msg) _ = Left (DeserialiseFailure offset msg) -------------------------------------------------------------------------------- -- File-based API -- | Serialise a @'BS.ByteString'@ (via @'serialise'@) and write it directly -- to the specified @'Handle'@. hPutSerialise :: Serialise a => Handle -- ^ The @'Handle'@ to write to. -> a -- ^ The value to be serialized and written. -> IO () hPutSerialise hnd x = BS.hPut hnd (serialise x) -- | Serialise a @'BS.ByteString'@ and write it directly to the -- specified file. writeFileSerialise :: Serialise a => FilePath -- ^ The file to write to. -> a -- ^ The value to be serialized and written. -> IO () writeFileSerialise fname x = withFile fname WriteMode $ \hnd -> hPutSerialise hnd x -- | Read the specified file (internally, by reading a @'BS.ByteString'@) -- and attempt to decode it into a Haskell value using @'deserialise'@ -- (the type of which is determined by the choice of the result type). -- -- /Throws/: @'DeserialiseFailure'@ iff the file fails to -- deserialise properly. readFileDeserialise :: Serialise a => FilePath -- ^ The file to read from. -> IO a -- ^ The deserialized value. readFileDeserialise fname = withFile fname ReadMode $ \hnd -> do input <- BS.hGetContents hnd case deserialiseOrFail input of Left err -> throwIO err Right x -> return x
arianvp/binary-serialise-cbor
Data/Binary/Serialise/CBOR.hs
bsd-3-clause
6,939
0
14
1,525
917
529
388
73
4
module Language.SimPOL.Template.Obs where import Language.SimPOL import qualified Data.POL.Observable as Obs import Control.Monad.Trans.Class at :: Time -> Obs Bool at t = labeled (nullary "time") (lift now) Obs.== constant t before :: Time -> Obs Bool before t = labeled (nullary "time") (lift now) Obs.< constant t after :: Time -> Obs Bool after t = labeled (nullary "time") (lift now) Obs.> constant t between :: Time -> Time -> Obs Bool between s t = (at s Obs.|| at t) Obs.|| strictbetween s t strictbetween :: Time -> Time -> Obs Bool strictbetween s t = after s Obs.&& before t occurs :: String -> Obs Bool occurs e = labeled (nullary (e ++ " occurs")) (fmap ((elem e) . events) (lift now)) -- vim: ft=haskell:sts=2:sw=2:et:nu:ai
ZjMNZHgG5jMXw/privacy-option-simpol
Language/SimPOL/Template/Obs.hs
bsd-3-clause
740
0
11
128
323
164
159
17
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Test.IO.Zodiac.Raw.TSRP where import Data.ByteString (ByteString) import Data.Time (UTCTime) import Disorder.Core.IO (testIO) import Disorder.Core.Property (failWith) import Disorder.Core.Run (ExpectedTestSpeed(..), disorderCheckEnvAll) import P import System.IO (IO) import Test.Zodiac.TSRP.Arbitrary () import Test.QuickCheck import Test.QuickCheck.Instances () import Test.Zodiac.Core.Gen import Tinfoil.Data (Verified(..)) import Zodiac.TSRP.Data import Zodiac.Raw.Error import Zodiac.Raw.Request import Zodiac.Raw.TSRP prop_verifyRawRequest' :: KeyId -> RequestTimestamp -> RequestExpiry -> CRequest -> TSRPKey -> Property prop_verifyRawRequest' kid rt re cr sk = forAll (genTimeWithin rt re) $ \now -> let req = fromCanonicalRequest cr in case authedRawRequest kid sk re req rt of Left e -> failWith $ "authentication unexpectedly failed: " <> renderRequestError e Right ar -> testIO $ do r <- verifyRawRequest' kid sk ar now pure $ r === Verified prop_verifyRawRequest_junk :: KeyId -> TSRPKey -> UTCTime -> ByteString -> Property prop_verifyRawRequest_junk kid sk now ar = testIO $ do r <- verifyRawRequest' kid sk ar now pure $ r === NotVerified return [] tests :: IO Bool tests = $disorderCheckEnvAll TestRunMore
ambiata/zodiac
zodiac-raw/test/Test/IO/Zodiac/Raw/TSRP.hs
bsd-3-clause
1,776
0
16
613
395
216
179
46
2
{-# LANGUAGE ScopedTypeVariables, BangPatterns #-} -- K-Means sample from "Parallel and Concurrent Programming in Haskell" -- -- With three versions: -- [ kmeans_seq ] a sequential version -- [ kmeans_strat ] a parallel version using Control.Parallel.Strategies -- [ kmeans_par ] a parallel version using Control.Monad.Par -- -- Usage (sequential): -- $ ./kmeans seq -- -- Usage (Strategies): -- $ ./kmeans strat 600 +RTS -N4 -- -- Usage (Par monad): -- $ ./kmeans par 600 +RTS -N4 -- -- Usage (divide-and-conquer / Par monad): -- $ ./kmeans divpar 7 +RTS -N4 -- -- Usage (divide-and-conquer / Eval monad): -- $ ./kmeans diveval 7 +RTS -N4 import System.IO import KMeansCore import Data.Array import Data.Array.Unsafe as Unsafe import Text.Printf import Data.List import Data.Function import Data.Binary (decodeFile) import Debug.Trace import Control.Parallel.Strategies as Strategies import Control.Monad.Par as Par import Control.DeepSeq import System.Environment import Data.Time.Clock import Control.Exception import Control.Concurrent import Control.Monad.ST import Data.Array.ST import System.Mem import Data.Maybe import qualified Data.Vector as Vector import Data.Vector (Vector) import qualified Data.Vector.Mutable as MVector -- ----------------------------------------------------------------------------- -- main: read input files, time calculation main = runInUnboundThread $ do points <- decodeFile "points.bin" clusters <- read `fmap` readFile "clusters" let nclusters = length clusters args <- getArgs npoints <- evaluate (length points) performGC t0 <- getCurrentTime final_clusters <- case args of ["seq" ] -> kmeans_seq nclusters points clusters ["strat", n] -> kmeans_strat (read n) nclusters points clusters ["par", n] -> kmeans_par (read n) nclusters points clusters ["divpar", n] -> kmeans_div_par (read n) nclusters points clusters npoints ["diveval", n] -> kmeans_div_eval (read n) nclusters points clusters npoints _other -> error "args" t1 <- getCurrentTime print final_clusters printf "Total time: %.2f\n" (realToFrac (diffUTCTime t1 t0) :: Double) -- ----------------------------------------------------------------------------- -- K-Means: repeatedly step until convergence (sequential) -- <<kmeans_seq kmeans_seq :: Int -> [Point] -> [Cluster] -> IO [Cluster] kmeans_seq nclusters points clusters = let loop :: Int -> [Cluster] -> IO [Cluster] loop n clusters | n > tooMany = do -- <1> putStrLn "giving up." return clusters loop n clusters = do printf "iteration %d\n" n putStr (unlines (map show clusters)) let clusters' = step nclusters clusters points -- <2> if clusters' == clusters -- <3> then return clusters else loop (n+1) clusters' in loop 0 clusters tooMany = 80 -- >> -- ----------------------------------------------------------------------------- -- K-Means: repeatedly step until convergence (Strategies) -- <<kmeans_strat kmeans_strat :: Int -> Int -> [Point] -> [Cluster] -> IO [Cluster] kmeans_strat numChunks nclusters points clusters = let chunks = split numChunks points -- <1> loop :: Int -> [Cluster] -> IO [Cluster] loop n clusters | n > tooMany = do printf "giving up." return clusters loop n clusters = do printf "iteration %d\n" n putStr (unlines (map show clusters)) let clusters' = parSteps_strat nclusters clusters chunks -- <2> if clusters' == clusters then return clusters else loop (n+1) clusters' in loop 0 clusters -- >> -- <<split split :: Int -> [a] -> [[a]] split numChunks xs = chunk (length xs `quot` numChunks) xs chunk :: Int -> [a] -> [[a]] chunk n [] = [] chunk n xs = as : chunk n bs where (as,bs) = splitAt n xs -- >> -- ----------------------------------------------------------------------------- -- K-Means: repeatedly step until convergence (Par monad) kmeans_par :: Int -> Int -> [Point] -> [Cluster] -> IO [Cluster] kmeans_par mappers nclusters points clusters = let chunks = split mappers points loop :: Int -> [Cluster] -> IO [Cluster] loop n clusters | n > tooMany = do printf "giving up."; return clusters loop n clusters = do printf "iteration %d\n" n putStr (unlines (map show clusters)) let clusters' = steps_par nclusters clusters chunks if clusters' == clusters then return clusters else loop (n+1) clusters' in loop 0 clusters -- ----------------------------------------------------------------------------- -- kmeans_div_par: Use divide-and-conquer, and the Par monad for parallellism. kmeans_div_par :: Int -> Int -> [Point] -> [Cluster] -> Int -> IO [Cluster] kmeans_div_par threshold nclusters points clusters npoints = let tree = mkPointTree threshold points npoints loop :: Int -> [Cluster] -> IO [Cluster] loop n clusters | n > tooMany = do printf "giving up."; return clusters loop n clusters = do hPrintf stderr "iteration %d\n" n hPutStr stderr (unlines (map show clusters)) let divconq :: Tree [Point] -> Par (Vector PointSum) divconq (Leaf points) = return $ assign nclusters clusters points divconq (Node left right) = do i1 <- spawn $ divconq left i2 <- spawn $ divconq right c1 <- get i1 c2 <- get i2 return $! combine c1 c2 clusters' = makeNewClusters $ runPar $ divconq tree if clusters' == clusters then return clusters else loop (n+1) clusters' in loop 0 clusters data Tree a = Leaf a | Node (Tree a) (Tree a) mkPointTree :: Int -> [Point] -> Int -> Tree [Point] mkPointTree threshold points npoints = go 0 points npoints where go depth points npoints | depth >= threshold = Leaf points | otherwise = Node (go (depth+1) xs half) (go (depth+1) ys half) where half = npoints `quot` 2 (xs,ys) = splitAt half points -- ----------------------------------------------------------------------------- -- kmeans_div_eval: Use divide-and-conquer, and the Eval monad for parallellism. kmeans_div_eval :: Int -> Int -> [Point] -> [Cluster] -> Int -> IO [Cluster] kmeans_div_eval threshold nclusters points clusters npoints = let tree = mkPointTree threshold points npoints loop :: Int -> [Cluster] -> IO [Cluster] loop n clusters | n > tooMany = do printf "giving up."; return clusters loop n clusters = do hPrintf stderr "iteration %d\n" n hPutStr stderr (unlines (map show clusters)) let divconq :: Tree [Point] -> Vector PointSum divconq (Leaf points) = assign nclusters clusters points divconq (Node left right) = runEval $ do c1 <- rpar $ divconq left c2 <- rpar $ divconq right rdeepseq c1 rdeepseq c2 return $! combine c1 c2 clusters' = makeNewClusters $ divconq tree if clusters' == clusters then return clusters else loop (n+1) clusters' in loop 0 clusters -- ----------------------------------------------------------------------------- -- Perform one step of the K-Means algorithm -- <<step step :: Int -> [Cluster] -> [Point] -> [Cluster] step nclusters clusters points = makeNewClusters (assign nclusters clusters points) -- >> -- <<assign assign :: Int -> [Cluster] -> [Point] -> Vector PointSum assign nclusters clusters points = Vector.create $ do vec <- MVector.replicate nclusters (PointSum 0 0 0) let addpoint p = do let c = nearest p; cid = clId c ps <- MVector.read vec cid MVector.write vec cid $! addToPointSum ps p mapM_ addpoint points return vec where nearest p = fst $ minimumBy (compare `on` snd) [ (c, sqDistance (clCent c) p) | c <- clusters ] -- >> data PointSum = PointSum {-# UNPACK #-} !Int {-# UNPACK #-} !Double {-# UNPACK #-} !Double instance NFData PointSum -- <<addToPointSum addToPointSum :: PointSum -> Point -> PointSum addToPointSum (PointSum count xs ys) (Point x y) = PointSum (count+1) (xs + x) (ys + y) -- >> -- <<pointSumToCluster pointSumToCluster :: Int -> PointSum -> Cluster pointSumToCluster i (PointSum count xs ys) = Cluster { clId = i , clCent = Point (xs / fromIntegral count) (ys / fromIntegral count) } -- >> -- <<addPointSums addPointSums :: PointSum -> PointSum -> PointSum addPointSums (PointSum c1 x1 y1) (PointSum c2 x2 y2) = PointSum (c1+c2) (x1+x2) (y1+y2) -- >> -- <<combine combine :: Vector PointSum -> Vector PointSum -> Vector PointSum combine = Vector.zipWith addPointSums -- >> -- <<parSteps_strat parSteps_strat :: Int -> [Cluster] -> [[Point]] -> [Cluster] parSteps_strat nclusters clusters pointss = makeNewClusters $ foldr1 combine $ (map (assign nclusters clusters) pointss `using` parList rseq) -- >> steps_par :: Int -> [Cluster] -> [[Point]] -> [Cluster] steps_par nclusters clusters pointss = makeNewClusters $ foldl1' combine $ (runPar $ Par.parMap (assign nclusters clusters) pointss) -- <<makeNewClusters makeNewClusters :: Vector PointSum -> [Cluster] makeNewClusters vec = [ pointSumToCluster i ps | (i,ps@(PointSum count _ _)) <- zip [0..] (Vector.toList vec) , count > 0 ] -- >> -- v. important: filter out any clusters that have -- no points. This can happen when a cluster is not -- close to any points. If we leave these in, then -- the NaNs mess up all the future calculations.
mono0926/ParallelConcurrentHaskell
kmeans/kmeans.hs
bsd-3-clause
10,087
0
19
2,657
2,822
1,442
1,380
196
6
module Main where import Prelude hiding (lookup) import Data.HashMap.Strict (fromList, lookup) import System.Environment type WordString = String type Score = Int letterScores = fromList $ zip ['a'..'z'] [1..] wordScore :: WordString -> Maybe Score wordScore w = sum <$> mapM (\x -> lookup x letterScores) w score100 :: [(WordString, Maybe Score)] -> [WordString] score100 l = map fst $ filter (\(_, x) -> x == Just 100) l main :: IO () main = do (filePath:_) <- getArgs f <- readFile filePath let wordList = words f let scoreList = wordScore <$> wordList let wordScoreList = zip wordList scoreList let words100Score = score100 wordScoreList putStrLn $ "Number of words with a score of 100: " ++ show (length words100Score) putStrLn "Words with a score of 100:" print words100Score
Michaelt293/Demotivation
src/Main.hs
bsd-3-clause
824
0
10
170
295
151
144
22
1
module Reactive.Banana.GTK where import BasePrelude import Control.Monad.Trans (liftIO) import Linear import Linear.Affine import qualified Graphics.UI.Gtk as GTK import qualified Reactive.Banana as RB import qualified Reactive.Banana.Frameworks as RB registerDestroy :: (RB.Frameworks t,GTK.WidgetClass w) => w -> RB.Moment t (RB.Event t ()) registerDestroy widget = RB.fromAddHandler (RB.AddHandler (\h -> fmap GTK.signalDisconnect (GTK.on widget GTK.objectDestroy (liftIO (h ()))))) registerMotionNotify :: (RB.Frameworks t,GTK.WidgetClass w) => w -> RB.Moment t (RB.Event t (Point V2 Double)) registerMotionNotify widget = RB.fromAddHandler (withEvent (GTK.on widget GTK.motionNotifyEvent) (\h -> do (x,y) <- GTK.eventCoordinates False <$ liftIO (h (P (V2 x y))))) data MouseClick = MouseClick {mcButton :: GTK.MouseButton ,mcCoordinates :: Point V2 Double} deriving (Eq, Show) registerMouseClicked :: (RB.Frameworks t,GTK.WidgetClass w) => w -> RB.Moment t (RB.Event t MouseClick) registerMouseClicked widget = RB.fromAddHandler (RB.AddHandler (\h -> fmap GTK.signalDisconnect (GTK.on widget GTK.buttonPressEvent (do button <- GTK.eventButton (x,y) <- GTK.eventCoordinates False <$ liftIO (h (MouseClick button (P (V2 x y)))))))) registerMouseReleased :: (RB.Frameworks t,GTK.WidgetClass w) => w -> RB.Moment t (RB.Event t MouseClick) registerMouseReleased widget = RB.fromAddHandler (RB.AddHandler (\h -> fmap GTK.signalDisconnect (GTK.on widget GTK.buttonReleaseEvent (do button <- GTK.eventButton (x,y) <- GTK.eventCoordinates False <$ liftIO (h (MouseClick button (P (V2 x y)))))))) withEvent :: (GTK.GObjectClass obj,RB.MonadIO m) => (t -> IO (GTK.ConnectId obj)) -> ((a -> m ()) -> t) -> RB.AddHandler a withEvent f m = RB.AddHandler (\h -> fmap GTK.signalDisconnect (f (m (liftIO . h)))) registerToolButtonClicked b = RB.fromAddHandler (RB.AddHandler (\h -> fmap GTK.signalDisconnect (GTK.onToolButtonClicked b (h ())))) registerKeyPressed w = RB.fromAddHandler (RB.AddHandler (\h -> fmap GTK.signalDisconnect (GTK.on w GTK.keyReleaseEvent (do kv <- GTK.eventKeyVal True <$ (liftIO (h kv)))))) -- TODO This should return False if we're not interested in the event
ocharles/hadoom
hadoom-editor/Reactive/Banana/GTK.hs
bsd-3-clause
3,085
0
25
1,182
923
478
445
81
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} -- -- Copyright (c) 2009-2011, ERICSSON AB -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the ERICSSON AB nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- | Implementation of Logic constructs -- module Feldspar.Core.Constructs.Logic ( Logic (..) ) where import Language.Syntactic import Language.Syntactic.Constructs.Binding import Feldspar.Core.Types import Feldspar.Core.Interpretation import Feldspar.Core.Constructs.Eq import Feldspar.Core.Constructs.Ord -- | Logic constructs data Logic a where And :: Logic (Bool :-> Bool :-> Full Bool) Or :: Logic (Bool :-> Bool :-> Full Bool) Not :: Logic (Bool :-> Full Bool) instance Semantic Logic where semantics And = Sem "(&&)" (&&) semantics Or = Sem "(||)" (||) semantics Not = Sem "not" not instance Equality Logic where equal = equalDefault; exprHash = exprHashDefault instance Render Logic where renderArgs = renderArgsDefault instance ToTree Logic instance Eval Logic where evaluate = evaluateDefault instance EvalBind Logic where evalBindSym = evalBindSymDefault instance Sharable Logic instance AlphaEq dom dom dom env => AlphaEq Logic Logic dom env where alphaEqSym = alphaEqSymDefault instance SizeProp (Logic :|| Type) where sizeProp a@(C' _) args = sizePropDefault a args instance ( (Logic :|| Type) :<: dom , (EQ :|| Type) :<: dom , (ORD :|| Type) :<: dom , OptimizeSuper dom ) => Optimize (Logic :|| Type) dom where constructFeatOpt _ (C' And) (a :* b :* Nil) | Just True <- viewLiteral a = return b | Just False <- viewLiteral a = return a | Just True <- viewLiteral b = return a | Just False <- viewLiteral b = return b | a `alphaEq` b = return a constructFeatOpt _ (C' Or) (a :* b :* Nil) | Just True <- viewLiteral a = return a | Just False <- viewLiteral a = return b | Just True <- viewLiteral b = return b | Just False <- viewLiteral b = return a | a `alphaEq` b = return a constructFeatOpt _ (C' Not) ((op :$ a) :* Nil) | Just (C' Not) <- prjF op = return a constructFeatOpt opts (C' Not) ((op :$ a :$ b) :* Nil) | Just (C' Equal) <- prjF op = constructFeat opts (c' NotEqual) (a :* b :* Nil) | Just (C' NotEqual) <- prjF op = constructFeat opts (c' Equal) (a :* b :* Nil) | Just (C' LTH) <- prjF op = constructFeat opts (c' GTE) (a :* b :* Nil) | Just (C' GTH) <- prjF op = constructFeat opts (c' LTE) (a :* b :* Nil) | Just (C' LTE) <- prjF op = constructFeat opts (c' GTH) (a :* b :* Nil) | Just (C' GTE) <- prjF op = constructFeat opts (c' LTH) (a :* b :* Nil) constructFeatOpt opts a args = constructFeatUnOpt opts a args constructFeatUnOpt opts x@(C' _) = constructFeatUnOptDefault opts x
rCEx/feldspar-lang-small
src/Feldspar/Core/Constructs/Logic.hs
bsd-3-clause
4,580
0
12
1,122
1,114
566
548
-1
-1
module TinyBlog( module TinyBlog.Config, TinyBlog.app ) where import TinyBlog.Config import TinyBlog.Entry import Data.Maybe import Network.Gravatar import Network.Loli import Network.Loli.Template.TextTemplate import Network.Loli.Utils --import Hack.Contrib.Request import Hack.Contrib.Response import Hack --import Control.Monad.Reader -- | *application main app :: Config -> Hack.Env -> IO Hack.Response app cfg = loli $ do layout "layout.html" -- | JSON response get "/json/entries" $ do -- get count from querystring --env <- ask --let count = getCount env -- get recent entries files <- io $ getEntryFiles entries <- io $ readEntries files no_layout $ do update $ set_content_type "application/json; charset=utf-8" update $ set_body $ toJSON entries -- | RSS response get "/rss" $ do -- get recent entries files <- io $ getEntryFiles entries <- io $ readEntries files no_layout $ do update $ set_content_type "application/xml; charset=utf-8" update $ set_body $ toRSS entries cfg -- | HTML response get "/:entry" $ do ps <- captures let entryCode = fromJust $ lookup "entry" ps maybeEntry <- io $ readEntry $ "data/" ++ entryCode ++ ".txt" update $ set_content_type "text/html" case maybeEntry of Just entry -> do let gravatarImage = getGravatarImage (cUseGravatar cfg) (cEmail cfg) context ((entryToKV entry) ++ [ ("metaTitle", eTitle entry ++ " - " ++ (cBlogName cfg)) , ("gravatar", gravatarImage) ]) $ do output $ text_template "entry.html" Nothing -> do update $ set_status 404 no_layout $ output $ text_template "404.html" get "/" $ do -- get a latest entry files <- io $ getEntryFiles entries <- io $ readEntries files let entry = head entries let gravatarImage = getGravatarImage (cUseGravatar cfg) (cEmail cfg) update $ set_content_type "text/html" context ((entryToKV entry) ++ [ ("metaTitle", cBlogName cfg) , ("gravatar", gravatarImage) ]) $ do output $ text_template "index.html" public (Just ".") ["/static"] -- | get a gravatar image getGravatarImage :: Bool -> String -> String getGravatarImage True email = gravatar email getGravatarImage False _ = "" -- | get count from querystring {- getCount :: Hack.Env -> Int getCount env = let ps = params env in case lookup "count" ps of Just count -> read count _ -> 20 -}
nsyee00/tinyblog
src/TinyBlog.hs
bsd-3-clause
2,803
0
24
907
649
318
331
58
2
{-# LANGUAGE CPP, BangPatterns, DeriveDataTypeable, FlexibleContexts, FlexibleInstances, GeneralizedNewtypeDeriving, OverloadedStrings, DefaultSignatures, UndecidableInstances, ViewPatterns, NoImplicitPrelude #-} #define NEEDS_INCOHERENT #include "overlapping-compat.h" {-# OPTIONS_GHC -fno-warn-orphans #-} -- TODO: Drop this when we remove support for Data.Attoparsec.Number {-# OPTIONS_GHC -fno-warn-deprecations #-} module Json.Internal.Instances ( -- * Helpers for writing instances object, objectE, foldableE, -- * Lower-level helpers emptyObjectE, emptyArrayE, ) where import BasePrelude -- TODO: group these imports import Json.Internal.Types import Json.Internal.Classes import Json.Internal.ValueParser import Json.Internal.Utils import Data.Attoparsec.Number (Number(..)) import Data.Functor.Identity (Identity(..)) import Data.Hashable (Hashable(..)) import Data.Scientific (Scientific) import Data.Text (Text, pack, unpack) import Data.Time (Day, LocalTime, NominalDiffTime, TimeOfDay, UTCTime, ZonedTime) import Data.Time.Format (FormatTime, formatTime, parseTime) import Data.Vector (Vector) import qualified Json.Internal.Encode.ByteString as E import qualified Json.Internal.JsonParser.Time as Time import qualified Data.ByteString.Builder as B import qualified Data.ByteString.Lazy as L import qualified Data.HashMap.Strict as H import qualified Data.HashSet as HashSet import qualified Data.IntMap as IntMap import qualified Data.IntSet as IntSet import qualified Data.Map as M import qualified Data.Scientific as Scientific import qualified Data.Sequence as Seq import qualified Data.Set as Set import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy as LT import qualified Data.Tree as Tree import qualified Data.Vector as V import qualified Data.Vector.Generic as VG import qualified Data.Vector.Mutable as VM (unsafeNew, unsafeWrite) import qualified Data.Vector.Primitive as VP import qualified Data.Vector.Storable as VS import qualified Data.Vector.Unboxed as VU #if MIN_VERSION_base(4,8,0) import Numeric.Natural #endif #if MIN_VERSION_time(1,5,0) import Data.Time.Format (defaultTimeLocale) #else import System.Locale (defaultTimeLocale) #endif -- | Create 'Json' from a list of name\/value 'Pair's. If duplicate -- keys arise, earlier keys and their associated values win. object :: [Pair] -> Json object = Object . H.fromList {-# INLINE object #-} -- | Encode a series of key/value pairs, separated by commas. objectE :: Series -> Encoding objectE (Value b) = Encoding (E.braces (fromEncoding b)) objectE Empty = emptyObjectE {-# INLINE objectE #-} emptyObjectE :: Encoding emptyObjectE = Encoding E.emptyObject arrayE :: Series -> Encoding arrayE (Value b) = Encoding (E.brackets (fromEncoding b)) arrayE Empty = emptyArrayE {-# INLINE arrayE #-} emptyArrayE :: Encoding emptyArrayE = Encoding E.emptyArray -- | Encode a 'Foldable' as an array. foldableE :: (Foldable t, ToJson a) => t a -> Encoding foldableE xs = case foldMap (Value . toEncoding) xs of Empty -> emptyArrayE Value b -> Encoding (E.brackets (fromEncoding b)) {-# INLINE foldableE #-} comma :: B.Builder comma = B.char7 ',' {-# INLINE comma #-} builder :: ToJson a => a -> B.Builder builder = fromEncoding . toEncoding {-# INLINE builder #-} list :: ToJson a => [a] -> Encoding list [] = emptyArrayE list (x:xs) = Encoding $ B.char7 '[' <> builder x <> commas xs <> B.char7 ']' where commas = foldr (\v vs -> comma <> builder v <> vs) mempty {-# INLINE list #-} parseIndexedJson :: FromJson a => Int -> Json -> Parser Json a parseIndexedJson idx value = apply parseJson value <?> Index idx parseKeyedJson :: FromJson a => Text -> Json -> Parser Json a parseKeyedJson key value = apply parseJson value <?> Key key instance (ToJson a) => ToJson (Identity a) where toJson (Identity a) = toJson a {-# INLINE toJson #-} toEncoding (Identity a) = toEncoding a {-# INLINE toEncoding #-} instance (FromJson a) => FromJson (Identity a) where parseJson = Identity <$> parseJson {-# INLINE parseJson #-} instance (ToJson a) => ToJson (Maybe a) where toJson (Just a) = toJson a toJson Nothing = Null {-# INLINE toJson #-} toEncoding (Just a) = toEncoding a toEncoding Nothing = Encoding E.null_ {-# INLINE toEncoding #-} instance (FromJson a) => FromJson (Maybe a) where parseJson = Nothing <$ getNull "" <|> Just <$> parseJson {-# INLINE parseJson #-} instance (ToJson a, ToJson b) => ToJson (Either a b) where toJson (Left a) = object ["Left" .= a] toJson (Right b) = object ["Right" .= b] {-# INLINE toJson #-} toEncoding (Left a) = Encoding $ B.shortByteString "{\"Left\":" <> builder a <> B.char7 '}' toEncoding (Right a) = Encoding $ B.shortByteString "{\"Right\":" <> builder a <> B.char7 '}' {-# INLINE toEncoding #-} instance (FromJson a, FromJson b) => FromJson (Either a b) where parseJson = withSingleton "Either" $ \key -> case key of "Left" -> Left <$> parseJson "Right" -> Right <$> parseJson _ -> fail $ "Expected an object with a single field called either \"Left\" or \"Right\", found " ++ T.unpack key {-# INLINE parseJson #-} instance ToJson Bool where toJson = Bool {-# INLINE toJson #-} toEncoding = Encoding . E.bool {-# INLINE toEncoding #-} instance FromJson Bool where parseJson = getBool "" {-# INLINE parseJson #-} instance ToJson Ordering where toJson = toJson . orderingToText toEncoding = toEncoding . orderingToText orderingToText :: Ordering -> T.Text orderingToText o = case o of LT -> "LT" EQ -> "EQ" GT -> "GT" instance FromJson Ordering where parseJson = do s <- getString "Ordering" case s of "LT" -> return LT "EQ" -> return EQ "GT" -> return GT _ -> fail "Parsing Ordering value failed: expected \"LT\", \"EQ\", or \"GT\"" instance ToJson () where toJson _ = Array mempty {-# INLINE toJson #-} toEncoding _ = emptyArrayE {-# INLINE toEncoding #-} instance FromJson () where parseJson = do v <- getArray "()" if V.null v then return () else fail "Expected an empty array" {-# INLINE parseJson #-} instance INCOHERENT_ ToJson [Char] where toJson = String . T.pack {-# INLINE toJson #-} toEncoding = Encoding . E.string {-# INLINE toEncoding #-} instance INCOHERENT_ FromJson [Char] where parseJson = T.unpack <$> getString "String" {-# INLINE parseJson #-} instance ToJson Char where toJson = String . T.singleton {-# INLINE toJson #-} toEncoding = Encoding . E.string . (:[]) {-# INLINE toEncoding #-} instance FromJson Char where parseJson = do t <- getString "Char" case T.compareLength t 1 of EQ -> return (T.head t) _ -> fail "Expected a string of length 1" {-# INLINE parseJson #-} instance ToJson Scientific where toJson = Number {-# INLINE toJson #-} toEncoding = Encoding . E.number {-# INLINE toEncoding #-} instance FromJson Scientific where parseJson = getNumber "Scientific" {-# INLINE parseJson #-} instance ToJson Double where toJson = realFloatToJson {-# INLINE toJson #-} toEncoding = realFloatToEncoding {-# INLINE toEncoding #-} instance FromJson Double where parseJson = parseRealFloat "Double" {-# INLINE parseJson #-} instance ToJson Number where toJson (D d) = toJson d toJson (I i) = toJson i {-# INLINE toJson #-} toEncoding (D d) = toEncoding d toEncoding (I i) = toEncoding i {-# INLINE toEncoding #-} -- TODO: <|> should combine error messages; what is it doing now? instance FromJson Number where parseJson = scientificToNumber <$> getNumber "Number" <|> D (0/0) <$ getNull "Number" {-# INLINE parseJson #-} instance ToJson Float where toJson = realFloatToJson {-# INLINE toJson #-} toEncoding = realFloatToEncoding {-# INLINE toEncoding #-} instance FromJson Float where parseJson = parseRealFloat "Float" {-# INLINE parseJson #-} instance ToJson (Ratio Integer) where toJson r = object [ "numerator" .= numerator r , "denominator" .= denominator r ] {-# INLINE toJson #-} toEncoding r = Encoding $ B.shortByteString "{\"numerator\":" <> builder (numerator r) <> B.shortByteString ",\"denominator\":" <> builder (denominator r) <> B.char7 '}' {-# INLINE toEncoding #-} instance FromJson (Ratio Integer) where parseJson = withObject "Rational" $ (%) <$> field "numerator" <*> field "denominator" {-# INLINE parseJson #-} instance HasResolution a => ToJson (Fixed a) where toJson = Number . realToFrac {-# INLINE toJson #-} toEncoding = Encoding . E.number . realToFrac {-# INLINE toEncoding #-} -- | /WARNING:/ Only parse fixed-precision numbers from trusted input -- since an attacker could easily fill up the memory of the target -- system by specifying a scientific number with a big exponent like -- @1e1000000000@. instance HasResolution a => FromJson (Fixed a) where parseJson = realToFrac <$> getNumber "Fixed" {-# INLINE parseJson #-} instance ToJson Int where toJson = Number . fromIntegral {-# INLINE toJson #-} toEncoding = Encoding . B.intDec {-# INLINE toEncoding #-} instance FromJson Int where parseJson = parseIntegral "Int" {-# INLINE parseJson #-} instance ToJson Integer where toJson = Number . fromInteger {-# INLINE toJson #-} toEncoding = Encoding . B.integerDec {-# INLINE toEncoding #-} -- | /WARNING:/ Only parse Integers from trusted input since an -- attacker could easily fill up the memory of the target system by -- specifying a scientific number with a big exponent like -- @1e1000000000@. instance FromJson Integer where parseJson = parseIntegral "Integer" {-# INLINE parseJson #-} #if MIN_VERSION_base(4,8,0) instance ToJson Natural where toJson = toJson . toInteger {-# INLINE toJson #-} toEncoding = toEncoding . toInteger {-# INLINE toEncoding #-} instance FromJson Natural where parseJson = do s <- getNumber "Natural" if Scientific.coefficient s < 0 then fail $ "Expected a Natural number but got the negative number: " <> show s else pure $ truncate s #endif instance ToJson Int8 where toJson = Number . fromIntegral {-# INLINE toJson #-} toEncoding = Encoding . B.int8Dec {-# INLINE toEncoding #-} instance FromJson Int8 where parseJson = parseIntegral "Int8" {-# INLINE parseJson #-} instance ToJson Int16 where toJson = Number . fromIntegral {-# INLINE toJson #-} toEncoding = Encoding . B.int16Dec {-# INLINE toEncoding #-} instance FromJson Int16 where parseJson = parseIntegral "Int16" {-# INLINE parseJson #-} instance ToJson Int32 where toJson = Number . fromIntegral {-# INLINE toJson #-} toEncoding = Encoding . B.int32Dec {-# INLINE toEncoding #-} instance FromJson Int32 where parseJson = parseIntegral "Int32" {-# INLINE parseJson #-} instance ToJson Int64 where toJson = Number . fromIntegral {-# INLINE toJson #-} toEncoding = Encoding . B.int64Dec {-# INLINE toEncoding #-} instance FromJson Int64 where parseJson = parseIntegral "Int64" {-# INLINE parseJson #-} instance ToJson Word where toJson = Number . fromIntegral {-# INLINE toJson #-} toEncoding = Encoding . B.wordDec {-# INLINE toEncoding #-} instance FromJson Word where parseJson = parseIntegral "Word" {-# INLINE parseJson #-} instance ToJson Word8 where toJson = Number . fromIntegral {-# INLINE toJson #-} toEncoding = Encoding . B.word8Dec {-# INLINE toEncoding #-} instance FromJson Word8 where parseJson = parseIntegral "Word8" {-# INLINE parseJson #-} instance ToJson Word16 where toJson = Number . fromIntegral {-# INLINE toJson #-} toEncoding = Encoding . B.word16Dec {-# INLINE toEncoding #-} instance FromJson Word16 where parseJson = parseIntegral "Word16" {-# INLINE parseJson #-} instance ToJson Word32 where toJson = Number . fromIntegral {-# INLINE toJson #-} toEncoding = Encoding . B.word32Dec {-# INLINE toEncoding #-} instance FromJson Word32 where parseJson = parseIntegral "Word32" {-# INLINE parseJson #-} instance ToJson Word64 where toJson = Number . fromIntegral {-# INLINE toJson #-} toEncoding = Encoding . B.word64Dec {-# INLINE toEncoding #-} instance FromJson Word64 where parseJson = parseIntegral "Word64" {-# INLINE parseJson #-} instance ToJson Text where toJson = String {-# INLINE toJson #-} toEncoding = Encoding . E.text {-# INLINE toEncoding #-} instance FromJson Text where -- TODO: can just have "" here (and think about parseIntegral too) parseJson = getString "Text" {-# INLINE parseJson #-} instance ToJson LT.Text where toJson = String . LT.toStrict {-# INLINE toJson #-} toEncoding t = Encoding $ B.char7 '"' <> LT.foldrChunks (\x xs -> E.unquoted x <> xs) (B.char7 '"') t {-# INLINE toEncoding #-} instance FromJson LT.Text where -- TODO: and what about "" here? parseJson = LT.fromStrict <$> getString "Lazy Text" {-# INLINE parseJson #-} instance OVERLAPPABLE_ (ToJson a) => ToJson [a] where toJson = Array . V.fromList . map toJson {-# INLINE toJson #-} toEncoding xs = list xs {-# INLINE toEncoding #-} instance OVERLAPPABLE_ (FromJson a) => FromJson [a] where -- TODO: can I use zipWithM here? parseJson = sequence . zipWith parseIndexedJson [0..] . V.toList =<< getArray "[a]" {-# INLINE parseJson #-} instance (ToJson a) => ToJson (Seq.Seq a) where toJson = toJson . toList toEncoding = toEncoding . toList instance (FromJson a) => FromJson (Seq.Seq a) where -- TODO: use “label” here once it's available parseJson = fmap Seq.fromList . sequence . zipWith parseIndexedJson [0..] . V.toList =<< getArray "Seq a" {-# INLINE parseJson #-} instance (ToJson a) => ToJson (Vector a) where toJson = Array . V.map toJson {-# INLINE toJson #-} toEncoding = encodeVector {-# INLINE toEncoding #-} encodeVector :: (ToJson a, VG.Vector v a) => v a -> Encoding encodeVector xs | VG.null xs = emptyArrayE | otherwise = Encoding $ B.char7 '[' <> builder (VG.unsafeHead xs) <> VG.foldr go (B.char7 ']') (VG.unsafeTail xs) where go v b = comma <> builder v <> b {-# INLINE encodeVector #-} instance (FromJson a) => FromJson (Vector a) where parseJson = V.mapM (uncurry parseIndexedJson) . V.indexed =<< getArray "Vector a" {-# INLINE parseJson #-} vectorToJson :: (VG.Vector v a, ToJson a) => v a -> Json vectorToJson = Array . V.map toJson . V.convert {-# INLINE vectorToJson #-} vectorParseJson :: (FromJson a, VG.Vector w a) => String -> Parser Json (w a) vectorParseJson s = do v <- getArray s fmap V.convert . V.mapM (uncurry parseIndexedJson) . V.indexed $ v {-# INLINE vectorParseJson #-} instance (Storable a, ToJson a) => ToJson (VS.Vector a) where toJson = vectorToJson {-# INLINE toJson #-} toEncoding = encodeVector {-# INLINE toEncoding #-} instance (Storable a, FromJson a) => FromJson (VS.Vector a) where parseJson = vectorParseJson "Data.Vector.Storable.Vector a" instance (VP.Prim a, ToJson a) => ToJson (VP.Vector a) where toJson = vectorToJson {-# INLINE toJson #-} toEncoding = encodeVector {-# INLINE toEncoding #-} instance (VP.Prim a, FromJson a) => FromJson (VP.Vector a) where parseJson = vectorParseJson "Data.Vector.Primitive.Vector a" {-# INLINE parseJson #-} instance (VG.Vector VU.Vector a, ToJson a) => ToJson (VU.Vector a) where toJson = vectorToJson {-# INLINE toJson #-} toEncoding = encodeVector {-# INLINE toEncoding #-} instance (VG.Vector VU.Vector a, FromJson a) => FromJson (VU.Vector a) where parseJson = vectorParseJson "Data.Vector.Unboxed.Vector a" {-# INLINE parseJson #-} instance (ToJson a) => ToJson (Set.Set a) where toJson = toJson . Set.toList {-# INLINE toJson #-} toEncoding = encodeSet Set.minView Set.foldr {-# INLINE toEncoding #-} instance (Ord a, FromJson a) => FromJson (Set.Set a) where parseJson = Set.fromList <$> parseJson {-# INLINE parseJson #-} instance (ToJson a) => ToJson (HashSet.HashSet a) where toJson = toJson . HashSet.toList {-# INLINE toJson #-} toEncoding = foldableE {-# INLINE toEncoding #-} instance (Eq a, Hashable a, FromJson a) => FromJson (HashSet.HashSet a) where parseJson = HashSet.fromList <$> parseJson {-# INLINE parseJson #-} instance ToJson IntSet.IntSet where toJson = toJson . IntSet.toList {-# INLINE toJson #-} toEncoding = encodeSet IntSet.minView IntSet.foldr {-# INLINE toEncoding #-} encodeSet :: (ToJson a) => (s -> Maybe (a, s)) -> ((a -> B.Builder -> B.Builder) -> B.Builder -> s -> B.Builder) -> s -> Encoding encodeSet minView foldr_ xs = case minView xs of Nothing -> emptyArrayE Just (m,ys) -> Encoding $ B.char7 '[' <> builder m <> foldr_ go (B.char7 ']') ys where go v b = comma <> builder v <> b {-# INLINE encodeSet #-} instance FromJson IntSet.IntSet where -- TODO: “expected a set” would actually be useful here (or not?) parseJson = IntSet.fromList <$> parseJson {-# INLINE parseJson #-} instance ToJson a => ToJson (IntMap.IntMap a) where toJson = toJson . IntMap.toList {-# INLINE toJson #-} toEncoding = toEncoding . IntMap.toList {-# INLINE toEncoding #-} instance FromJson a => FromJson (IntMap.IntMap a) where parseJson = IntMap.fromList <$> parseJson {-# INLINE parseJson #-} instance (ToJson v) => ToJson (M.Map Text v) where toJson = Object . M.foldrWithKey (\k -> H.insert k . toJson) H.empty {-# INLINE toJson #-} toEncoding = encodeMap M.minViewWithKey M.foldrWithKey {-# INLINE toEncoding #-} encodeMap :: (ToJson k, ToJson v) => (m -> Maybe ((k,v), m)) -> ((k -> v -> B.Builder -> B.Builder) -> B.Builder -> m -> B.Builder) -> m -> Encoding encodeMap minViewWithKey foldrWithKey xs = case minViewWithKey xs of Nothing -> emptyObjectE Just ((k,v),ys) -> Encoding $ B.char7 '{' <> encodeKV k v <> foldrWithKey go (B.char7 '}') ys where go k v b = comma <> encodeKV k v <> b {-# INLINE encodeMap #-} encodeWithKey :: (ToJson k, ToJson v) => ((k -> v -> Series -> Series) -> Series -> m -> Series) -> m -> Encoding encodeWithKey foldrWithKey = arrayE . foldrWithKey go mempty where go k v c = Value (Encoding $ encodeKV k v) <> c {-# INLINE encodeWithKey #-} encodeKV :: (ToJson k, ToJson v) => k -> v -> B.Builder encodeKV k v = builder k <> B.char7 ':' <> builder v {-# INLINE encodeKV #-} instance (FromJson v) => FromJson (M.Map Text v) where -- TODO: “Map Text a” is probably useless here parseJson = do x <- getObject "Map Text a" H.foldrWithKey M.insert M.empty <$> H.traverseWithKey parseKeyedJson x instance (ToJson v) => ToJson (M.Map LT.Text v) where toJson = Object . mapHashKeyVal LT.toStrict toJson {-# INLINE toJson #-} toEncoding = encodeMap M.minViewWithKey M.foldrWithKey {-# INLINE toEncoding #-} instance (FromJson v) => FromJson (M.Map LT.Text v) where parseJson = hashMapKey LT.fromStrict <$> parseJson {-# INLINE parseJson #-} instance (ToJson v) => ToJson (M.Map String v) where toJson = Object . mapHashKeyVal pack toJson {-# INLINE toJson #-} toEncoding = encodeMap M.minViewWithKey M.foldrWithKey {-# INLINE toEncoding #-} instance (FromJson v) => FromJson (M.Map String v) where parseJson = hashMapKey unpack <$> parseJson {-# INLINE parseJson #-} instance (ToJson v) => ToJson (H.HashMap Text v) where toJson = Object . H.map toJson {-# INLINE toJson #-} toEncoding = encodeWithKey H.foldrWithKey {-# INLINE toEncoding #-} instance (FromJson v) => FromJson (H.HashMap Text v) where -- TODO: another useless thing parseJson = do x <- getObject "HashMap Text a" H.traverseWithKey parseKeyedJson x {-# INLINE parseJson #-} instance (ToJson v) => ToJson (H.HashMap LT.Text v) where toJson = Object . mapKeyVal LT.toStrict toJson {-# INLINE toJson #-} toEncoding = encodeWithKey H.foldrWithKey {-# INLINE toEncoding #-} instance (FromJson v) => FromJson (H.HashMap LT.Text v) where parseJson = mapKey LT.fromStrict <$> parseJson {-# INLINE parseJson #-} instance (ToJson v) => ToJson (H.HashMap String v) where toJson = Object . mapKeyVal pack toJson {-# INLINE toJson #-} toEncoding = encodeWithKey H.foldrWithKey {-# INLINE toEncoding #-} instance (FromJson v) => FromJson (H.HashMap String v) where parseJson = mapKey unpack <$> parseJson {-# INLINE parseJson #-} instance (ToJson v) => ToJson (Tree.Tree v) where toJson (Tree.Node root branches) = toJson (root,branches) {-# INLINE toJson #-} toEncoding (Tree.Node root branches) = toEncoding (root,branches) {-# INLINE toEncoding #-} instance (FromJson v) => FromJson (Tree.Tree v) where parseJson = uncurry Tree.Node <$> parseJson {-# INLINE parseJson #-} instance ToJson Json where toJson a = a {-# INLINE toJson #-} toEncoding = Encoding . E.encodeToBuilder {-# INLINE toEncoding #-} instance FromJson Json where parseJson = getInput {-# INLINE parseJson #-} instance ToJson DotNetTime where toJson = toJson . dotNetTime toEncoding = toEncoding . dotNetTime dotNetTime :: DotNetTime -> String dotNetTime (DotNetTime t) = secs ++ formatMillis t ++ ")/" where secs = formatTime defaultTimeLocale "/Date(%s" t instance FromJson DotNetTime where parseJson = do t <- getString "DotNetTime" let (s,m) = T.splitAt (T.length t - 5) t t' = T.concat [s,".",m] case parseTime defaultTimeLocale "/Date(%s%Q)/" (unpack t') of Just d -> pure (DotNetTime d) _ -> fail "could not parse .NET time" {-# INLINE parseJson #-} instance ToJson Day where toJson = stringEncoding toEncoding z = Encoding (E.quotes $ E.day z) instance FromJson Day where parseJson = Time.run Time.day =<< getString "Day" instance ToJson TimeOfDay where toJson = stringEncoding toEncoding z = Encoding (E.quotes $ E.timeOfDay z) instance FromJson TimeOfDay where parseJson = Time.run Time.timeOfDay =<< getString "TimeOfDay" instance ToJson LocalTime where toJson = stringEncoding toEncoding z = Encoding (E.quotes $ E.localTime z) instance FromJson LocalTime where parseJson = Time.run Time.localTime =<< getString "LocalTime" instance ToJson ZonedTime where toJson = stringEncoding toEncoding z = Encoding (E.quotes $ E.zonedTime z) formatMillis :: (FormatTime t) => t -> String formatMillis = take 3 . formatTime defaultTimeLocale "%q" instance FromJson ZonedTime where parseJson = Time.run Time.zonedTime =<< getString "ZonedTime" instance ToJson UTCTime where toJson = stringEncoding toEncoding t = Encoding (E.quotes $ E.utcTime t) -- | Encode something to a JSON string. Can only be used on things that -- get encoded to Unicode-less JSON! -- -- TODO: rename to “unsafe” or even get rid of stringEncoding :: ToJson a => a -> Json stringEncoding = String . T.dropAround (== '"') . T.decodeLatin1 . L.toStrict . encodingToByteString . toEncoding {-# INLINE stringEncoding #-} instance FromJson UTCTime where parseJson = Time.run Time.utcTime =<< getString "UTCTime" instance ToJson NominalDiffTime where toJson = Number . realToFrac {-# INLINE toJson #-} toEncoding = Encoding . E.number . realToFrac {-# INLINE toEncoding #-} -- | /WARNING:/ Only parse lengths of time from trusted input -- since an attacker could easily fill up the memory of the target -- system by specifying a scientific number with a big exponent like -- @1e1000000000@. instance FromJson NominalDiffTime where -- TODO: make it clear in the docs how to parse numbers safely parseJson = realToFrac <$> getNumber "NominalDiffTime" {-# INLINE parseJson #-} instance (ToJson a, ToJson b) => ToJson (a,b) where toJson (a,b) = Array $ V.create $ do mv <- VM.unsafeNew 2 VM.unsafeWrite mv 0 (toJson a) VM.unsafeWrite mv 1 (toJson b) return mv {-# INLINE toJson #-} toEncoding (a,b) = Encoding . E.brackets $ builder a <> comma <> builder b {-# INLINE toEncoding #-} instance (FromJson a, FromJson b) => FromJson (a,b) where parseJson = withArray "pair" $ do checkLength 2 (,) <$> unsafeElementAt 0 <*> unsafeElementAt 1 {-# INLINE parseJson #-} instance (ToJson a, ToJson b, ToJson c) => ToJson (a,b,c) where toJson (a,b,c) = Array $ V.create $ do mv <- VM.unsafeNew 3 VM.unsafeWrite mv 0 (toJson a) VM.unsafeWrite mv 1 (toJson b) VM.unsafeWrite mv 2 (toJson c) return mv {-# INLINE toJson #-} toEncoding (a,b,c) = Encoding . E.brackets $ builder a <> comma <> builder b <> comma <> builder c {-# INLINE toEncoding #-} instance (FromJson a, FromJson b, FromJson c) => FromJson (a,b,c) where parseJson = withArray "triple" $ do checkLength 3 (,,) <$> unsafeElementAt 0 <*> unsafeElementAt 1 <*> unsafeElementAt 2 {-# INLINE parseJson #-} instance (ToJson a, ToJson b, ToJson c, ToJson d) => ToJson (a,b,c,d) where toJson (a,b,c,d) = Array $ V.create $ do mv <- VM.unsafeNew 4 VM.unsafeWrite mv 0 (toJson a) VM.unsafeWrite mv 1 (toJson b) VM.unsafeWrite mv 2 (toJson c) VM.unsafeWrite mv 3 (toJson d) return mv {-# INLINE toJson #-} toEncoding (a,b,c,d) = Encoding . E.brackets $ builder a <> comma <> builder b <> comma <> builder c <> comma <> builder d {-# INLINE toEncoding #-} instance (FromJson a, FromJson b, FromJson c, FromJson d) => FromJson (a,b,c,d) where parseJson = withArray "4-tuple" $ do checkLength 4 (,,,) <$> unsafeElementAt 0 <*> unsafeElementAt 1 <*> unsafeElementAt 2 <*> unsafeElementAt 3 {-# INLINE parseJson #-} instance (ToJson a, ToJson b, ToJson c, ToJson d, ToJson e) => ToJson (a,b,c,d,e) where toJson (a,b,c,d,e) = Array $ V.create $ do mv <- VM.unsafeNew 5 VM.unsafeWrite mv 0 (toJson a) VM.unsafeWrite mv 1 (toJson b) VM.unsafeWrite mv 2 (toJson c) VM.unsafeWrite mv 3 (toJson d) VM.unsafeWrite mv 4 (toJson e) return mv {-# INLINE toJson #-} toEncoding (a,b,c,d,e) = Encoding . E.brackets $ builder a <> comma <> builder b <> comma <> builder c <> comma <> builder d <> comma <> builder e {-# INLINE toEncoding #-} instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e) => FromJson (a,b,c,d,e) where parseJson = withArray "5-tuple" $ do checkLength 5 (,,,,) <$> unsafeElementAt 0 <*> unsafeElementAt 1 <*> unsafeElementAt 2 <*> unsafeElementAt 3 <*> unsafeElementAt 4 {-# INLINE parseJson #-} instance (ToJson a, ToJson b, ToJson c, ToJson d, ToJson e, ToJson f) => ToJson (a,b,c,d,e,f) where toJson (a,b,c,d,e,f) = Array $ V.create $ do mv <- VM.unsafeNew 6 VM.unsafeWrite mv 0 (toJson a) VM.unsafeWrite mv 1 (toJson b) VM.unsafeWrite mv 2 (toJson c) VM.unsafeWrite mv 3 (toJson d) VM.unsafeWrite mv 4 (toJson e) VM.unsafeWrite mv 5 (toJson f) return mv {-# INLINE toJson #-} toEncoding (a,b,c,d,e,f) = Encoding . E.brackets $ builder a <> comma <> builder b <> comma <> builder c <> comma <> builder d <> comma <> builder e <> comma <> builder f {-# INLINE toEncoding #-} instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e, FromJson f) => FromJson (a,b,c,d,e,f) where parseJson = withArray "6-tuple" $ do checkLength 6 (,,,,,) <$> unsafeElementAt 0 <*> unsafeElementAt 1 <*> unsafeElementAt 2 <*> unsafeElementAt 3 <*> unsafeElementAt 4 <*> unsafeElementAt 5 {-# INLINE parseJson #-} instance (ToJson a, ToJson b, ToJson c, ToJson d, ToJson e, ToJson f, ToJson g) => ToJson (a,b,c,d,e,f,g) where toJson (a,b,c,d,e,f,g) = Array $ V.create $ do mv <- VM.unsafeNew 7 VM.unsafeWrite mv 0 (toJson a) VM.unsafeWrite mv 1 (toJson b) VM.unsafeWrite mv 2 (toJson c) VM.unsafeWrite mv 3 (toJson d) VM.unsafeWrite mv 4 (toJson e) VM.unsafeWrite mv 5 (toJson f) VM.unsafeWrite mv 6 (toJson g) return mv {-# INLINE toJson #-} toEncoding (a,b,c,d,e,f,g) = Encoding . E.brackets $ builder a <> comma <> builder b <> comma <> builder c <> comma <> builder d <> comma <> builder e <> comma <> builder f <> comma <> builder g {-# INLINE toEncoding #-} instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e, FromJson f, FromJson g) => FromJson (a,b,c,d,e,f,g) where parseJson = withArray "7-tuple" $ do checkLength 7 (,,,,,,) <$> unsafeElementAt 0 <*> unsafeElementAt 1 <*> unsafeElementAt 2 <*> unsafeElementAt 3 <*> unsafeElementAt 4 <*> unsafeElementAt 5 <*> unsafeElementAt 6 {-# INLINE parseJson #-} instance (ToJson a, ToJson b, ToJson c, ToJson d, ToJson e, ToJson f, ToJson g, ToJson h) => ToJson (a,b,c,d,e,f,g,h) where toJson (a,b,c,d,e,f,g,h) = Array $ V.create $ do mv <- VM.unsafeNew 8 VM.unsafeWrite mv 0 (toJson a) VM.unsafeWrite mv 1 (toJson b) VM.unsafeWrite mv 2 (toJson c) VM.unsafeWrite mv 3 (toJson d) VM.unsafeWrite mv 4 (toJson e) VM.unsafeWrite mv 5 (toJson f) VM.unsafeWrite mv 6 (toJson g) VM.unsafeWrite mv 7 (toJson h) return mv {-# INLINE toJson #-} toEncoding (a,b,c,d,e,f,g,h) = Encoding . E.brackets $ builder a <> comma <> builder b <> comma <> builder c <> comma <> builder d <> comma <> builder e <> comma <> builder f <> comma <> builder g <> comma <> builder h {-# INLINE toEncoding #-} instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e, FromJson f, FromJson g, FromJson h) => FromJson (a,b,c,d,e,f,g,h) where parseJson = withArray "8-tuple" $ do checkLength 8 (,,,,,,,) <$> unsafeElementAt 0 <*> unsafeElementAt 1 <*> unsafeElementAt 2 <*> unsafeElementAt 3 <*> unsafeElementAt 4 <*> unsafeElementAt 5 <*> unsafeElementAt 6 <*> unsafeElementAt 7 {-# INLINE parseJson #-} instance (ToJson a, ToJson b, ToJson c, ToJson d, ToJson e, ToJson f, ToJson g, ToJson h, ToJson i) => ToJson (a,b,c,d,e,f,g,h,i) where toJson (a,b,c,d,e,f,g,h,i) = Array $ V.create $ do mv <- VM.unsafeNew 9 VM.unsafeWrite mv 0 (toJson a) VM.unsafeWrite mv 1 (toJson b) VM.unsafeWrite mv 2 (toJson c) VM.unsafeWrite mv 3 (toJson d) VM.unsafeWrite mv 4 (toJson e) VM.unsafeWrite mv 5 (toJson f) VM.unsafeWrite mv 6 (toJson g) VM.unsafeWrite mv 7 (toJson h) VM.unsafeWrite mv 8 (toJson i) return mv {-# INLINE toJson #-} toEncoding (a,b,c,d,e,f,g,h,i) = Encoding . E.brackets $ builder a <> comma <> builder b <> comma <> builder c <> comma <> builder d <> comma <> builder e <> comma <> builder f <> comma <> builder g <> comma <> builder h <> comma <> builder i {-# INLINE toEncoding #-} instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e, FromJson f, FromJson g, FromJson h, FromJson i) => FromJson (a,b,c,d,e,f,g,h,i) where parseJson = withArray "9-tuple" $ do checkLength 9 (,,,,,,,,) <$> unsafeElementAt 0 <*> unsafeElementAt 1 <*> unsafeElementAt 2 <*> unsafeElementAt 3 <*> unsafeElementAt 4 <*> unsafeElementAt 5 <*> unsafeElementAt 6 <*> unsafeElementAt 7 <*> unsafeElementAt 8 {-# INLINE parseJson #-} instance (ToJson a, ToJson b, ToJson c, ToJson d, ToJson e, ToJson f, ToJson g, ToJson h, ToJson i, ToJson j) => ToJson (a,b,c,d,e,f,g,h,i,j) where toJson (a,b,c,d,e,f,g,h,i,j) = Array $ V.create $ do mv <- VM.unsafeNew 10 VM.unsafeWrite mv 0 (toJson a) VM.unsafeWrite mv 1 (toJson b) VM.unsafeWrite mv 2 (toJson c) VM.unsafeWrite mv 3 (toJson d) VM.unsafeWrite mv 4 (toJson e) VM.unsafeWrite mv 5 (toJson f) VM.unsafeWrite mv 6 (toJson g) VM.unsafeWrite mv 7 (toJson h) VM.unsafeWrite mv 8 (toJson i) VM.unsafeWrite mv 9 (toJson j) return mv {-# INLINE toJson #-} toEncoding (a,b,c,d,e,f,g,h,i,j) = Encoding . E.brackets $ builder a <> comma <> builder b <> comma <> builder c <> comma <> builder d <> comma <> builder e <> comma <> builder f <> comma <> builder g <> comma <> builder h <> comma <> builder i <> comma <> builder j {-# INLINE toEncoding #-} instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e, FromJson f, FromJson g, FromJson h, FromJson i, FromJson j) => FromJson (a,b,c,d,e,f,g,h,i,j) where parseJson = withArray "10-tuple" $ do checkLength 10 (,,,,,,,,,) <$> unsafeElementAt 0 <*> unsafeElementAt 1 <*> unsafeElementAt 2 <*> unsafeElementAt 3 <*> unsafeElementAt 4 <*> unsafeElementAt 5 <*> unsafeElementAt 6 <*> unsafeElementAt 7 <*> unsafeElementAt 8 <*> unsafeElementAt 9 {-# INLINE parseJson #-} instance (ToJson a, ToJson b, ToJson c, ToJson d, ToJson e, ToJson f, ToJson g, ToJson h, ToJson i, ToJson j, ToJson k) => ToJson (a,b,c,d,e,f,g,h,i,j,k) where toJson (a,b,c,d,e,f,g,h,i,j,k) = Array $ V.create $ do mv <- VM.unsafeNew 11 VM.unsafeWrite mv 0 (toJson a) VM.unsafeWrite mv 1 (toJson b) VM.unsafeWrite mv 2 (toJson c) VM.unsafeWrite mv 3 (toJson d) VM.unsafeWrite mv 4 (toJson e) VM.unsafeWrite mv 5 (toJson f) VM.unsafeWrite mv 6 (toJson g) VM.unsafeWrite mv 7 (toJson h) VM.unsafeWrite mv 8 (toJson i) VM.unsafeWrite mv 9 (toJson j) VM.unsafeWrite mv 10 (toJson k) return mv {-# INLINE toJson #-} toEncoding (a,b,c,d,e,f,g,h,i,j,k) = Encoding . E.brackets $ builder a <> comma <> builder b <> comma <> builder c <> comma <> builder d <> comma <> builder e <> comma <> builder f <> comma <> builder g <> comma <> builder h <> comma <> builder i <> comma <> builder j <> comma <> builder k {-# INLINE toEncoding #-} instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e, FromJson f, FromJson g, FromJson h, FromJson i, FromJson j, FromJson k) => FromJson (a,b,c,d,e,f,g,h,i,j,k) where parseJson = withArray "11-tuple" $ do checkLength 11 (,,,,,,,,,,) <$> unsafeElementAt 0 <*> unsafeElementAt 1 <*> unsafeElementAt 2 <*> unsafeElementAt 3 <*> unsafeElementAt 4 <*> unsafeElementAt 5 <*> unsafeElementAt 6 <*> unsafeElementAt 7 <*> unsafeElementAt 8 <*> unsafeElementAt 9 <*> unsafeElementAt 10 {-# INLINE parseJson #-} instance (ToJson a, ToJson b, ToJson c, ToJson d, ToJson e, ToJson f, ToJson g, ToJson h, ToJson i, ToJson j, ToJson k, ToJson l) => ToJson (a,b,c,d,e,f,g,h,i,j,k,l) where toJson (a,b,c,d,e,f,g,h,i,j,k,l) = Array $ V.create $ do mv <- VM.unsafeNew 12 VM.unsafeWrite mv 0 (toJson a) VM.unsafeWrite mv 1 (toJson b) VM.unsafeWrite mv 2 (toJson c) VM.unsafeWrite mv 3 (toJson d) VM.unsafeWrite mv 4 (toJson e) VM.unsafeWrite mv 5 (toJson f) VM.unsafeWrite mv 6 (toJson g) VM.unsafeWrite mv 7 (toJson h) VM.unsafeWrite mv 8 (toJson i) VM.unsafeWrite mv 9 (toJson j) VM.unsafeWrite mv 10 (toJson k) VM.unsafeWrite mv 11 (toJson l) return mv {-# INLINE toJson #-} toEncoding (a,b,c,d,e,f,g,h,i,j,k,l) = Encoding . E.brackets $ builder a <> comma <> builder b <> comma <> builder c <> comma <> builder d <> comma <> builder e <> comma <> builder f <> comma <> builder g <> comma <> builder h <> comma <> builder i <> comma <> builder j <> comma <> builder k <> comma <> builder l {-# INLINE toEncoding #-} instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e, FromJson f, FromJson g, FromJson h, FromJson i, FromJson j, FromJson k, FromJson l) => FromJson (a,b,c,d,e,f,g,h,i,j,k,l) where parseJson = withArray "12-tuple" $ do checkLength 12 (,,,,,,,,,,,) <$> unsafeElementAt 0 <*> unsafeElementAt 1 <*> unsafeElementAt 2 <*> unsafeElementAt 3 <*> unsafeElementAt 4 <*> unsafeElementAt 5 <*> unsafeElementAt 6 <*> unsafeElementAt 7 <*> unsafeElementAt 8 <*> unsafeElementAt 9 <*> unsafeElementAt 10 <*> unsafeElementAt 11 {-# INLINE parseJson #-} instance (ToJson a, ToJson b, ToJson c, ToJson d, ToJson e, ToJson f, ToJson g, ToJson h, ToJson i, ToJson j, ToJson k, ToJson l, ToJson m) => ToJson (a,b,c,d,e,f,g,h,i,j,k,l,m) where toJson (a,b,c,d,e,f,g,h,i,j,k,l,m) = Array $ V.create $ do mv <- VM.unsafeNew 13 VM.unsafeWrite mv 0 (toJson a) VM.unsafeWrite mv 1 (toJson b) VM.unsafeWrite mv 2 (toJson c) VM.unsafeWrite mv 3 (toJson d) VM.unsafeWrite mv 4 (toJson e) VM.unsafeWrite mv 5 (toJson f) VM.unsafeWrite mv 6 (toJson g) VM.unsafeWrite mv 7 (toJson h) VM.unsafeWrite mv 8 (toJson i) VM.unsafeWrite mv 9 (toJson j) VM.unsafeWrite mv 10 (toJson k) VM.unsafeWrite mv 11 (toJson l) VM.unsafeWrite mv 12 (toJson m) return mv {-# INLINE toJson #-} toEncoding (a,b,c,d,e,f,g,h,i,j,k,l,m) = Encoding . E.brackets $ builder a <> comma <> builder b <> comma <> builder c <> comma <> builder d <> comma <> builder e <> comma <> builder f <> comma <> builder g <> comma <> builder h <> comma <> builder i <> comma <> builder j <> comma <> builder k <> comma <> builder l <> comma <> builder m {-# INLINE toEncoding #-} instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e, FromJson f, FromJson g, FromJson h, FromJson i, FromJson j, FromJson k, FromJson l, FromJson m) => FromJson (a,b,c,d,e,f,g,h,i,j,k,l,m) where parseJson = withArray "13-tuple" $ do checkLength 13 (,,,,,,,,,,,,) <$> unsafeElementAt 0 <*> unsafeElementAt 1 <*> unsafeElementAt 2 <*> unsafeElementAt 3 <*> unsafeElementAt 4 <*> unsafeElementAt 5 <*> unsafeElementAt 6 <*> unsafeElementAt 7 <*> unsafeElementAt 8 <*> unsafeElementAt 9 <*> unsafeElementAt 10 <*> unsafeElementAt 11 <*> unsafeElementAt 12 {-# INLINE parseJson #-} instance (ToJson a, ToJson b, ToJson c, ToJson d, ToJson e, ToJson f, ToJson g, ToJson h, ToJson i, ToJson j, ToJson k, ToJson l, ToJson m, ToJson n) => ToJson (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where toJson (a,b,c,d,e,f,g,h,i,j,k,l,m,n) = Array $ V.create $ do mv <- VM.unsafeNew 14 VM.unsafeWrite mv 0 (toJson a) VM.unsafeWrite mv 1 (toJson b) VM.unsafeWrite mv 2 (toJson c) VM.unsafeWrite mv 3 (toJson d) VM.unsafeWrite mv 4 (toJson e) VM.unsafeWrite mv 5 (toJson f) VM.unsafeWrite mv 6 (toJson g) VM.unsafeWrite mv 7 (toJson h) VM.unsafeWrite mv 8 (toJson i) VM.unsafeWrite mv 9 (toJson j) VM.unsafeWrite mv 10 (toJson k) VM.unsafeWrite mv 11 (toJson l) VM.unsafeWrite mv 12 (toJson m) VM.unsafeWrite mv 13 (toJson n) return mv {-# INLINE toJson #-} toEncoding (a,b,c,d,e,f,g,h,i,j,k,l,m,n) = Encoding . E.brackets $ builder a <> comma <> builder b <> comma <> builder c <> comma <> builder d <> comma <> builder e <> comma <> builder f <> comma <> builder g <> comma <> builder h <> comma <> builder i <> comma <> builder j <> comma <> builder k <> comma <> builder l <> comma <> builder m <> comma <> builder n {-# INLINE toEncoding #-} instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e, FromJson f, FromJson g, FromJson h, FromJson i, FromJson j, FromJson k, FromJson l, FromJson m, FromJson n) => FromJson (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where parseJson = withArray "14-tuple" $ do checkLength 14 (,,,,,,,,,,,,,) <$> unsafeElementAt 0 <*> unsafeElementAt 1 <*> unsafeElementAt 2 <*> unsafeElementAt 3 <*> unsafeElementAt 4 <*> unsafeElementAt 5 <*> unsafeElementAt 6 <*> unsafeElementAt 7 <*> unsafeElementAt 8 <*> unsafeElementAt 9 <*> unsafeElementAt 10 <*> unsafeElementAt 11 <*> unsafeElementAt 12 <*> unsafeElementAt 13 {-# INLINE parseJson #-} instance (ToJson a, ToJson b, ToJson c, ToJson d, ToJson e, ToJson f, ToJson g, ToJson h, ToJson i, ToJson j, ToJson k, ToJson l, ToJson m, ToJson n, ToJson o) => ToJson (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where toJson (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) = Array $ V.create $ do mv <- VM.unsafeNew 15 VM.unsafeWrite mv 0 (toJson a) VM.unsafeWrite mv 1 (toJson b) VM.unsafeWrite mv 2 (toJson c) VM.unsafeWrite mv 3 (toJson d) VM.unsafeWrite mv 4 (toJson e) VM.unsafeWrite mv 5 (toJson f) VM.unsafeWrite mv 6 (toJson g) VM.unsafeWrite mv 7 (toJson h) VM.unsafeWrite mv 8 (toJson i) VM.unsafeWrite mv 9 (toJson j) VM.unsafeWrite mv 10 (toJson k) VM.unsafeWrite mv 11 (toJson l) VM.unsafeWrite mv 12 (toJson m) VM.unsafeWrite mv 13 (toJson n) VM.unsafeWrite mv 14 (toJson o) return mv {-# INLINE toJson #-} toEncoding (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) = Encoding . E.brackets $ builder a <> comma <> builder b <> comma <> builder c <> comma <> builder d <> comma <> builder e <> comma <> builder f <> comma <> builder g <> comma <> builder h <> comma <> builder i <> comma <> builder j <> comma <> builder k <> comma <> builder l <> comma <> builder m <> comma <> builder n <> comma <> builder o {-# INLINE toEncoding #-} instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e, FromJson f, FromJson g, FromJson h, FromJson i, FromJson j, FromJson k, FromJson l, FromJson m, FromJson n, FromJson o) => FromJson (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where parseJson = withArray "15-tuple" $ do checkLength 15 (,,,,,,,,,,,,,,) <$> unsafeElementAt 0 <*> unsafeElementAt 1 <*> unsafeElementAt 2 <*> unsafeElementAt 3 <*> unsafeElementAt 4 <*> unsafeElementAt 5 <*> unsafeElementAt 6 <*> unsafeElementAt 7 <*> unsafeElementAt 8 <*> unsafeElementAt 9 <*> unsafeElementAt 10 <*> unsafeElementAt 11 <*> unsafeElementAt 12 <*> unsafeElementAt 13 <*> unsafeElementAt 14 {-# INLINE parseJson #-} instance ToJson a => ToJson (Dual a) where toJson = toJson . getDual {-# INLINE toJson #-} toEncoding = toEncoding . getDual {-# INLINE toEncoding #-} instance FromJson a => FromJson (Dual a) where parseJson = Dual <$> parseJson {-# INLINE parseJson #-} instance ToJson a => ToJson (First a) where toJson = toJson . getFirst {-# INLINE toJson #-} toEncoding = toEncoding . getFirst {-# INLINE toEncoding #-} instance FromJson a => FromJson (First a) where parseJson = First <$> parseJson {-# INLINE parseJson #-} instance ToJson a => ToJson (Last a) where toJson = toJson . getLast {-# INLINE toJson #-} toEncoding = toEncoding . getLast {-# INLINE toEncoding #-} instance FromJson a => FromJson (Last a) where parseJson = Last <$> parseJson {-# INLINE parseJson #-} instance ToJson Version where toJson = toJson . showVersion {-# INLINE toJson #-} toEncoding = toEncoding . showVersion {-# INLINE toEncoding #-} instance FromJson Version where {-# INLINE parseJson #-} parseJson = do t <- getString "Version" go . readP_to_S parseVersion . unpack $ t where go [(v,[])] = return v go (_ : xs) = go xs go _ = fail $ "could not parse Version" {- -- | Retrieve the value associated with the given key of an 'Object'. -- The result is 'Nothing' if the key is not present, or 'empty' if -- the value cannot be converted to the desired type. -- -- This accessor is most useful if the key and value can be absent -- from an object without affecting its validity. If the key and -- value are mandatory, use '.:' instead. (.:?) :: (FromJson a) => Object -> Text -> Parser (Maybe a) obj .:? key = case H.lookup key obj of Nothing -> pure Nothing Just v -> modifyFailure addKeyName $ parseJson v <?> Key key where addKeyName = (("failed to parse field " <> unpack key <> ": ") <>) {-# INLINE (.:?) #-} -- | Like '.:?', but the resulting parser will fail, -- if the key is present but is 'Null'. (.:!) :: (FromJson a) => Object -> Text -> Parser (Maybe a) obj .:! key = case H.lookup key obj of Nothing -> pure Nothing Just v -> modifyFailure addKeyName $ Just <$> parseJson v <?> Key key where addKeyName = (("failed to parse field " <> unpack key <> ": ") <>) {-# INLINE (.:!) #-} -- | Helper for use in combination with '.:?' to provide default -- values for optional JSON object fields. -- -- This combinator is most useful if the key and value can be absent -- from an object without affecting its validity and we know a default -- value to assign in that case. If the key and value are mandatory, -- use '.:' instead. -- -- Example usage: -- -- @ v1 <- o '.:?' \"opt_field_with_dfl\" .!= \"default_val\" -- v2 <- o '.:' \"mandatory_field\" -- v3 <- o '.:?' \"opt_field2\" -- @ (.!=) :: Parser (Maybe a) -> a -> Parser a pmval .!= val = fromMaybe val <$> pmval {-# INLINE (.!=) #-} -} realFloatToJson :: RealFloat a => a -> Json realFloatToJson d | isNaN d || isInfinite d = Null | otherwise = Number $ Scientific.fromFloatDigits d {-# INLINE realFloatToJson #-} realFloatToEncoding :: RealFloat a => a -> Encoding realFloatToEncoding d | isNaN d || isInfinite d = Encoding E.null_ | otherwise = toEncoding (Scientific.fromFloatDigits d) {-# INLINE realFloatToEncoding #-} scientificToNumber :: Scientific -> Number scientificToNumber s | e < 0 = D $ Scientific.toRealFloat s | otherwise = I $ c * 10 ^ e where e = Scientific.base10Exponent s c = Scientific.coefficient s {-# INLINE scientificToNumber #-} -- TODO: specify in the docs that parsing a null results in a NaN parseRealFloat :: RealFloat a => String -> Parser Json a parseRealFloat expected = Scientific.toRealFloat <$> getNumber expected <|> (0/0) <$ getNull expected {-# INLINE parseRealFloat #-} parseIntegral :: Integral a => String -> Parser Json a parseIntegral expected = truncate <$> getNumber expected {-# INLINE parseIntegral #-} -- TODO: add tests for errors
aelve/json-x
lib/Json/Internal/Instances.hs
bsd-3-clause
49,867
0
36
13,786
15,453
7,968
7,485
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module Backend.InductiveGraph.Probability (toProbBDD, nodeProb) where import Backend.InductiveGraph.InductiveGraph import Control.Arrow (first) import Control.Monad import Data.Graph.Inductive import Data.Maybe import Data.String.Interpolate import Data.Text.Lazy (unpack) import Utils.Plot (plotDot, plotTikz) type ExtendedNodeLabel = (NodeLabel, Float, [Float]) type ProbBDD = Gr ExtendedNodeLabel EdgeLabel boolToFloat :: Fractional b => [Bool] -> [b] boolToFloat bv = let as = 2 ^ (length bv) iv = boolToInt bv f i = if i == iv then 1.0 else 0.0 rv = [ f i | i <- [0 .. as - 1] ] in rv boolToInt :: [Bool] -> Int boolToInt bv = let bs = map (\x -> if x then 1 else 0) bv bb = reverse [ 2^i | i <- [ 0 .. (length bv) - 1]] zp = sum $ zipWith (*) bb bs in zp groundprob :: ProbBDD -> Node -> [Float] groundprob b n = case (context b n) of (_, _, (D _, _, gp), _) -> gp _ -> error "cant compute ground prob" toProbBDD :: (String -> Float) -> BDD -> ProbBDD toProbBDD f b = propagate $ annote f b annote :: (String -> Float) -> BDD -> ProbBDD annote f b = let g nl@(Vr s) = (nl, f s, []) g nl@(D bv) = (nl, 1.0, boolToFloat bv) in nmap g b propagate :: ProbBDD -> ProbBDD propagate b = let f (r, n, (nl, pr, pv), s) = (r, n, (nl, pr, nodeProb b n), s) in gmap f b isLeaf b n = case (context b n) of (_, _, (D _,_,_), _) -> True _ -> False branchProb b n = case (context b n) of (_,_, (Vr _, bp, _), _) -> bp _ -> error "sorry, this is not a branch node" nodeProb :: ProbBDD -> Node -> [Float] nodeProb b n = if isLeaf b n then groundprob b n else let (nf, nt) = subNodes b n (gf, gt) = (nodeProb b nf, nodeProb b nt) p = branchProb b n s = zipWith (+) (map ((1-p) *) gf) (map (p *) gt) in s subNodes :: ProbBDD -> Node -> (Node, Node) subNodes b n = let (_, _, nl, s) = context b n in case s of [(False, nf), (True, nt)] -> (nf, nt) [(True, nt), (False, nf)] -> (nf, nt) _ -> error [i| node (#{show n} - #{nl}) found to have outgoing edges #{show s} |]
vzaccaria/bddtool
src/Backend/InductiveGraph/Probability.hs
bsd-3-clause
2,363
0
16
756
1,029
571
458
68
3
module Internal.HaskellPackage ( Package(..), getPackage, sourceFromHackage ) where import qualified Distribution.Nixpkgs.Haskell.Hackage as DB import qualified Control.Exception as Exception import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Maybe import Data.List ( isSuffixOf, isPrefixOf ) import Data.Maybe import Data.Version import Distribution.Nixpkgs.Fetch import qualified Distribution.Package as Cabal import qualified Distribution.PackageDescription as Cabal import qualified Distribution.PackageDescription.Parse as Cabal import qualified Distribution.ParseUtils as ParseUtils import Distribution.Text ( simpleParse ) import System.Directory ( doesDirectoryExist, doesFileExist, createDirectoryIfMissing, getHomeDirectory, getDirectoryContents ) import System.Exit ( exitFailure ) import System.FilePath ( (</>), (<.>) ) import System.IO ( hPutStrLn, stderr, hPutStr ) data Package = Package { pkgSource :: DerivationSource , pkgCabal :: Cabal.GenericPackageDescription } deriving (Show) getPackage :: Maybe String -> Source -> IO Package getPackage optHackageDB source = do (derivSource, pkgDesc) <- fetchOrFromDB optHackageDB source flip Package pkgDesc <$> maybe (sourceFromHackage (sourceHash source) $ showPackageIdentifier pkgDesc) return derivSource fetchOrFromDB :: Maybe String -> Source -> IO (Maybe DerivationSource, Cabal.GenericPackageDescription) fetchOrFromDB optHackageDB src | "cabal://" `isPrefixOf` sourceUrl src = fmap ((,) Nothing) . fromDB optHackageDB . drop (length "cabal://") $ sourceUrl src | otherwise = do r <- fetch cabalFromPath src case r of Nothing -> hPutStrLn stderr "*** failed to fetch source. Does the URL exist?" >> exitFailure Just (derivSource, (externalSource, pkgDesc)) -> return (derivSource <$ guard externalSource, pkgDesc) fromDB :: Maybe String -> String -> IO Cabal.GenericPackageDescription fromDB optHackageDB pkg = do pkgDesc <- (lookupVersion <=< DB.lookup name) <$> maybe DB.readHashedHackage DB.readHackage' optHackageDB case pkgDesc of Just r -> return r Nothing -> hPutStrLn stderr "*** no such package in the cabal database (did you run cabal update?). " >> exitFailure where pkgId = fromMaybe (error ("invalid Haskell package id " ++ show pkg)) (simpleParse pkg) Cabal.PackageName name = Cabal.pkgName pkgId version = Cabal.pkgVersion pkgId lookupVersion :: DB.Map DB.Version Cabal.GenericPackageDescription -> Maybe Cabal.GenericPackageDescription lookupVersion | null (versionBranch version) = fmap snd . listToMaybe . reverse . DB.toAscList | otherwise = DB.lookup version readFileMay :: String -> IO (Maybe String) readFileMay file = do e <- doesFileExist file if e then Just <$> readFile file else return Nothing hashCachePath :: String -> IO String hashCachePath pid = do home <- getHomeDirectory let cacheDir = home </> ".cache/cabal2nix" createDirectoryIfMissing True cacheDir return $ cacheDir </> pid <.> "sha256" sourceFromHackage :: Hash -> String -> IO DerivationSource sourceFromHackage optHash pkgId = do cacheFile <- hashCachePath pkgId cachedHash <- case optHash of Certain h -> return . Certain $ h Guess h -> return . Guess $ h _ -> fmap (maybe UnknownHash Certain) . readFileMay $ cacheFile let url = "mirror://hackage/" ++ pkgId ++ ".tar.gz" -- Use the cached hash (either from cache file or given on cmdline via sha256 opt) -- if available, otherwise download from hackage to compute hash. case cachedHash of Guess hash -> return $ DerivationSource "url" url "" hash Certain hash -> -- We need to force the hash here. If we didn't do this, then when reading the -- hash from the cache file, the cache file will still be open for reading -- (because lazy io) when writeFile opens the file again for writing. By forcing -- the hash here, we ensure that the file is closed before opening it again. seq (length hash) $ DerivationSource "url" url "" hash <$ writeFile cacheFile hash UnknownHash -> do maybeHash <- runMaybeT (derivHash . fst <$> fetchWith (False, "url", []) (Source url "" UnknownHash)) case maybeHash of Just hash -> seq (length hash) $ DerivationSource "url" url "" hash <$ writeFile cacheFile hash Nothing -> do hPutStr stderr $ unlines [ "*** cannot compute hash. (Not a hackage project?)" , " If your project is not on hackage, please supply the path to the root directory of" , " the project, not to the cabal file." , "" , " If your project is on hackage but you still want to specify the hash manually, you" , " can use the --sha256 option." ] exitFailure showPackageIdentifier :: Cabal.GenericPackageDescription -> String showPackageIdentifier pkgDesc = name ++ "-" ++ showVersion version where pkgId = Cabal.package . Cabal.packageDescription $ pkgDesc Cabal.PackageName name = Cabal.packageName pkgId version = Cabal.packageVersion pkgId cabalFromPath :: FilePath -> MaybeT IO (Bool, Cabal.GenericPackageDescription) cabalFromPath path = do d <- liftIO $ doesDirectoryExist path (,) d <$> if d then cabalFromDirectory path else cabalFromFile False path cabalFromDirectory :: FilePath -> MaybeT IO Cabal.GenericPackageDescription cabalFromDirectory dir = do cabals <- liftIO $ getDirectoryContents dir >>= filterM doesFileExist . map (dir </>) . filter (".cabal" `isSuffixOf`) case cabals of [cabalFile] -> cabalFromFile True cabalFile _ -> liftIO $ hPutStrLn stderr "*** found zero or more than one cabal file. Exiting." >> exitFailure handleIO :: (Exception.IOException -> IO a) -> IO a -> IO a handleIO = Exception.handle cabalFromFile :: Bool -> FilePath -> MaybeT IO Cabal.GenericPackageDescription cabalFromFile failHard file = -- readFile throws an error if it's used on binary files which contain sequences -- that do not represent valid characters. To catch that exception, we need to -- wrap the whole block in `catchIO`, because of lazy IO. The `case` will force -- the reading of the file, so we will always catch the expression here. MaybeT $ handleIO (\err -> Nothing <$ hPutStrLn stderr ("*** parsing cabal file: " ++ show err)) $ do content <- readFile file case Cabal.parsePackageDescription content of Cabal.ParseFailed e | failHard -> do let (line, err) = ParseUtils.locatedErrorMsg e msg = maybe "" ((++ ": ") . show) line ++ err hPutStrLn stderr $ "*** error parsing cabal file: " ++ msg exitFailure Cabal.ParseFailed _ -> return Nothing Cabal.ParseOk _ a -> return (Just a)
psibi/cabal2nix
src/Internal/HaskellPackage.hs
bsd-3-clause
6,866
0
21
1,450
1,684
852
832
123
6
-- | This module contains the 'SourceId' wrapper type, that indicate that -- something is identifies a single source of media. This could be an RTP SSRC -- or the IP/Port pair of a network source. The defining characteristic of a -- 'SourceId' is that every thing that has a certain source id stems from **the -- same media source**, e.g. the same microphone, audio file, synthesizer,... module Data.MediaBus.Basics.SourceId ( SourceId (..), sourceIdValue, type SrcId32, type SrcId64, HasSourceId (..), EachSourceId (..), ) where import Control.DeepSeq import Control.Lens import Data.Default import Data.Word import GHC.Generics (Generic) import Test.QuickCheck -- | Things that can be uniquely identified by a looking at a (much simpler) -- representation, the 'identity'. newtype SourceId i = MkSourceId { _sourceIdValue :: i } deriving (Eq, Arbitrary, Default, Ord, Generic) -- | An 'Iso' for the value of a 'SourceId' sourceIdValue :: Iso (SourceId a) (SourceId b) a b sourceIdValue = iso _sourceIdValue MkSourceId -- | A short alias for 'SourceId' with a 'Word32' value type SrcId32 = SourceId Word32 -- | A short alias for 'SourceId' with a 'Word64' value type SrcId64 = SourceId Word64 instance (NFData i) => NFData (SourceId i) instance Show i => Show (SourceId i) where showsPrec d (MkSourceId x) = showParen (d > 10) $ showString "source-id: " . showsPrec 11 x -- | Type class for a lens over the contained source id class HasSourceId s t where type SourceIdFrom s type SourceIdTo t -- | A lens for the 'SourceId' sourceId :: Lens s t (SourceIdFrom s) (SourceIdTo t) -- | Type class with a 'Traversal' for types that may or may not contain anctual -- source id. class EachSourceId s t where type SourceIdsFrom s type SourceIdsTo t -- | A 'Traversal' for the 'SourceId' eachSourceId :: Traversal s t (SourceIdsFrom s) (SourceIdsTo t)
lindenbaum/mediabus
src/Data/MediaBus/Basics/SourceId.hs
bsd-3-clause
1,927
0
10
387
361
206
155
-1
-1
data A = B :+: B data B = Int :*: Int infixl 6 :+: infixl 7 :*: instance Show A where showsPrec d (b :+: c) | d > 6 = ("(" ++) . showsPrec 7 b . (" :+: " ++) . showsPrec 7 c . (")" ++) | otherwise = showsPrec 7 b . (" :+: " ++) . showsPrec 7 c instance Show B where showsPrec d (m :*: n) | d > 7 = ("(" ++) . showsPrec 8 m . (" :*: " ++) . showsPrec 8 n . (")" ++) | otherwise = showsPrec 8 m . (" :*: " ++) . showsPrec 8 n
YoshikuniJujo/funpaala
samples/27_basic_type_classes/showBinding0.hs
bsd-3-clause
443
0
11
131
239
124
115
14
0
module VideoCore4.QPU.Instruction.BranchRelative ( BranchRelative , rel_Off , rel_On ) where import Data.Typeable import Data.Word import VideoCore4.QPU.Instruction.Types newtype BranchRelative = BranchRelative { unBranchRelative :: Word8 } deriving (Eq, Show, Typeable) instance To64 BranchRelative where to64 = toEnum . fromEnum . unBranchRelative rel_Off :: BranchRelative rel_Off = BranchRelative 0 rel_On :: BranchRelative rel_On = BranchRelative 1
notogawa/VideoCore4
src/VideoCore4/QPU/Instruction/BranchRelative.hs
bsd-3-clause
497
0
7
97
111
66
45
15
1
import Data.List import Data.Ord mode :: Ord a => [a] -> a mode = head . maximumBy (comparing length) . group . sort isInt n = n == (fromInteger (round n)) integerRightTriangles cap = mode [p | a <- [1..cap / 2], b <- [1..(cap / 2)], let c = sqrt (a^2 + b^2), let p = a + b + c, isInt c, p <= cap] main = print . integerRightTriangles $ 1000
JacksonGariety/euler.hs
039.hs
bsd-3-clause
487
0
15
219
205
105
100
11
1
type ListZipper a = ([a], [a]) goForward :: ListZipper a -> ListZipper a goForward (x:xs, bs) = (xs, x:bs) goBack :: ListZipper a -> ListZipper a goBack (xs, b:bs) = (b:xs, bs)
ku00/h-book
src/ListZipper.hs
bsd-3-clause
179
0
7
34
106
59
47
5
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE Trustworthy #-} module Data.Hexagon.Range (range) where import Control.Lens.Review import Control.Lens.Getter import Control.Lens.Operators import Data.Hexagon.Types range :: (HexCoordinate t a, Integral a) => a -> t a -> [t a] range n c = fmap (view _CoordinateCubeIso) . cubeRange n $ c ^. re _CoordinateCubeIso cubeRange :: (Integral a) => a -> CubeCoordinate a -> [CubeCoordinate a] cubeRange n c = let dxys = [(dx, [(max (-n) (-dx-n)) .. (min (n) (n-dx))] ) | dx <- [-n .. n]] addDelta dx dy = c & cubeX +~ dx & cubeY +~ dy & cubeZ +~ (-dx-dy) applyDelta (dx, dys) = fmap (addDelta dx) dys in mconcat . fmap applyDelta $ dxys
alios/hexagon
src/Data/Hexagon/Range.hs
bsd-3-clause
725
0
16
162
316
170
146
16
1
{-# LANGUAGE TypeOperators #-} module SortOverMorphism where -- ref.) http://www.cs.ox.ac.uk/people/daniel.james/sorting/sorting.pdf import Data.List (partition, unfoldr, delete) pair :: (a -> b) -> (a -> c) -> a -> (b, c) pair f g x = (f x, g x) cross :: (a -> c) -> (b -> d) -> (a, b) -> (c, d) cross f g (x, y) = (f x, g y) insertSort :: [Integer] -> [Integer] insertSort = foldr insert [] insert :: Integer -> [Integer] -> [Integer] insert y ys = xs ++ [y] ++ zs where (xs, zs) = partition (<y) ys selectSort :: [Integer] -> [Integer] selectSort = unfoldr select select :: [Integer] -> Maybe (Integer, [Integer]) select [] = Nothing select xs = Just (x, xs') where x = minimum xs xs' = delete x xs ------------------------------------------------------------------------------------ newtype Mu f = In { in' :: f (Mu f) } fold :: (Functor f) => (f a -> a) -> Mu f -> a fold f = f . fmap (fold f) . in' newtype Nu f = Out' { out :: f (Nu f) } out' :: f (Nu f) -> Nu f out' = Out' unfold :: (Functor f) => (a -> f a) -> (a -> Nu f) unfold f = out' . fmap (unfold f) . f para :: Functor f => (f (Mu f :*: a) -> a) -> Mu f -> a para f = f . fmap (id `split` para f) . in' apo :: Functor f => (b -> f (Nu f :+: b)) -> b -> Nu f apo f = Out' . fmap (id `join` apo f) . f ------------------------------------------------------------------------------------ type a :*: b = (a, b) split :: (a -> b) -> (a -> c) -> a -> b :*: c split = pair data a :+: b = Stop a | Play b deriving Show join :: (a -> c) -> (b -> c) -> a :+: b -> c (f `join` _) (Stop x) = f x (_ `join` g) (Play y) = g y ------------------------------------------------------------------------------------ downcast :: (Functor f) => Nu f -> Mu f downcast = In . fmap downcast . out upcast :: (Functor f) => Mu f -> Nu f upcast = fold (unfold (fmap out)) -- == fold out' -- これは fold In == id だから upcast' :: (Functor f) => Mu f -> Nu f upcast' = unfold (fold (fmap In)) -- == unfold in' -- これは unfold out == id だから ------------------------------------------------------------------------------------ -- NOTE : instance of Ord type K = Int data List list = Nil | Cons K list deriving Show instance Functor List where fmap f Nil = Nil fmap f (Cons k x) = Cons k (f x) data SList list = SNil | SCons K list deriving Show instance Functor SList where fmap f SNil = SNil fmap f (SCons k x) = SCons k (f x) bubbleSort :: Mu List -> Nu SList bubbleSort = unfold bubble where bubble = fold bub bub :: List (SList (Mu List)) -> SList (Mu List) bub Nil = SNil bub (Cons a SNil) = SCons a (In Nil) bub (Cons a (SCons b x)) | a <= b = SCons a (In (Cons b x)) | otherwise = SCons b (In (Cons a x)) naiveInsertSort :: Mu List -> Nu SList naiveInsertSort = fold naiveInsert where naiveInsert = unfold naiveIns naiveIns :: List (Nu SList) -> SList (List (Nu SList)) naiveIns Nil = SNil naiveIns (Cons a (Out' SNil)) = SCons a Nil naiveIns (Cons a (Out' (SCons b x))) | a <= b = SCons a (Cons b x) | otherwise = SCons b (Cons a x) ------------------------------------------------------------------------------------ swap :: List (SList x) -> SList (List x) swap Nil = SNil swap (Cons a SNil) = SCons a Nil swap (Cons a (SCons b x)) | a <= b = SCons a (Cons b x) | otherwise = SCons b (Cons a x) bubbleSort' :: Mu List -> Nu SList bubbleSort' = unfold (fold (fmap In . swap)) naiveInsertSort' :: Mu List -> Nu SList naiveInsertSort' = fold (unfold (swap . fmap out)) ------------------------------------------------------------------------------------ insertSort' :: Mu List -> Nu SList insertSort' = fold insert where insert = apo ins ins :: List (Nu SList) -> SList (Nu SList :+: List (Nu SList)) ins Nil = SNil ins (Cons a (Out' SNil)) = SCons a (Stop (Out' SNil)) ins (Cons a (Out' (SCons b x'))) | a <= b = SCons a (Stop (Out' (SCons b x'))) | otherwise = SCons b (Play (Cons a x')) insertSort'' :: Mu List -> Nu SList insertSort'' = fold insert where insert = apo (swop . fmap (id `split` out)) selectSort' :: Mu List -> Nu SList selectSort' = unfold select where select = para sel sel :: List (Mu List, SList (Mu List)) -> SList (Mu List) sel Nil = SNil sel (Cons a (x, SNil)) = SCons a x sel (Cons a (x, SCons b x')) | a <= b = SCons a x | otherwise = SCons b (In (Cons a x')) selectSort'' :: Mu List -> Nu SList selectSort'' = unfold select where select = para (fmap (id `join` In) . swop) swop :: List (x :*: SList x) -> SList (x :+: List x) swop Nil = SNil swop (Cons a (x, SNil)) = SCons a (Stop x) swop (Cons a (x, SCons b x')) | a <= b = SCons a (Stop x) | otherwise = SCons b (Play (Cons a x')) ------------------------------------------------------------------------------------ data Tree t = Empty | Node t K t deriving Show instance Functor Tree where fmap f Empty = Empty fmap f (Node l k r) = Node (f l) k (f r) type SearchTree = Tree pivot :: List (SearchTree (Mu List)) -> SearchTree (Mu List) pivot Nil = Empty pivot (Cons a Empty) = Node (In Nil) a (In Nil) pivot (Cons a (Node l b r)) | a <= b = Node (In (Cons a l)) b r | otherwise = Node l b (In (Cons a r)) sprout :: List (x :*: SearchTree x) -> SearchTree (x :+: List x) sprout Nil = Empty sprout (Cons a (t, Empty)) = Node (Stop t) a (Stop t) sprout (Cons a (t, Node l b r)) | a <= b = Node (Play (Cons a l)) b (Stop r) | otherwise = Node (Stop l) b (Play (Cons a r)) treeIns :: List (Nu SearchTree) -> SearchTree (Nu SearchTree :+: List (Nu SearchTree)) treeIns Nil = Empty treeIns (Cons a (Out' Empty)) = Node (Stop (Out' Empty)) a (Stop (Out' Empty)) treeIns (Cons a (Out' (Node l b r))) | a <= b = Node (Play (Cons a l)) b (Stop r) | otherwise = Node (Stop l) b (Play (Cons a r)) grow :: Mu List -> Nu SearchTree grow = unfold (para (fmap (id `join` In) . sprout)) grow' :: Mu List -> Nu SearchTree grow' = fold (apo (sprout . fmap (id `split` out))) ------------------------------------------------------------------------------------ glue :: SearchTree (Nu SList) -> SList (Nu SList :+: SearchTree (Nu SList)) glue Empty = SNil glue (Node (Out' SNil) a r) = SCons a (Stop r) glue (Node (Out' (SCons b l)) a r) = SCons b (Play (Node l a r)) wither :: SearchTree (x :*: SList x) -> SList (x :+: SearchTree x) wither Empty = SNil wither (Node (l, SNil) a (r, _)) = SCons a (Stop r) wither (Node (l, SCons b l') a (r, _)) = SCons b (Play (Node l' a r)) shear :: SearchTree (Mu SearchTree :*: SList (Mu SearchTree)) -> SList (Mu SearchTree) shear Empty = SNil shear (Node (l, SNil) a (r, _)) = SCons a r shear (Node (l, SCons b l') a (r, _)) = SCons b (In (Node l' a r)) flatten :: Mu SearchTree -> Nu SList flatten = fold (apo (wither . fmap (id `split` out))) flatten' :: Mu SearchTree -> Nu SList flatten' = unfold (para (fmap (id `join` In) . wither)) quickSort :: Mu List -> Nu SList quickSort = flatten . downcast . grow treeSort :: Mu List -> Nu SList treeSort = flatten' . downcast . grow' ------------------------------------------------------------------------------------ type Heap = Tree pile :: List (x :*: Heap x) -> Heap (x :+: List x) pile Nil = Empty pile (Cons a (t, Empty)) = Node (Stop t) a (Stop t) pile (Cons a (t, Node l b r)) | a <= b = Node (Play (Cons b r)) a (Stop l) | otherwise = Node (Play (Cons a r)) b (Stop l) heapIns :: List (Nu Heap) -> Heap (Nu Heap :+: List (Nu Heap)) heapIns Nil = Empty heapIns (Cons a (Out' Empty)) = Node (Stop (Out' Empty)) a (Stop (Out' Empty)) heapIns (Cons a (Out' (Node l b r))) | a <= b = Node (Play (Cons b r)) a (Stop l) | otherwise = Node (Play (Cons a r)) b (Stop l) divvy :: List (Heap (Mu List)) -> Heap (Mu List) divvy Nil = Empty divvy (Cons a Empty) = Node (In Nil) a (In Nil) divvy (Cons a (Node l b r)) | a <= b = Node (In (Cons b r)) a l | otherwise = Node (In (Cons a r)) b l sift :: Heap (x :*: SList x) -> SList (x :+: Heap x) sift Empty = SNil sift (Node (l, SNil) a (r, _)) = SCons a (Stop r) sift (Node (l, _) a (r, SNil)) = SCons a (Stop l) sift (Node (l, SCons b l') a (r, SCons c r')) | b <= c = SCons a (Play (Node l' b r)) | otherwise = SCons a (Play (Node l c r')) meld :: Heap (Mu Heap :*: SList (Mu Heap)) -> SList (Mu Heap) meld Empty = SNil meld (Node (l, SNil) a (r, _)) = SCons a r meld (Node (l, _) a (r, SNil)) = SCons a l meld (Node (l, SCons b l') a (r, SCons c r')) | b <= c = SCons a (In (Node l' b r)) | otherwise = SCons a (In (Node l c r')) blend :: Heap (Nu SList :*: SList (Nu SList)) -> SList (Nu SList :+: Heap (Nu SList)) blend Empty = SNil blend (Node (l, SNil) a (r, _)) = SCons a (Stop r) blend (Node (l, _) a (r, SNil)) = SCons a (Stop l) blend (Node (l, SCons b l') a (r, SCons c r')) | b <= c = SCons a (Play (Node l' b r)) | otherwise = SCons a (Play (Node l c r')) heapSort :: Mu List -> Nu SList heapSort = unfold deleteMin . downcast . fold heapInsert where deleteMin = para meld heapInsert = apo heapIns mingleSort :: Mu List -> Nu SList mingleSort = fold (apo (blend . fmap (id `split` out))) . downcast . unfold (fold divvy)
cutsea110/aop
src/SortOverMorphism.hs
bsd-3-clause
9,118
3
14
2,056
4,990
2,512
2,478
204
1
-- Problem 14: Longest Collatz Sequence -- -- https://projecteuler.net/problem=14 -- -- The following iterative sequence is defined for the set of positive integers: -- n → n/2 (n is even) -- n → 3n + 1 (n is odd) -- -- Using the rule above and starting with 13, we generate the following sequence: -- 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 -- -- It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. -- Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. -- -- Which starting number, under one million, produces the longest chain? -- -- NOTE: Once the chain starts the terms are allowed to go above one million. collatz n = if n `mod` 2 == 0 then n `div` 2 else 3 * n + 1 collatzCount n = collatzCount' n 0 collatzCount' n c | collatz n == 1 = c | otherwise = collatzCount' (collatz n) (c + 1) maximum' [] = error "maximum of empty list" maximum' (x:xs) = maxTail x xs where maxTail currentMax [] = currentMax maxTail (m, n) (p:ps) | n < (snd p) = maxTail p ps | otherwise = maxTail (m, n) ps main = putStrLn $ show $ maximum $ zip (map collatzCount [1..1000000]) [1..1000000]
moddy3d/euler
p14/p14.hs
mit
1,246
0
12
289
272
145
127
12
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} module Math.NumberTheory.Primes.SequenceTests ( testSuite ) where import Test.Tasty import Test.Tasty.HUnit import Data.Bits import Data.Maybe import Data.Proxy import Numeric.Natural import Math.NumberTheory.Primes import Math.NumberTheory.Primes.Counting (nthPrime, primeCount) import Math.NumberTheory.TestUtils nextPrimeProperty :: (Bits a, Integral a, UniqueFactorisation a) => AnySign a -> Bool nextPrimeProperty (AnySign n) = unPrime (nextPrime n) >= n precPrimeProperty :: (Bits a, Integral a, UniqueFactorisation a) => Positive a -> Bool precPrimeProperty (Positive n) = n <= 2 || unPrime (precPrime n) <= n toEnumProperty :: forall a. (Enum (Prime a), Integral a) => Proxy a -> Int -> Bool toEnumProperty _ n = n <= 0 || unPrime (toEnum n :: Prime a) == fromInteger (unPrime (nthPrime n)) fromEnumProperty :: (Enum (Prime a), Integral a) => Prime a -> Bool fromEnumProperty p = fromEnum p == fromInteger (primeCount (toInteger (unPrime p))) succProperty :: (Enum a, Enum (Prime a), Num a, UniqueFactorisation a) => Prime a -> Bool succProperty p = all (isNothing . isPrime) [unPrime p + 1 .. unPrime (succ p) - 1] predProperty :: (Enum a, Enum (Prime a), Ord a, Num a, UniqueFactorisation a) => Prime a -> Bool predProperty p = unPrime p <= 2 || all (isNothing . isPrime) [unPrime (pred p) + 1 .. unPrime p - 1] enumFrom2To2 :: Assertion enumFrom2To2 = assertEqual "should be equal" [two] [two..two] where two = minBound :: Prime Word enumFrom65500To65600 :: Assertion enumFrom65500To65600 = assertEqual "should be equal" [65519, 65521, 65537, 65539, 65543, 65551, 65557, 65563, 65579, 65581, 65587, 65599] (map unPrime [low..high]) where low = nextPrime (65500 :: Word) high = precPrime (65600 :: Word) enumFrom2To100000 :: Assertion enumFrom2To100000 = assertEqual "should be equal" (takeWhile (<= high) [low..]) [low..high] where low = minBound :: Prime Word high = precPrime (100000 :: Word) enumFromProperty :: (Ord a, Enum (Prime a)) => Prime a -> Prime a -> Bool enumFromProperty p q = [p..q] == takeWhile (<= q) [p..] enumFromToProperty :: (Eq a, Enum a, Enum (Prime a), UniqueFactorisation a) => Prime a -> Prime a -> Bool enumFromToProperty p q = [p..q] == mapMaybe isPrime [unPrime p .. unPrime q] enumFromThenProperty :: (Show a, Ord a, Enum (Prime a)) => Prime a -> Prime a -> Prime a -> Bool enumFromThenProperty p q r = case p `compare` q of LT -> enumFromThenTo p q r == takeWhile (<= r) (enumFromThen p q) EQ -> True GT -> enumFromThenTo p q r == takeWhile (>= r) (enumFromThen p q) enumFromThenToProperty :: (Ord a, Enum a, Enum (Prime a), UniqueFactorisation a, Show a) => Prime a -> Prime a -> Prime a -> Bool enumFromThenToProperty p q r | p == q && q <= r = True | otherwise = [p, q .. r] == mapMaybe isPrime [unPrime p, unPrime q .. unPrime r] testSuite :: TestTree testSuite = testGroup "Sequence" [ testIntegralPropertyNoLarge "nextPrime" nextPrimeProperty , testIntegralPropertyNoLarge "precPrime" precPrimeProperty , testGroup "toEnum" [ testSmallAndQuick "Int" (toEnumProperty (Proxy @Int)) , testSmallAndQuick "Word" (toEnumProperty (Proxy @Word)) , testSmallAndQuick "Integer" (toEnumProperty (Proxy @Integer)) , testSmallAndQuick "Natural" (toEnumProperty (Proxy @Natural)) ] , testGroup "fromEnum" [ testSmallAndQuick "Int" (fromEnumProperty @Int) , testSmallAndQuick "Word" (fromEnumProperty @Word) , testSmallAndQuick "Integer" (fromEnumProperty @Integer) , testSmallAndQuick "Natural" (fromEnumProperty @Natural) ] , testGroup "succ" [ testSmallAndQuick "Int" (succProperty @Int) , testSmallAndQuick "Word" (succProperty @Word) , testSmallAndQuick "Integer" (succProperty @Integer) , testSmallAndQuick "Natural" (succProperty @Natural) ] , testGroup "pred" [ testSmallAndQuick "Int" (predProperty @Int) , testSmallAndQuick "Word" (predProperty @Word) , testSmallAndQuick "Integer" (predProperty @Integer) , testSmallAndQuick "Natural" (predProperty @Natural) ] , testCase "[2..2] == [2]" enumFrom2To2 , testCase "[65500..65600]" enumFrom65500To65600 , testCase "[2..100000]" enumFrom2To100000 , testGroup "enumFrom" [ testSmallAndQuick "Int" (enumFromProperty @Int) , testSmallAndQuick "Word" (enumFromProperty @Word) , testSmallAndQuick "Integer" (enumFromProperty @Integer) , testSmallAndQuick "Natural" (enumFromProperty @Natural) ] , testGroup "enumFromTo" [ testSmallAndQuick "Int" (enumFromToProperty @Int) , testSmallAndQuick "Word" (enumFromToProperty @Word) , testSmallAndQuick "Integer" (enumFromToProperty @Integer) , testSmallAndQuick "Natural" (enumFromToProperty @Natural) ] , testGroup "enumFromThen" [ testSmallAndQuick "Int" (enumFromThenProperty @Int) , testSmallAndQuick "Word" (enumFromThenProperty @Word) , testSmallAndQuick "Integer" (enumFromThenProperty @Integer) , testSmallAndQuick "Natural" (enumFromThenProperty @Natural) ] , testGroup "enumFromThenTo" [ testSmallAndQuick "Int" (enumFromThenToProperty @Int) , testSmallAndQuick "Word" (enumFromThenToProperty @Word) , testSmallAndQuick "Integer" (enumFromThenToProperty @Integer) , testSmallAndQuick "Natural" (enumFromThenToProperty @Natural) ] ]
Bodigrim/arithmoi
test-suite/Math/NumberTheory/Primes/SequenceTests.hs
mit
5,528
0
14
1,047
1,865
961
904
142
3
{- | Module : $Header$ Description : static analysis of CASL specification libraries Copyright : (c) Till Mossakowski, Uni Bremen 2002-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : non-portable(Logic) Static analysis of CASL specification libraries Follows the verification semantics sketched in Chap. IV:6 of the CASL Reference Manual. -} module Static.AnalysisLibrary ( anaLibFileOrGetEnv , anaLibDefn , anaSourceFile , anaLibItem , anaViewDefn , LNS ) where import Logic.Logic import Logic.Grothendieck import Logic.Comorphism import Logic.Coerce import Logic.ExtSign import Logic.Prover import Syntax.AS_Structured import Syntax.Print_AS_Structured import Syntax.Print_AS_Library () import Syntax.AS_Library import Static.GTheory import Static.DevGraph import Static.DgUtils import Static.ComputeTheory import Static.AnalysisStructured import Static.AnalysisArchitecture import Static.ArchDiagram (emptyExtStUnitCtx) import Common.AS_Annotation hiding (isAxiom, isDef) import Common.Consistency import Common.GlobalAnnotations import Common.ConvertGlobalAnnos import Common.AnalyseAnnos import Common.ExtSign import Common.Result import Common.ResultT import Common.LibName import Common.Id import Common.IRI import qualified Common.Unlit as Unlit import Driver.Options import Driver.ReadFn import Driver.ReadLibDefn import Driver.WriteLibDefn import qualified Data.Map as Map import qualified Data.Set as Set import Data.Either (lefts, rights) import Data.List import Data.Maybe import Control.Monad import Control.Monad.Trans import System.Directory import System.FilePath import LF.Twelf2DG import Framework.Analysis import MMT.Hets2mmt (mmtRes) -- a set of library names to check for cyclic imports type LNS = Set.Set LibName {- | parsing and static analysis for files Parameters: logic graph, default logic, file name -} anaSourceFile :: LogicGraph -> HetcatsOpts -> LNS -> LibEnv -> DGraph -> FilePath -> ResultT IO (LibName, LibEnv) anaSourceFile = anaSource Nothing anaSource :: Maybe LibName -- ^ suggested library name -> LogicGraph -> HetcatsOpts -> LNS -> LibEnv -> DGraph -> FilePath -> ResultT IO (LibName, LibEnv) anaSource mln lg opts topLns libenv initDG origName = ResultT $ do let mName = useCatalogURL opts origName fname = fromMaybe mName $ stripPrefix "file://" mName syn = case defSyntax opts of "" -> Nothing s -> Just $ simpleIdToIRI $ mkSimpleId s lgraph = setSyntax syn $ setCurLogic (defLogic opts) lg fname' <- getContentAndFileType opts fname case fname' of Left err -> return $ fail err Right (mr, _, file, inputLit) -> if any (`isSuffixOf` file) [envSuffix, prfSuffix] then return . fail $ "no matching source file for '" ++ fname ++ "' found." else let input = (if unlit opts then Unlit.unlit else id) inputLit libStr = if isAbsolute fname then convertFileToLibStr fname else dropExtensions fname nLn = case mln of Nothing | useLibPos opts && not (checkUri fname) -> Just $ emptyLibName libStr _ -> mln fn2 = keepOrigClifName opts origName file in if runMMT opts then mmtRes fname else if takeExtension file /= ('.' : show TwelfIn) then runResultT $ anaString nLn lgraph opts topLns libenv initDG input fn2 mr else do res <- anaTwelfFile opts file return $ case res of Nothing -> fail $ "failed to analyse file: " ++ file Just (lname, lenv) -> return (lname, Map.union lenv libenv) -- | parsing of input string (content of file) anaString :: Maybe LibName -- ^ suggested library name -> LogicGraph -> HetcatsOpts -> LNS -> LibEnv -> DGraph -> String -> FilePath -> Maybe String -- ^ mime-type of file -> ResultT IO (LibName, LibEnv) anaString mln lgraph opts topLns libenv initDG input file mr = do curDir <- lift getCurrentDirectory -- get full path for parser positions let realFileName = curDir </> file posFileName = case mln of Just gLn | useLibPos opts -> libToFileName gLn _ -> if checkUri file then file else realFileName lift $ putIfVerbose opts 2 $ "Reading file " ++ file libdefns <- readLibDefn lgraph opts mr file posFileName input when (null libdefns) . fail $ "failed to read contents of file: " ++ file foldM (anaStringAux mln lgraph opts topLns initDG mr file posFileName) (error "Static.AnalysisLibrary.anaString", libenv) $ case analysis opts of Skip -> [last libdefns] _ -> libdefns -- | calling static analysis for parsed library-defn anaStringAux :: Maybe LibName -- ^ suggested library name -> LogicGraph -> HetcatsOpts -> LNS -> DGraph -> Maybe String -> FilePath -> FilePath -> (LibName, LibEnv) -> LIB_DEFN -> ResultT IO (LibName, LibEnv) anaStringAux mln lgraph opts topLns initDG mt file posFileName (_, libenv) (Lib_defn pln is' ps ans) = do let pm = fst $ partPrefixes ans expnd i = fromMaybe i $ expandCurie pm i spNs = Set.unions . map (Set.map expnd . getSpecNames) $ concatMap (getSpecDef . item) is' declNs = Set.fromList . map expnd $ concatMap (getDeclSpecNames . item) is' missNames = Set.toList $ spNs Set.\\ declNs unDecls = map (addDownload True) $ filter (isNothing . (`lookupGlobalEnvDG` initDG)) missNames is = unDecls ++ is' spN = convertFileToLibStr file noLibName = getLibId pln == nullIRI nIs = case is of [Annoted (Spec_defn spn gn as qs) rs [] []] | noLibName && null (iriToStringUnsecure spn) -> [Annoted (Spec_defn (simpleIdToIRI $ mkSimpleId spN) gn as qs) rs [] []] _ -> is emptyFilePath = null $ getFilePath pln ln = setMimeType mt $ if emptyFilePath then setFilePath posFileName $ if noLibName then fromMaybe (emptyLibName spN) mln else pln else pln ast = Lib_defn ln nIs ps ans case analysis opts of Skip -> do lift $ putIfVerbose opts 1 $ "Skipping static analysis of library " ++ show ln ga <- liftR $ addGlobalAnnos emptyGlobalAnnos ans lift $ writeLibDefn lgraph ga file opts ast liftR mzero _ -> do let libstring = libToFileName ln unless (isSuffixOf libstring (dropExtension file) || not emptyFilePath) . lift . putIfVerbose opts 1 $ "### file name '" ++ file ++ "' does not match library name '" ++ libstring ++ "'" lift $ putIfVerbose opts 1 $ "Analyzing " ++ (if noLibName then "file " ++ file ++ " as " else "") ++ "library " ++ show ln (lnFinal, ld, ga, lenv) <- anaLibDefn lgraph opts topLns libenv initDG ast file case Map.lookup lnFinal lenv of Nothing -> error $ "anaString: missing library: " ++ show lnFinal Just dg -> lift $ do writeLibDefn lgraph ga file opts ld when (hasEnvOut opts) (writeFileInfo opts lnFinal file ld dg) return (lnFinal, lenv) -- lookup or read a library anaLibFile :: LogicGraph -> HetcatsOpts -> LNS -> LibEnv -> DGraph -> LibName -> ResultT IO (LibName, LibEnv) anaLibFile lgraph opts topLns libenv initDG ln = let lnstr = show ln in case find (== ln) $ Map.keys libenv of Just ln' -> do analyzing opts $ "from " ++ lnstr return (ln', libenv) Nothing -> do putMessageIORes opts 1 $ "Downloading " ++ lnstr ++ " ..." res <- anaLibFileOrGetEnv lgraph (if recurse opts then opts else opts { outtypes = [] , unlit = False }) (Set.insert ln topLns) libenv initDG (Just ln) $ libNameToFile ln putMessageIORes opts 1 $ "... loaded " ++ lnstr return res -- | lookup or read a library anaLibFileOrGetEnv :: LogicGraph -> HetcatsOpts -> LNS -> LibEnv -> DGraph -> Maybe LibName -> FilePath -> ResultT IO (LibName, LibEnv) anaLibFileOrGetEnv lgraph opts topLns libenv initDG mln file = do let envFile = rmSuffix file ++ envSuffix recent_envFile <- lift $ checkRecentEnv opts envFile file if recent_envFile then do mgc <- lift $ readVerbose lgraph opts mln envFile case mgc of Nothing -> do lift $ putIfVerbose opts 1 $ "Deleting " ++ envFile lift $ removeFile envFile anaSource mln lgraph opts topLns libenv initDG file Just (ld@(Lib_defn ln _ _ _), gc) -> do lift $ writeLibDefn lgraph (globalAnnos gc) file opts ld -- get all DGRefs from DGraph mEnv <- foldl ( \ ioLibEnv labOfDG -> let node = snd labOfDG in if isDGRef node then do let ln2 = dgn_libname node p_libEnv <- ioLibEnv if Map.member ln2 p_libEnv then return p_libEnv else fmap snd $ anaLibFile lgraph opts topLns p_libEnv initDG ln2 else ioLibEnv) (return $ Map.insert ln gc libenv) $ labNodesDG gc return (ln, mEnv) else anaSource mln lgraph opts topLns libenv initDG file {- | analyze a LIB_DEFN. Parameters: logic graph, default logic, opts, library env, LIB_DEFN. Call this function as follows: > do Result diags res <- runResultT (anaLibDefn ...) > mapM_ (putStrLn . show) diags -} anaLibDefn :: LogicGraph -> HetcatsOpts -> LNS -> LibEnv -> DGraph -> LIB_DEFN -> FilePath -> ResultT IO (LibName, LIB_DEFN, GlobalAnnos, LibEnv) anaLibDefn lgraph opts topLns libenv dg (Lib_defn ln alibItems pos ans) file = do let libStr = libToFileName ln isDOLlib = elem ':' libStr gannos <- showDiags1 opts $ liftR $ addGlobalAnnos (defPrefixGlobalAnnos $ if isDOLlib then file else libStr) ans allAnnos <- liftR $ mergeGlobalAnnos (globalAnnos dg) gannos (libItems', dg', libenv', _, _) <- foldM (anaLibItemAux opts topLns ln) ([], dg { globalAnnos = allAnnos }, libenv , lgraph, Map.empty) (map item alibItems) let dg1 = computeDGraphTheories libenv' $ markFree libenv' $ markHiding libenv' $ fromMaybe dg' $ maybeResult $ shortcutUnions dg' newLD = Lib_defn ln (zipWith replaceAnnoted (reverse libItems') alibItems) pos ans dg2 = dg1 { optLibDefn = Just newLD } return (ln, newLD, globalAnnos dg2, Map.insert ln dg2 libenv') shortcutUnions :: DGraph -> Result DGraph shortcutUnions dgraph = let spNs = getGlobNodes $ globalEnv dgraph in foldM (\ dg (n, nl) -> let locTh = dgn_theory nl innNs = innDG dg n in case outDG dg n of [(_, t, et@DGLink {dgl_type = lt})] | Set.notMember n spNs && null (getThSens locTh) && isGlobalDef lt && length innNs > 1 && all (\ (_, _, el) -> case dgl_type el of ScopedLink Global DefLink (ConsStatus cs None LeftOpen) | cs == getCons lt -> True _ -> False) innNs && case nodeInfo nl of DGNode DGUnion _ -> True _ -> False -> foldM (\ dg' (s, _, el) -> do newMor <- composeMorphisms (dgl_morphism el) $ dgl_morphism et return $ insLink dg' newMor (dgl_type el) (dgl_origin el) s t) (delNodeDG n dg) innNs _ -> return dg) dgraph $ topsortedNodes dgraph defPrefixGlobalAnnos :: FilePath -> GlobalAnnos defPrefixGlobalAnnos file = emptyGlobalAnnos { prefix_map = Map.singleton "" $ fromMaybe nullIRI $ parseIRIReference $ file ++ "?" } anaLibItemAux :: HetcatsOpts -> LNS -> LibName -> ([LIB_ITEM], DGraph, LibEnv, LogicGraph, ExpOverrides) -> LIB_ITEM -> ResultT IO ([LIB_ITEM], DGraph, LibEnv, LogicGraph, ExpOverrides) anaLibItemAux opts topLns ln q@(libItems', dg1, libenv1, lg, eo) libItem = let currLog = currentLogic lg newOpts = if elem currLog ["DMU", "Framework"] then opts { defLogic = currLog } else opts in ResultT $ do res2@(Result diags2 res) <- runResultT $ anaLibItem lg newOpts topLns ln libenv1 dg1 eo libItem runResultT $ showDiags1 opts (liftR res2) let mRes = case res of Just (libItem', dg1', libenv1', newLG, eo') -> Just (libItem' : libItems', dg1', libenv1', newLG, eo') Nothing -> Just q if outputToStdout opts then if hasErrors diags2 then fail "Stopped due to errors" else runResultT $ liftR $ Result [] mRes else runResultT $ liftR $ Result diags2 mRes putMessageIORes :: HetcatsOpts -> Int -> String -> ResultT IO () putMessageIORes opts i msg = if outputToStdout opts then lift $ putIfVerbose opts i msg else liftR $ message () msg analyzing :: HetcatsOpts -> String -> ResultT IO () analyzing opts = putMessageIORes opts 1 . ("Analyzing " ++) alreadyDefined :: String -> String alreadyDefined str = "Name " ++ str ++ " already defined" -- | analyze a GENERICITY anaGenericity :: LogicGraph -> LibName -> DGraph -> HetcatsOpts -> ExpOverrides -> NodeName -> GENERICITY -> Result (GENERICITY, GenSig, DGraph) anaGenericity lg ln dg opts eo name gen@(Genericity (Params psps) (Imported isps) pos) = let ms = currentBaseTheory dg in adjustPos pos $ case psps of [] -> do -- no parameter ... unless (null isps) $ plain_error () "Parameterless specifications must not have imports" pos l <- lookupCurrentLogic "GENERICITY" lg return (gen, GenSig (EmptyNode l) [] $ maybe (EmptyNode l) JustNode ms, dg) _ -> do l <- lookupCurrentLogic "IMPORTS" lg let baseNode = maybe (EmptyNode l) JustNode ms (imps', nsigI, dg') <- case isps of [] -> return ([], baseNode, dg) _ -> do (is', _, nsig', dgI) <- anaUnion False lg ln dg baseNode (extName "Imports" name) opts eo isps $ getRange isps return (is', JustNode nsig', dgI) (ps', nsigPs, ns, dg'') <- anaUnion False lg ln dg' nsigI (extName "Parameters" name) opts eo psps $ getRange psps return (Genericity (Params ps') (Imported imps') pos, GenSig nsigI nsigPs $ JustNode ns, dg'') expCurieT :: GlobalAnnos -> ExpOverrides -> IRI -> ResultT IO IRI expCurieT ga eo = liftR . expCurieR ga eo -- | analyse a LIB_ITEM anaLibItem :: LogicGraph -> HetcatsOpts -> LNS -> LibName -> LibEnv -> DGraph -> ExpOverrides -> LIB_ITEM -> ResultT IO (LIB_ITEM, DGraph, LibEnv, LogicGraph, ExpOverrides) anaLibItem lg opts topLns currLn libenv dg eo itm = case itm of Spec_defn spn2 gen asp pos -> do let spn' = if null (iriToStringUnsecure spn2) then simpleIdToIRI $ mkSimpleId "Spec" else spn2 spn <- expCurieT (globalAnnos dg) eo spn' let spstr = iriToStringUnsecure spn nName = makeName spn analyzing opts $ "spec " ++ spstr (gen', gsig@(GenSig _ _args allparams), dg') <- liftR $ anaGenericity lg currLn dg opts eo nName gen (sanno1, impliesA) <- liftR $ getSpecAnnos pos asp when impliesA $ liftR $ plain_error () "unexpected initial %implies in spec-defn" pos (sp', body, dg'') <- liftR (anaSpecTop sanno1 True lg currLn dg' allparams nName opts eo (item asp) pos) let libItem' = Spec_defn spn gen' (replaceAnnoted sp' asp) pos genv = globalEnv dg if Map.member spn genv then liftR $ plain_error (libItem', dg'', libenv, lg, eo) (alreadyDefined spstr) pos else -- let (_n, dg''') = addSpecNodeRT dg'' (UnitSig args body) $ show spn return ( libItem' , dg'' { globalEnv = Map.insert spn (SpecEntry $ ExtGenSig gsig body) genv } , libenv, lg, eo) View_defn vn' gen vt gsis pos -> do vn <- expCurieT (globalAnnos dg) eo vn' analyzing opts $ "view " ++ iriToStringUnsecure vn liftR $ anaViewDefn lg currLn libenv dg opts eo vn gen vt gsis pos Align_defn an' arities atype acorresps _ pos -> do an <- expCurieT (globalAnnos dg) eo an' analyzing opts $ "alignment " ++ iriToStringUnsecure an anaAlignDefn lg currLn libenv dg opts eo an arities atype acorresps pos Arch_spec_defn asn' asp pos -> do asn <- expCurieT (globalAnnos dg) eo asn' let asstr = iriToStringUnsecure asn analyzing opts $ "arch spec " ++ asstr (_, _, diag, archSig, dg', asp') <- liftR $ anaArchSpec lg currLn dg opts eo emptyExtStUnitCtx Nothing $ item asp let asd' = Arch_spec_defn asn (replaceAnnoted asp' asp) pos genv = globalEnv dg' if Map.member asn genv then liftR $ plain_error (asd', dg', libenv, lg, eo) (alreadyDefined asstr) pos else do let aName = show asn dg'' = updateNodeNameRT dg' (refSource $ getPointerFromRef archSig) True aName dg3 = dg'' { archSpecDiags = Map.insert aName diag $ archSpecDiags dg''} return (asd', dg3 { globalEnv = Map.insert asn (ArchOrRefEntry True archSig) genv } , libenv, lg, eo) Unit_spec_defn usn' usp pos -> do usn <- expCurieT (globalAnnos dg) eo usn' let usstr = iriToStringUnsecure usn analyzing opts $ "unit spec " ++ usstr l <- lookupCurrentLogic "Unit_spec_defn" lg (rSig, dg', usp') <- liftR $ anaUnitSpec lg currLn dg opts eo (EmptyNode l) Nothing usp unitSig <- liftR $ getUnitSigFromRef rSig let usd' = Unit_spec_defn usn usp' pos genv = globalEnv dg' if Map.member usn genv then liftR $ plain_error (itm, dg', libenv, lg, eo) (alreadyDefined usstr) pos else return (usd', dg' { globalEnv = Map.insert usn (UnitEntry unitSig) genv }, libenv, lg, eo) Ref_spec_defn rn' rsp pos -> do rn <- expCurieT (globalAnnos dg) eo rn' let rnstr = iriToStringUnsecure rn l <- lookupCurrentLogic "Ref_spec_defn" lg (_, _, _, rsig, dg', rsp') <- liftR $ anaRefSpec lg currLn dg opts eo (EmptyNode l) rn emptyExtStUnitCtx Nothing rsp analyzing opts $ "ref spec " ++ rnstr let rsd' = Ref_spec_defn rn rsp' pos genv = globalEnv dg' if Map.member rn genv then liftR $ plain_error (itm, dg', libenv, lg, eo) (alreadyDefined rnstr) pos else return ( rsd', dg' { globalEnv = Map.insert rn (ArchOrRefEntry False rsig) genv } , libenv, lg, eo) Logic_decl logN pos -> do putMessageIORes opts 1 . show $ prettyLG lg itm (mth, newLg) <- liftR $ adjustPos pos $ anaSublogic opts logN currLn dg libenv lg case mth of Nothing -> return (itm, dg { currentBaseTheory = Nothing }, libenv, newLg, eo) Just (s, (libName, refDG, (_, lbl))) -> do -- store th-lbl in newDG let dg2 = if libName /= currLn then let (s2, (genv, newDG)) = refExtsigAndInsert libenv libName refDG (globalEnv dg, dg) (getName $ dgn_name lbl) s in newDG { globalEnv = genv , currentBaseTheory = Just $ extGenBody s2 } else dg { currentBaseTheory = Just $ extGenBody s } return (itm, dg2, libenv, newLg, eo) Download_items ln items pos -> if Set.member ln topLns then liftR $ mkError "illegal cyclic library import" $ Set.map getLibId topLns else do (ln', libenv') <- anaLibFile lg opts topLns libenv (cpIndexMaps dg emptyDG { globalAnnos = emptyGlobalAnnos { prefix_map = prefix_map $ globalAnnos dg }}) ln unless (ln == ln') $ liftR $ warning () (shows ln " does not match internal name " ++ shows ln' "") pos case Map.lookup ln' libenv' of Nothing -> error $ "Internal error: did not find library " ++ show ln' ++ " available: " ++ show (Map.keys libenv') Just dg' -> do let dg0 = cpIndexMaps dg' dg fn = libToFileName ln' currFn = libToFileName currLn (realItems, errs, origItems) = case items of ItemMaps rawIms -> let (ims, warns) = foldr (\ im@(ItemNameMap i mi) (is, ws) -> if Just i == mi then (ItemNameMap i Nothing : is , warning () (show i ++ " item no renamed") (getRange mi) : ws) else (im : is, ws)) ([], []) rawIms expIms = map (expandCurieItemNameMap fn currFn) ims leftExpIms = lefts expIms in if not $ null leftExpIms then ([], leftExpIms, itemNameMapsToIRIs ims) else (rights expIms, warns, itemNameMapsToIRIs ims) UniqueItem i -> case Map.keys $ globalEnv dg' of [j] -> case expCurie (globalAnnos dg) eo i of Nothing -> ([], [prefixErrorIRI i], [i]) Just expI -> case expCurie (globalAnnos dg) eo j of Nothing -> ([], [prefixErrorIRI j], [i, j]) Just expJ -> ([ItemNameMap expJ (Just expI)], [], [i, j]) _ -> ( [] , [ mkError "non-unique name within imported library" ln'], []) additionalEo = Map.fromList $ map (\ o -> (o, fn)) origItems eo' = Map.unionWith (\ _ p2 -> p2) eo additionalEo mapM_ liftR errs dg1 <- liftR $ anaItemNamesOrMaps libenv' ln' dg' dg0 realItems return (itm, dg1, libenv', lg, eo') Newlogic_defn ld _ -> ResultT $ do dg' <- anaLogicDef ld dg return $ Result [] $ Just (itm, dg', libenv, lg, eo) Newcomorphism_defn com _ -> ResultT $ do dg' <- anaComorphismDef com dg return $ Result [] $ Just (itm, dg', libenv, lg, eo) _ -> return (itm, dg, libenv, lg, eo) symbolsOf :: LogicGraph -> G_sign -> G_sign -> [CORRESPONDENCE] -> Result (Set.Set (G_symbol, G_symbol)) symbolsOf lg gs1@(G_sign l1 (ExtSign sig1 sys1) _) gs2@(G_sign l2 (ExtSign sig2 sys2) _) corresps = case corresps of [] -> return Set.empty c : corresps' -> case c of Default_correspondence -> symbolsOf lg gs1 gs2 corresps' -- TO DO Correspondence_block _ _ cs -> do sPs1 <- symbolsOf lg gs1 gs2 cs sPs2 <- symbolsOf lg gs1 gs2 corresps' return $ Set.union sPs1 sPs2 Single_correspondence _ (G_symb_items_list lid1 sis1) (G_symb_items_list lid2 sis2) _ _ -> do ss1 <- coerceSymbItemsList lid1 l1 "symbolsOf1" sis1 rs1 <- stat_symb_items l1 sig1 ss1 ss2 <- coerceSymbItemsList lid2 l2 "symbolsOf1" sis2 rs2 <- stat_symb_items l2 sig2 ss2 p <- case (rs1, rs2) of ([r1], [r2]) -> -- trace (show r1 ++ " " ++ show (Set.toList sys1)) $ case ( filter (\ sy -> matches l1 sy r1) $ Set.toList sys1 , filter (\ sy -> matches l2 sy r2) $ Set.toList sys2) of ([s1], [s2]) -> return (G_symbol l1 s1, G_symbol l2 s2) (ll1, ll2) -> {- trace ("sys1:" ++ (show $ Set.toList sys1 )) $ -} error $ "non-unique symbol match: " ++ show ll1 ++ "\n" ++ show ll2 _ -> mkError "non-unique raw symbols" c ps <- symbolsOf lg gs1 gs2 corresps' return $ Set.insert p ps -- | analyse genericity and view type and construct gmorphism anaViewDefn :: LogicGraph -> LibName -> LibEnv -> DGraph -> HetcatsOpts -> ExpOverrides -> IRI -> GENERICITY -> VIEW_TYPE -> [G_mapping] -> Range -> Result (LIB_ITEM, DGraph, LibEnv, LogicGraph, ExpOverrides) anaViewDefn lg ln libenv dg opts eo vn gen vt gsis pos = do let vName = makeName vn (gen', gsig@(GenSig _ _ allparams), dg') <- anaGenericity lg ln dg opts eo vName gen (vt', (src@(NodeSig nodeS gsigmaS) , tar@(NodeSig nodeT gsigmaT@(G_sign lidT _ _))), dg'') <- anaViewType lg ln dg' allparams opts eo vName vt let genv = globalEnv dg'' if Map.member vn genv then plain_error (View_defn vn gen' vt' gsis pos, dg'', libenv, lg, eo) (alreadyDefined $ iriToStringUnsecure vn) pos else do let (tsis, hsis) = partitionGmaps gsis (gsigmaS', tmor) <- if null tsis then do (gsigmaS', imor) <- gSigCoerce lg gsigmaS (Logic lidT) tmor <- gEmbedComorphism imor gsigmaS return (gsigmaS', tmor) else do mor <- anaRenaming lg allparams gsigmaS opts (Renaming tsis pos) let gsigmaS'' = cod mor (gsigmaS', imor) <- gSigCoerce lg gsigmaS'' (Logic lidT) tmor <- gEmbedComorphism imor gsigmaS'' fmor <- comp mor tmor return (gsigmaS', fmor) emor <- fmap gEmbed $ anaGmaps lg opts pos gsigmaS' gsigmaT hsis gmor <- comp tmor emor let vsig = ExtViewSig src gmor $ ExtGenSig gsig tar voidView = nodeS == nodeT && isInclusion gmor when voidView $ warning () ("identity mapping of source to same target for view: " ++ iriToStringUnsecure vn) pos return (View_defn vn gen' vt' gsis pos, (if voidView then dg'' else insLink dg'' gmor globalThm (DGLinkView vn $ Fitted gsis) nodeS nodeT) -- 'LeftOpen' for conserv correct? { globalEnv = Map.insert vn (ViewOrStructEntry True vsig) genv } , libenv, lg, eo) {- | analyze a VIEW_TYPE The first three arguments give the global context The AnyLogic is the current logic The NodeSig is the signature of the parameter of the view flag, whether just the structure shall be analysed -} anaViewType :: LogicGraph -> LibName -> DGraph -> MaybeNode -> HetcatsOpts -> ExpOverrides -> NodeName -> VIEW_TYPE -> Result (VIEW_TYPE, (NodeSig, NodeSig), DGraph) anaViewType lg ln dg parSig opts eo name (View_type aspSrc aspTar pos) = do -- trace "called anaViewType" $ do l <- lookupCurrentLogic "VIEW_TYPE" lg let spS = item aspSrc spT = item aspTar (spSrc', srcNsig, dg') <- anaSpec False lg ln dg (EmptyNode l) (extName "Source" name) opts eo spS $ getRange spS (spTar', tarNsig, dg'') <- anaSpec True lg ln dg' parSig (extName "Target" name) opts eo spT $ getRange spT return (View_type (replaceAnnoted spSrc' aspSrc) (replaceAnnoted spTar' aspTar) pos, (srcNsig, tarNsig), dg'') anaAlignDefn :: LogicGraph -> LibName -> LibEnv -> DGraph -> HetcatsOpts -> ExpOverrides -> IRI -> Maybe ALIGN_ARITIES -> VIEW_TYPE -> [CORRESPONDENCE] -> Range -> ResultT IO (LIB_ITEM, DGraph, LibEnv, LogicGraph, ExpOverrides) anaAlignDefn lg ln libenv dg opts eo an arities atype acorresps pos = do l <- lookupCurrentLogic "Align_defn" lg (atype', (src, tar), dg') <- liftR $ anaViewType lg ln dg (EmptyNode l) opts eo (makeName an) atype let gsig1 = getSig src gsig2 = getSig tar case (gsig1, gsig2) of (G_sign lid1 gsign1 ind1, G_sign lid2 gsign2 _) -> if Logic lid1 == Logic lid2 then do -- arities TO DO pairsSet <- liftR $ symbolsOf lg gsig1 gsig2 acorresps let leftList = map fst $ Set.toList pairsSet rightList = map snd $ Set.toList pairsSet isTotal gsig sList = Set.fromList sList == symsOfGsign gsig isInjective sList = length sList == length (nub sList) checkArity sList1 sList2 gsig arity = case arity of AA_InjectiveAndTotal -> isTotal gsig sList1 && isInjective sList2 AA_Injective -> isInjective sList2 AA_Total -> isTotal gsig sList1 _ -> True aCheck = case arities of Nothing -> True Just (Align_arities aleft aright) -> checkArity leftList rightList gsig1 aleft && checkArity rightList leftList gsig2 aright if not aCheck then liftR $ mkError "Arities do not check" arities else do -- correspondence let isFunctional = isTotal gsig1 leftList && isInjective leftList allEquiv = all (\ c -> case c of Single_correspondence _ _ _ (Just Equivalent) _ -> True _ -> False ) acorresps newDg <- if isFunctional && allEquiv then do let eMap = foldl (\ f (gs1, gs2) -> case gs1 of G_symbol l1 s1 -> case gs2 of G_symbol l2 s2 -> let s1' = symbol_to_raw lid1 $ coerceSymbol l1 lid1 s1 s2' = symbol_to_raw lid1 $ coerceSymbol l2 lid1 s2 in Map.insert s1' s2' f ) Map.empty $ Set.toList pairsSet gsign2' <- liftR $ coerceSign lid2 lid1 "coerce sign" gsign2 phi <- liftR $ induced_from_to_morphism lid1 eMap gsign1 gsign2' let gmor = GMorphism (mkIdComorphism lid1 (top_sublogic lid1)) gsign1 ind1 phi startMorId asign = AlignMor src gmor tar dg'' = dg' { globalEnv = Map.insert an (AlignEntry asign) $ globalEnv dg' } dg3 = insLink dg'' gmor globalThm (DGLinkAlign an) (getNode src) (getNode tar) return dg3 else if allEquiv then do (pairedSymSet, eMap1, eMap2) <- liftR $ foldM (\ (s, f1, f2) (gs1, gs2) -> case gs1 of G_symbol l1 s1 -> case gs2 of G_symbol l2 s2 -> do let s1' = coerceSymbol l1 lid1 s1 s2' = coerceSymbol l2 lid1 s2 csym <- pair_symbols lid1 s1' s2' let s' = Set.insert csym s f1' = Map.insert (symbol_to_raw lid1 csym) (symbol_to_raw lid1 s1') f1 f2' = Map.insert (symbol_to_raw lid1 csym) (symbol_to_raw lid1 s2') f2 return (s', f1', f2') ) (Set.empty, Map.empty, Map.empty) $ Set.toList pairsSet sigma0 <- liftR $ foldM (add_symb_to_sign lid1) (empty_signature lid1) $ Set.toList pairedSymSet let eSigma0 = makeExtSign lid1 sigma0 pi1 <- liftR $ induced_from_to_morphism lid1 eMap1 eSigma0 gsign1 gsign2' <- liftR $ coerceSign lid2 lid1 "coerce sign" gsign2 pi2 <- liftR $ induced_from_to_morphism lid1 eMap2 eSigma0 gsign2' let gsig = G_sign lid1 eSigma0 startSigId -- check index!!!!! (sspan, dg'') = insGSig dg' (makeName an) DGAlignment gsig gmor1 = GMorphism (mkIdComorphism lid1 (top_sublogic lid1)) eSigma0 ind1 pi1 startMorId gmor2 = GMorphism (mkIdComorphism lid1 (top_sublogic lid1)) eSigma0 ind1 pi2 startMorId dg3 = insLink dg'' gmor1 globalDef (DGLinkAlign an) (getNode sspan) (getNode src) dg4 = insLink dg3 gmor2 globalDef (DGLinkAlign an) (getNode sspan) (getNode tar) asign = AlignSpan sspan gmor1 src gmor2 tar return dg4 { globalEnv = Map.insert an (AlignEntry asign) $ globalEnv dg4 } else do (gt1, gt2, gt, gmor1, gmor2) <- liftR $ generateWAlign gsig1 gsig2 acorresps let n1 = getNewNodeDG dg' labN1 = newInfoNodeLab (makeName an {abbrevFragment = abbrevFragment an ++ "_source"}) (newNodeInfo DGAlignment) gt1 dg1 = insLNodeDG (n1, labN1) dg' n2 = getNewNodeDG dg1 labN2 = newInfoNodeLab (makeName an {abbrevFragment = abbrevFragment an ++ "_target"}) (newNodeInfo DGAlignment) gt2 dg2 = insLNodeDG (n2, labN2) dg1 n = getNewNodeDG dg2 labN = newInfoNodeLab (makeName an {abbrevFragment = abbrevFragment an ++ "_bridge"}) (newNodeInfo DGAlignment) gt dg3 = insLNodeDG (n, labN) dg2 (_, dg4) = insLEdgeDG (n2, n, globDefLink gmor2 $ DGLinkAlign an) dg3 (_, dg5) = insLEdgeDG (n1, n, globDefLink gmor1 $ DGLinkAlign an) dg4 incl1 <- liftR $ ginclusion lg (signOf gt1) gsig1 incl2 <- liftR $ ginclusion lg (signOf gt2) gsig2 let (_, dg6) = insLEdgeDG (n1, getNode src, globDefLink incl1 $ DGLinkAlign an) dg5 (_, dg7) = insLEdgeDG (n2, getNode tar, globDefLink incl2 $ DGLinkAlign an) dg6 -- store the alignment in the global env asign = WAlign (NodeSig n1 $ signOf gt1) incl1 gmor1 (NodeSig n2 $ signOf gt2) incl2 gmor2 src tar (NodeSig n $ signOf gt) return dg7 {globalEnv = Map.insert an (AlignEntry asign) $ globalEnv dg7} -- error "nyi" let itm = Align_defn an arities atype' acorresps SingleDomain pos anstr = iriToStringUnsecure an if Map.member an $ globalEnv dg then liftR $ plain_error (itm, dg, libenv, lg, eo) (alreadyDefined anstr) pos else return (itm, newDg, libenv, lg, eo) -- error "Analysis of alignments nyi" else liftR $ fatal_error ("Alignments only work between ontologies in the same logic\n" ++ show (prettyLG lg atype)) pos generateWAlign :: G_sign -> G_sign -> [CORRESPONDENCE] -> Result (G_theory, G_theory, G_theory, GMorphism, GMorphism) generateWAlign (G_sign lid1 (ExtSign ssig _) _) (G_sign lid2 (ExtSign tsig _) _) corrs = do tsig' <- coercePlainSign lid2 lid1 "coercePlainSign" tsig let (eSymbs, cSymbs) = foldl (\ (l1, l2) c -> case c of Single_correspondence _ s1 s2 (Just Equivalent) _ -> ((s1, s2) : l1, l2) Single_correspondence _ s1 s2 (Just rref) _ -> (l1, (s1, s2, refToRel rref) : l2) _ -> error "only single correspondences") ([], []) corrs -- 1. initialize sig1 = empty_signature lid1 sig2 = empty_signature lid1 sig = empty_signature lid1 phi1 = Map.empty phi2 = Map.empty {- for each equivalence in eSymbs put s1 in gth1, sigma_1(s1) = s1_s2 put s2 in gth2, sigma_2(s2) = s1_s2 put s1_s2 in gth -} addEquiv (s1, s2, s, p1, p2) (G_symb_items_list lids1 l1, G_symb_items_list lids2 l2) = do l1' <- coerceSymbItemsList lids1 lid1 "coerceSymbItemsList" l1 l2' <- coerceSymbItemsList lids2 lid1 "coerceSymbItemsList" l2 (ctsig, cssig1, cssig2, cmap1, cmap2) <- equiv2cospan lid1 ssig tsig' l1' l2' s1' <- signature_union lid1 s1 cssig1 s2' <- signature_union lid1 s2 cssig2 s' <- signature_union lid1 s ctsig let p1' = Map.union cmap1 p1 p2' = Map.union cmap2 p2 return (s1', s2', s', p1', p2') (sig1', sig2', sig', phi1', phi2') <- foldM addEquiv (sig1, sig2, sig, phi1, phi2) eSymbs {- for each other correspondence in cSymbs put s1 in gth1, sigma_1(s1) = s1 if undefined put s2 in gth2, sigma_2(s2) = s2 if undefined gtI = corresp2th s1 s2 rref make the union of gtI with gth, possibly renaming symbols in gtI according to sigma_1,2 -} let addCorresp (s1, s2, s, sens, p1, p2) (G_symb_items_list lids1 l1, G_symb_items_list lids2 l2, rrel) = do l1' <- coerceSymbItemsList lids1 lid1 "coerceSymbItemsList" l1 l2' <- coerceSymbItemsList lids2 lid1 "coerceSymbItemsList" l2 (sigb, senb, s1', s2', eMap1, eMap2) <- corresp2th lid1 ssig tsig' l1' l2' p1 p2 rrel s1'' <- signature_union lid1 s1 s1' s2'' <- signature_union lid1 s2 s2' s' <- signature_union lid1 s sigb let p1' = Map.union eMap1 p1 p2' = Map.union eMap2 p2 return (s1'', s2'', s', sens ++ senb, p1', p2') (sig1'', sig2'', sig'', sens'', sMap1, sMap2) <- foldM addCorresp (sig1', sig2', sig', [], phi1', phi2') cSymbs -- make G_ results let gth1 = noSensGTheory lid1 (mkExtSign sig1'') startSigId gth2 = noSensGTheory lid1 (mkExtSign sig2'') startSigId gth = G_theory lid1 Nothing (mkExtSign sig'') startSigId (toThSens sens'') startThId rsMap1 = Map.mapKeys (symbol_to_raw lid1) $ Map.map (symbol_to_raw lid1) sMap1 rsMap2 = Map.mapKeys (symbol_to_raw lid1) $ Map.map (symbol_to_raw lid1) sMap2 mor1 <- induced_from_to_morphism lid1 rsMap1 (mkExtSign sig1'') (mkExtSign sig'') let gmor1 = gEmbed2 (signOf gth1) $ mkG_morphism lid1 mor1 mor2 <- {- trace "mor2:" $ trace ("source: " ++ (show sig2'')) $ trace ("target: " ++ (show sig'')) $ -} induced_from_to_morphism lid1 rsMap2 (mkExtSign sig2'') (mkExtSign sig'') let gmor2 = gEmbed2 (signOf gth2) $ mkG_morphism lid1 mor2 return (gth1, gth2, gth, gmor1, gmor2) -- the first DGraph dg' is that of the imported library anaItemNamesOrMaps :: LibEnv -> LibName -> DGraph -> DGraph -> [ItemNameMap] -> Result DGraph anaItemNamesOrMaps libenv' ln refDG dg items = do (genv1, dg1) <- foldM (anaItemNameOrMap libenv' ln refDG) (globalEnv dg, dg) items gannos'' <- mergeGlobalAnnos (globalAnnos refDG) $ globalAnnos dg return dg1 { globalAnnos = gannos'' , globalEnv = genv1 } anaItemNameOrMap :: LibEnv -> LibName -> DGraph -> (GlobalEnv, DGraph) -> ItemNameMap -> Result (GlobalEnv, DGraph) anaItemNameOrMap libenv ln refDG res (ItemNameMap old m) = anaItemNameOrMap1 libenv ln refDG res (old, fromMaybe old m) -- | Auxiliary function for not yet implemented features anaErr :: String -> a anaErr f = error $ "*** Analysis of " ++ f ++ " is not yet implemented!" anaItemNameOrMap1 :: LibEnv -> LibName -> DGraph -> (GlobalEnv, DGraph) -> (IRI, IRI) -> Result (GlobalEnv, DGraph) anaItemNameOrMap1 libenv ln refDG (genv, dg) (old, new) = do entry <- maybe (notFoundError "item" old) return $ lookupGlobalEnvDG old refDG maybeToResult (iriPos new) (iriToStringUnsecure new ++ " already used") $ case Map.lookup new genv of Nothing -> Just () Just _ -> Nothing case entry of SpecEntry extsig -> return $ snd $ refExtsigAndInsert libenv ln refDG (genv, dg) new extsig ViewOrStructEntry b vsig -> let (dg1, vsig1) = refViewsig libenv ln refDG dg (makeName new) vsig genv1 = Map.insert new (ViewOrStructEntry b vsig1) genv in return (genv1, dg1) UnitEntry _usig -> anaErr "unit spec download" AlignEntry _asig -> anaErr "alignment download" ArchOrRefEntry b _rsig -> anaErr $ (if b then "arch" else "ref") ++ " spec download" refNodesig :: LibEnv -> LibName -> DGraph -> DGraph -> (NodeName, NodeSig) -> (DGraph, NodeSig) refNodesig libenv refln refDG dg (name, NodeSig refn sigma@(G_sign lid sig ind)) = let (ln, _, (n, lbl)) = lookupRefNode libenv refln refDG refn refInfo = newRefInfo ln n new = newInfoNodeLab name refInfo $ noSensGTheory lid sig ind nodeCont = new { globalTheory = globalTheory lbl } node = getNewNodeDG dg in case lookupInAllRefNodesDG refInfo dg of Just existNode -> (dg, NodeSig existNode sigma) Nothing -> ( insNodeDG (node, nodeCont) dg , NodeSig node sigma) refNodesigs :: LibEnv -> LibName -> DGraph -> DGraph -> [(NodeName, NodeSig)] -> (DGraph, [NodeSig]) refNodesigs libenv ln = mapAccumR . refNodesig libenv ln refExtsigAndInsert :: LibEnv -> LibName -> DGraph -> (GlobalEnv, DGraph) -> IRI -> ExtGenSig -> (ExtGenSig, (GlobalEnv, DGraph)) refExtsigAndInsert libenv ln refDG (genv, dg) new extsig = let (dg1, extsig1) = refExtsig libenv ln refDG dg (makeName new) extsig genv1 = Map.insert new (SpecEntry extsig1) genv in (extsig1, (genv1, dg1)) refExtsig :: LibEnv -> LibName -> DGraph -> DGraph -> NodeName -> ExtGenSig -> (DGraph, ExtGenSig) refExtsig libenv ln refDG dg name (ExtGenSig (GenSig imps params gsigmaP) body) = let pName = extName "Parameters" name (dg1, imps1) = case imps of EmptyNode _ -> (dg, imps) JustNode ns -> let (dg0, nns) = refNodesig libenv ln refDG dg (extName "Imports" name, ns) in (dg0, JustNode nns) (dg2, params1) = refNodesigs libenv ln refDG dg1 $ snd $ foldr (\ p (n, l) -> let nn = inc n in (nn, (nn, p) : l)) (pName, []) params (dg3, gsigmaP1) = case gsigmaP of EmptyNode _ -> (dg, gsigmaP) JustNode ns -> let (dg0, nns) = refNodesig libenv ln refDG dg2 (pName, ns) in (dg0, JustNode nns) (dg4, body1) = refNodesig libenv ln refDG dg3 (name, body) in (dg4, ExtGenSig (GenSig imps1 params1 gsigmaP1) body1) refViewsig :: LibEnv -> LibName -> DGraph -> DGraph -> NodeName -> ExtViewSig -> (DGraph, ExtViewSig) refViewsig libenv ln refDG dg name (ExtViewSig src mor extsig) = let (dg1, src1) = refNodesig libenv ln refDG dg (extName "Source" name, src) (dg2, extsig1) = refExtsig libenv ln refDG dg1 (extName "Target" name) extsig in (dg2, ExtViewSig src1 mor extsig1) -- BEGIN CURIE expansion expandCurieItemNameMap :: FilePath -> FilePath -> ItemNameMap -> Either (Result ()) ItemNameMap expandCurieItemNameMap fn newFn (ItemNameMap i1 mi2) = case expandCurieByPath fn i1 of Just i -> case mi2 of Nothing -> Right $ ItemNameMap i mi2 Just j -> case expandCurieByPath newFn j of Nothing -> Left $ prefixErrorIRI j mj -> Right $ ItemNameMap i mj Nothing -> Left $ prefixErrorIRI i1 itemNameMapsToIRIs :: [ItemNameMap] -> [IRI] itemNameMapsToIRIs = concatMap (\ (ItemNameMap i mi) -> [i | isNothing mi]) -- END CURIE expansion
keithodulaigh/Hets
Static/AnalysisLibrary.hs
gpl-2.0
44,434
0
40
14,745
13,391
6,766
6,625
881
26
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QDynamicPropertyChangeEvent.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:31 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Core.QDynamicPropertyChangeEvent ( QqDynamicPropertyChangeEvent(..) ,QqDynamicPropertyChangeEvent_nf(..) ,propertyName ,qDynamicPropertyChangeEvent_delete ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core class QqDynamicPropertyChangeEvent x1 where qDynamicPropertyChangeEvent :: x1 -> IO (QDynamicPropertyChangeEvent ()) instance QqDynamicPropertyChangeEvent ((String)) where qDynamicPropertyChangeEvent (x1) = withQDynamicPropertyChangeEventResult $ withCWString x1 $ \cstr_x1 -> qtc_QDynamicPropertyChangeEvent cstr_x1 foreign import ccall "qtc_QDynamicPropertyChangeEvent" qtc_QDynamicPropertyChangeEvent :: CWString -> IO (Ptr (TQDynamicPropertyChangeEvent ())) instance QqDynamicPropertyChangeEvent ((QDynamicPropertyChangeEvent t1)) where qDynamicPropertyChangeEvent (x1) = withQDynamicPropertyChangeEventResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QDynamicPropertyChangeEvent1 cobj_x1 foreign import ccall "qtc_QDynamicPropertyChangeEvent1" qtc_QDynamicPropertyChangeEvent1 :: Ptr (TQDynamicPropertyChangeEvent t1) -> IO (Ptr (TQDynamicPropertyChangeEvent ())) class QqDynamicPropertyChangeEvent_nf x1 where qDynamicPropertyChangeEvent_nf :: x1 -> IO (QDynamicPropertyChangeEvent ()) instance QqDynamicPropertyChangeEvent_nf ((String)) where qDynamicPropertyChangeEvent_nf (x1) = withObjectRefResult $ withCWString x1 $ \cstr_x1 -> qtc_QDynamicPropertyChangeEvent cstr_x1 instance QqDynamicPropertyChangeEvent_nf ((QDynamicPropertyChangeEvent t1)) where qDynamicPropertyChangeEvent_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QDynamicPropertyChangeEvent1 cobj_x1 propertyName :: QDynamicPropertyChangeEvent a -> (()) -> IO (String) propertyName x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDynamicPropertyChangeEvent_propertyName cobj_x0 foreign import ccall "qtc_QDynamicPropertyChangeEvent_propertyName" qtc_QDynamicPropertyChangeEvent_propertyName :: Ptr (TQDynamicPropertyChangeEvent a) -> IO (Ptr (TQString ())) qDynamicPropertyChangeEvent_delete :: QDynamicPropertyChangeEvent a -> IO () qDynamicPropertyChangeEvent_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QDynamicPropertyChangeEvent_delete cobj_x0 foreign import ccall "qtc_QDynamicPropertyChangeEvent_delete" qtc_QDynamicPropertyChangeEvent_delete :: Ptr (TQDynamicPropertyChangeEvent a) -> IO ()
keera-studios/hsQt
Qtc/Core/QDynamicPropertyChangeEvent.hs
bsd-2-clause
2,976
0
12
367
560
296
264
50
1
module Control.Distributed.Process.Extras.Internal.Containers where class (Eq k, Functor m) => Map m k | m -> k where empty :: m a member :: k -> m a -> Bool insert :: k -> a -> m a -> m a delete :: k -> m a -> m a lookup :: k -> m a -> a filter :: (a -> Bool) -> m a -> m a filterWithKey :: (k -> a -> Bool) -> m a -> m a
haskell-distributed/distributed-process-extras
src/Control/Distributed/Process/Extras/Internal/Containers.hs
bsd-3-clause
382
0
10
140
180
93
87
-1
-1
-- |This module provides a type and a type class for expressing -- alignment. For concrete uses, see the Table and ProgressBar -- modules. module Graphics.Vty.Widgets.Alignment ( Alignment(..) , Alignable(..) ) where -- |Column alignment values. data Alignment = AlignCenter | AlignLeft | AlignRight deriving (Show) -- |The class of types whose values or contents can be aligned. class Alignable a where align :: a -> Alignment -> a
KommuSoft/vty-ui
src/Graphics/Vty/Widgets/Alignment.hs
bsd-3-clause
469
0
8
105
71
45
26
7
0
f :: a -> a -> Bool f x y = let z :: b z = y in True
bitemyapp/tandoori
input/rigid.hs
bsd-3-clause
79
0
8
46
44
21
23
4
1
{-# LANGUAGE OverloadedStrings #-} module WebParsing.GraphVisualization (makeGraph) where import Data.Char import qualified Data.Text as T import qualified Data.Text.Lazy as L import Data.Graph.Inductive.Graph import Data.GraphViz import Data.GraphViz.Attributes.Complete import Data.GraphViz.Printing import Data.GraphViz.Commands import Data.List import Database.CourseQueries import Network.HTTP import System.Process import Text.HTML.TagSoup import Text.HTML.TagSoup.Match import WebParsing.GraphConversion import WebParsing.ArtSciParser -- | simple GraphViz parameters for a deparment graph: labels nodes. graphParams :: GraphvizParams n T.Text el () T.Text graphParams = nonClusteredParams { globalAttributes = [GraphAttrs [Splines Ortho, Ratio FillRatio, Size (GSize 8 (Just 4.8) False)], NodeAttrs [ Shape BoxShape, FontSize 80, Style [SItem Bold []]], EdgeAttrs [Style [SItem Bold []]]], fmtNode = fn } where fn (_,l) = [toLabel (T.unpack l)] --takes in a String representation of a dot graph and creates an SVG file. graphVizProcess :: PrintDotRepr dg n => FilePath -> dg n -> IO FilePath graphVizProcess name graph = runGraphvizCommand Dot graph Canon name -- | outputs an SVG file with name filename containing a graph of nodes in courses makeGraph' :: [String] -> String -> IO FilePath makeGraph' codes filename = let courses = Prelude.map T.pack codes in (toGraph' courses) >>= (\g -> graphVizProcess filename (graphToDot graphParams g)) -- | constructs a graph of all courses starting with code. makeGraph :: String -> IO ProcessHandle makeGraph code = do getDeptCourses code >>= toGraph >>= (\g -> graphVizProcess code (graphToDot graphParams g)) >>= (\_ -> runCommand $ "unflatten -f -l50 -c 4 -o out.dot " ++ code) >>= (\_ -> runCommand $ "dot -Tsvg -o ./graphs/" ++ code ++".svg" ++ " out.dot") junkCodes :: [String] junkCodes = ["CMS"] main :: IO () main = do rsp <- simpleHTTP (getRequest fasCalendarURL) body <- getResponseBody rsp let depts = filter (isPrefixOf "crs_") (getDeptList $ parseTags body) let codes = map (drop 4 . takeWhile (/= '.') . map toUpper) depts\\ junkCodes mapM_ makeGraph codes mapM_ (\x -> (runCommand $ "rm " ++ map toUpper x)) codes
Ian-Stewart-Binks/courseography
hs/WebParsing/GraphVisualization.hs
gpl-3.0
2,755
0
16
887
678
360
318
54
1
-- | BigTable benchmark implemented using Hamlet. -- {-# LANGUAGE QuasiQuotes #-} module Main where import Criterion.Main import Text.Hamlet import Text.Hamlet.Monad import Numeric (showInt) import Data.Text (Text) import qualified Data.Text as T import Data.Maybe (fromJust) main = defaultMain [ bench "bigTable" $ nf bigTable bigTableData ] where rows :: Int rows = 1000 bigTableData :: [[Int]] bigTableData = replicate rows [1..10] {-# NOINLINE bigTableData #-} bigTable rows = fromJust $ hamletToText undefined [$hamlet| %table $forall rows row %tr $forall row cell %td $showInt'.cell$ |] where showInt' i = Encoded $ T.pack $ showInt i ""
jgm/blaze-html
benchmarks/bigtable/hamlet.hs
bsd-3-clause
724
2
12
175
206
112
94
18
1
module D3 where data Tree a = Leaf a | Branch (Tree a) (Tree a) fringe :: (Tree a) -> [a] fringe (Leaf x) = [x] fringe (Branch left right) = (fringe left) ++ (fringe right) class Same a where isSame :: a -> a -> Bool isNotSame :: a -> a -> Bool instance Same Int where isSame a b = a == b isNotSame a b = a /= b sumSquares ((x : xs)) = (sq x) + (sumSquares xs) where sq x = x ^ pow pow = 2 sumSquares [] = 0
kmate/HaRe
old/testing/renaming/D3_AstOut.hs
bsd-3-clause
469
0
8
157
234
123
111
17
1
module T4930 where foo :: Int -> Int foo n = (if n < 5 then foo n else n+2) `seq` n+5
olsner/ghc
testsuite/tests/simplCore/should_compile/T4930.hs
bsd-3-clause
95
0
9
31
53
30
23
4
2
{-# LANGUAGE OverloadedStrings #-} module Handler.Publications where import Import import Text.Blaze.Html5 ((!)) import qualified Text.Blaze.Html5 as H (span, a) import qualified Text.Blaze.Html5.Attributes as A (href, class_) import Text.Parsec.Text () import Text.Parsec (parse) import Text.BibTeX.Parse (splitAuthorList, skippingLeadingSpace, file) import Text.BibTeX.Entry (T(Cons), entryType, identifier, fields) import Data.Maybe (fromMaybe) import Data.List (intersperse, intercalate) import Text.Highlighting.Kate (highlightAs, formatHtmlBlock, defaultFormatOpts) import Handler.Types (Composer) import qualified Data.Text as T (unpack) publicationsComposer :: Composer publicationsComposer contentRaw = let res = parse (skippingLeadingSpace file) "publication handler" $ T.unpack contentRaw entries = case res of Left _ -> error "failed to parse" Right parsedEntries -> parsedEntries in mapM_ publicationWidget entries publicationWidget :: T -> Widget publicationWidget ent = let typ = entryType ent ide = filter (/= ':') $ identifier ent entLookup = (`bibtexLookup` ent) auths = splitAuthorList $ entLookup "author" title = toHtml $ entLookup "title" authors = toHtml $ intersperse ", " $ map formatAuthor auths venue = formatVenue ent maybeRepository = lookup "repository" $ fields ent maybeCopyright = lookup "copyright" $ fields ent abstract = entLookup "abstract" fieldsNoAbstract = filter (\(x, _) -> not $ x `elem` ["abstract", "repository", "copyright"]) $ fields ent bibtex = toHtml $ formatHtmlBlock defaultFormatOpts $ highlightAs "bibtex" $ formatEntry ent{fields = fieldsNoAbstract} in $(widgetFile "publication") formatEntry :: T -> String formatEntry (Cons bibType bibId items) = "@" ++ bibType ++ "{" ++ bibId ++ ",\n" ++ (concat $ intersperse ",\n" $ map formatItem items) ++ "\n}\n" formatItem :: (String, String) -> String formatItem (name, value) = " " ++ name ++ " = " ++ enclose value where enclose = if name `elem` ["year", "month"] then id else \val -> "\"" ++ val ++ "\"" knownAuthors :: [(String, Html -> Html)] knownAuthors = [ ("Dudebout, Nicolas", H.span ! A.class_ "me") , ("Shamma, Jeff S.", H.a ! A.href "http://www.prism.gatech.edu/~jshamma3/" ! A.class_ "external") ] knownEntryTypes :: [(String, T -> String)] knownEntryTypes = [ ("MastersThesis", \entry -> "Master's Thesis, " ++ "school" `bibtexLookup` entry) , ("PhDThesis", \entry -> "PhD Thesis, " ++ "school" `bibtexLookup` entry) , ("InProceedings", ("booktitle" `bibtexLookup`)) , ("Misc", miscFormatting) ] where miscFormatting entry = case "howpublished" `bibtexLookup` entry of "PhD Proposal" -> "PhD Proposal, " ++ "school" `bibtexLookup` entry _ -> "unknown_howpublished" formatAuthor :: String -> Html formatAuthor auth = fromMaybe id (lookup auth knownAuthors) $ toHtml $ flipAndShortenName auth formatVenue :: T -> Html formatVenue entry = toHtml $ intercalate ", " [venue entry, "year" `bibtexLookup` entry] where type_ = entryType entry venue = fromMaybe (const "unknown_type") $ lookup type_ knownEntryTypes bibtexLookup :: String -> T -> String bibtexLookup fieldName entry = fromMaybe ("unknown_" ++ fieldName) $ lookup fieldName $ fields entry flipAndShortenName :: String -> String flipAndShortenName name = let (lastName, firstAndMiddleNameDirty) = break (','==) name firstAndMiddleName = dropWhile (`elem` [',', ' ']) firstAndMiddleNameDirty (first, middle) = break (' '==) firstAndMiddleName firstNameAbbrev = abbreviate first middleNameAbbrev = abbreviate $ dropWhile (`elem` [' ']) middle names = filter (/="") [firstNameAbbrev, middleNameAbbrev, lastName] in intercalate " " names abbreviate :: String -> String abbreviate "" = "" abbreviate (n:_) = n:"."
dudebout/dudeboutdotcom
Handler/Publications.hs
isc
4,386
0
14
1,207
1,208
672
536
-1
-1
module Bot.Component.Command ( simpleCommand , simpleCommandT , emptyCommand , command , commandT , helpForCommand ) where import Bot.Component import Bot.IO import Control.Monad.Trans import Control.Monad.Trans.Identity -- | A convenience function that wraps `command` for commands that don't need to -- take arguments. simpleCommand :: String -> Bot () -> Bot Component simpleCommand trigger action = command trigger (const action) -- | Create a command `BotComponent` for a command that requires arguments. command :: String -> ([String] -> Bot ()) -> Bot Component command trigger action = mkComponentT $ commandT trigger actionT where actionT :: [String] -> IdentityT Bot () actionT = lift . action -- | Creates a `BotComponent` that runs its action everytime it's evaluated. emptyCommand :: Bot () -> Bot Component emptyCommand = simpleCommand "" -- | Similar to `simpleCommand` but allows the action to be wrapped inside of a -- monad transformer. simpleCommandT :: (BotMonad b) => String -> b () -> String -> b () simpleCommandT trigger action = commandT trigger (const action) -- | The most general command constructor possible, the result of the action -- method used here lives inside of a monad transformer. commandT :: (BotMonad b) -- | The `String` that will trigger this command => String -- | The action that should be run when trigger is seen -> ([String] -> b ()) -- | The resulting -> String -> b () commandT trigger action = onPrivMsgT (commandAction . words) where commandAction (first:args) | first == trigger = action args | otherwise = return () commandAction _ | trigger == "" = action [] | otherwise = return () -- | Creates a help message with a help string for the case where the canonical -- name is the same as the helpForCommand :: String -> [String] -> HelpMessage helpForCommand name helpString = HelpMessage { canonicalName = name , helpAliases = [name, '!':name] , helpString = helpString }
numberten/zhenya_bot
Bot/Component/Command.hs
mit
2,329
0
11
719
470
250
220
42
2
module Pretty ( ppexpr, pptype ) where import Check import Syntax import Text.PrettyPrint class Pretty p where ppr :: Int -> p -> Doc pp :: p -> Doc pp = ppr 0 parensIf :: Bool -> Doc -> Doc parensIf True = parens parensIf False = id instance Pretty Expr where ppr p ex = case ex of Var x -> text x Lit (LInt a) -> text (show a) Lit (LBool b) -> text (show b) Add a b -> parensIf (p>0) $ char '+' <+> (ppr (p+1) a) <+> (ppr (p+1) b) App a b -> (parensIf (p>0) (ppr (p+1) a)) <+> (ppr p b) Lam x t a -> parensIf (p > 0) $ char '\\' <+> parens (text x <+> char ':' <+> ppr p t) <+> text "->" <+> ppr (p+1) a instance Pretty Type where ppr _ TInt = text "Int" ppr _ TBool = text "Bool" ppr p (TArr a b) = (parensIf (isArrow a) (ppr p a)) <+> text "->" <+> ppr p b where isArrow TArr{} = True isArrow _ = False instance Show TypeError where show (Mismatch a b) = "Expecting " ++ (pptype b) ++ " but got " ++ (pptype a) show (NotFunction a) = "Tried to apply to non-function type: " ++ (pptype a) show (NotInScope a) = "Variable " ++ a ++ " is not in scope" ppexpr :: Expr -> String ppexpr = render . ppr 0 pptype :: Type -> String pptype = render . ppr 0
JoshuaGross/STILC
Pretty.hs
mit
1,319
0
16
422
622
309
313
45
1
import Data.Char inc x = x + 1 sumList :: [Int] -> Int sumList [] = 0 sumList (x:xs) = x + sumList xs fact :: Int -> Int fact 0 = 1 fact n = n * fact (n - 1) first :: [a] -> a first (x:_) = x member y [] = False member y (x:xs) = y == x || member y xs makeName :: String -> String -> String makeName family first = concat [first, " ", family] nakovit :: String -> String nakovit = makeName "Nakov" map2 :: (a -> b) -> [a] -> [b] map2 _ [] = [] map2 f (x:xs) = f x : map2 f xs confIt names = map (\name -> name ++ "Conf") names trimLeft = dropWhile isSpace trim = reverse . trimLeft . reverse . trimLeft trimLines = map trim
RadoRado/Talks
SoftUniConf2015/examples.hs
mit
637
0
8
156
349
182
167
23
1
module Rebase.Control.Monad.Trans.Writer ( module Control.Monad.Trans.Writer ) where import Control.Monad.Trans.Writer
nikita-volkov/rebase
library/Rebase/Control/Monad/Trans/Writer.hs
mit
122
0
5
12
26
19
7
4
0
#!/usr/bin/env stack -- stack --install-ghc --resolver lts-7.7 runghc import qualified Data.Set as Set {- # Sets -} data State = Alabama | Alaska | Arizona | Arkansas | California | Colorado | Connecticut | Delaware | Florida | Georgia | Hawaii | Idaho | Illinois | Indiana | Iowa | Kansas | Kentucky | Louisiana | Maine | Maryland | Massachusetts | Michigan | Minnesota | Mississippi | Missouri | Montana | Nebraska | Nevada | NewHampshire | NewJersey | NewMexico | NewYork | NorthCarolina | NorthDakota | Ohio | Oklahoma | Oregon | Pennsylvania | RhodeIsland | SouthCarolina | SouthDakota | Tennessee | Texas | Utah | Vermont | Virginia | Washington | WestVirginia | Wisconsin | Wyoming deriving (Show, Eq, Enum) foo = [ ([(001,003)], NewHampshire) ,([(004,007)], Maine) ,([(008,009)], Vermont) ,([(010,034)], Massachusetts) ,([(035,039)], RhodeIsland) ,([(040,049)], Connecticut) ,([(050,134)], NewYork) ,([(135,158)], NewJersey) ,([(159,211)], Pennsylvania) ,([(212,220)], Maryland) ,([(221,222)], Delaware) ,([(223,231)], Virginia) ,([(232,232)], NorthCarolina) ,([(232,236)], WestVirginia) ,([(247,251)], SouthCarolina) ,([(252,260)], Georgia) ,([(261,267)], Florida) ,([(268,302)], Ohio) ,([(303,317)], Indiana) ,([(318,361)], Illinois) ,([(362,386)], Michigan) ,([(387,399)], Wisconsin) ,([(400,407)], Kentucky) ,([(408,415)], Tennessee) ,([(416,424)], Alabama) ,([(425,428)], Mississippi) ,([(429,432)], Arkansas) ,([(433,439)], Louisiana) ,([(440,448)], Oklahoma) ,([(449,467)], Texas) ,([(468,477)], Minnesota) ,([(478,485)], Iowa) ,([(486,500)], Missouri) ,([(501,502)], NorthDakota) ,([(503,504)], SouthDakota) ,([(505,508)], Nebraska) ,([(509,515)], Kansas) ,([(516,517)], Montana) ,([(518,519)], Idaho) ,([(520,520)], Wyoming) ,([(521,524)], Colorado) ,([(525,525),(585,585)], NewMexico) ,([(526,527)], Arizona) ,([(528,529)], Utah) ,([(530,530),(680,680)], Nevada) ,([(531,539)], Washington) ,([(540,544)], Oregon) ,([(545,573)], California) ,([(574,574)], Alaska) ,([(575,576)], Hawaii) ] bar = [ (NewHampshire, [(1, 3)]) , (Maine, [(4, 7)]) , (Vermont, [(8, 9)]) , (Massachusetts, [(10, 34)]) , (RhodeIsland, [(35, 39)]) , (Connecticut, [(40, 49)]) , (NewYork, [(50, 134)]) , (NewJersey, [(135, 158)]) , (Pennsylvania, [(159, 211)]) , (Maryland, [(212, 220)]) , (Delaware, [(221, 222)]) , (Virginia, [(223, 231)]) , (NorthCarolina, [(232, 232)]) , (WestVirginia, [(232, 236)]) , (SouthCarolina, [(247, 251)]) , (Georgia, [(252, 260)]) , (Florida, [(261, 267)]) , (Ohio, [(268, 302)]) , (Indiana, [(303, 317)]) , (Illinois, [(318, 361)]) , (Michigan, [(362, 386)]) , (Wisconsin, [(387, 399)]) , (Kentucky, [(400, 407)]) , (Tennessee, [(408, 415)]) , (Alabama, [(416, 424)]) , (Mississippi, [(425, 428)]) , (Arkansas, [(429, 432)]) , (Louisiana, [(433, 439)]) , (Oklahoma, [(440, 448)]) , (Texas, [(449, 467)]) , (Minnesota, [(468, 477)]) , (Iowa, [(478, 485)]) , (Missouri, [(486, 500)]) , (NorthDakota, [(501, 502)]) , (SouthDakota, [(503, 504)]) , (Nebraska, [(505, 508)]) , (Kansas, [(509, 515)]) , (Montana, [(516, 517)]) , (Idaho, [(518, 519)]) , (Wyoming, [(520, 520)]) , (Colorado, [(521, 524)]) , (NewMexico, [(525, 525), (585, 585)]) , (Arizona, [(526, 527)]) , (Utah, [(528, 529)]) , (Nevada, [(530, 530), (680, 680)]) , (Washington, [(531, 539)]) , (Oregon, [(540, 544)]) , (California, [(545, 573)]) , (Alaska, [(574, 574)]) , (Hawaii, [(575, 576)]) ] allStates :: Set.Set State allStates = Set.fromAscList [toEnum 0 ..]
lehins/tutorials
Haskell/containers/States.hs
mit
3,765
49
9
759
2,155
1,364
791
157
1
----------------------------------------------------------------------------- -- -- Module : Language.PureScript.TypeChecker.Kinds -- Copyright : (c) Phil Freeman 2013 -- License : MIT -- -- Maintainer : Phil Freeman <[email protected]> -- Stability : experimental -- Portability : -- -- | -- This module implements the kind checker -- ----------------------------------------------------------------------------- {-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-} module Language.PureScript.TypeChecker.Kinds ( kindOf, kindsOf, kindsOfAll ) where import Language.PureScript.Types import Language.PureScript.Kinds import Language.PureScript.Names import Language.PureScript.TypeChecker.Monad import Language.PureScript.Pretty import Language.PureScript.Environment import Language.PureScript.Errors import Control.Monad.State import Control.Monad.Error import Control.Monad.Unify import Control.Applicative import qualified Data.Map as M import qualified Data.HashMap.Strict as H import Data.Monoid ((<>)) instance Partial Kind where unknown = KUnknown isUnknown (KUnknown u) = Just u isUnknown _ = Nothing unknowns = everythingOnKinds (++) go where go (KUnknown u) = [u] go _ = [] ($?) sub = everywhereOnKinds go where go t@(KUnknown u) = case H.lookup u (runSubstitution sub) of Nothing -> t Just t' -> t' go other = other instance Unifiable Check Kind where KUnknown u1 =?= KUnknown u2 | u1 == u2 = return () KUnknown u =?= k = u =:= k k =?= KUnknown u = u =:= k Star =?= Star = return () Bang =?= Bang = return () Row k1 =?= Row k2 = k1 =?= k2 FunKind k1 k2 =?= FunKind k3 k4 = do k1 =?= k3 k2 =?= k4 k1 =?= k2 = UnifyT . lift . throwError . strMsg $ "Cannot unify " ++ prettyPrintKind k1 ++ " with " ++ prettyPrintKind k2 ++ "." -- | -- Infer the kind of a single type -- kindOf :: ModuleName -> Type -> Check Kind kindOf _ ty = rethrow (mkErrorStack "Error checking kind" (Just (TypeError ty)) <>) $ fmap tidyUp . liftUnify $ starIfUnknown <$> infer ty where tidyUp (k, sub) = sub $? k -- | -- Infer the kind of a type constructor with a collection of arguments and a collection of associated data constructors -- kindsOf :: Bool -> ModuleName -> ProperName -> [String] -> [Type] -> Check Kind kindsOf isData moduleName name args ts = fmap tidyUp . liftUnify $ do tyCon <- fresh kargs <- replicateM (length args) fresh let dict = (name, tyCon) : zipWith (\arg kind -> (arg, kind)) (map ProperName args) kargs bindLocalTypeVariables moduleName dict $ solveTypes isData ts kargs tyCon where tidyUp (k, sub) = starIfUnknown $ sub $? k -- | -- Simultaneously infer the kinds of several mutually recursive type constructors -- kindsOfAll :: ModuleName -> [(ProperName, [String], Type)] -> [(ProperName, [String], [Type])] -> Check ([Kind], [Kind]) kindsOfAll moduleName syns tys = fmap tidyUp . liftUnify $ do synVars <- replicateM (length syns) fresh let dict = zipWith (\(name, _, _) var -> (name, var)) syns synVars bindLocalTypeVariables moduleName dict $ do tyCons <- replicateM (length tys) fresh let dict' = zipWith (\(name, _, _) tyCon -> (name, tyCon)) tys tyCons bindLocalTypeVariables moduleName dict' $ do data_ks <- zipWithM (\tyCon (_, args, ts) -> do kargs <- replicateM (length args) fresh let argDict = zip (map ProperName args) kargs bindLocalTypeVariables moduleName argDict $ solveTypes True ts kargs tyCon) tyCons tys syn_ks <- zipWithM (\synVar (_, args, ty) -> do kargs <- replicateM (length args) fresh let argDict = zip (map ProperName args) kargs bindLocalTypeVariables moduleName argDict $ solveTypes False [ty] kargs synVar) synVars syns return (syn_ks, data_ks) where tidyUp ((ks1, ks2), sub) = (map (starIfUnknown . (sub $?)) ks1, map (starIfUnknown . (sub $?)) ks2) -- | -- Solve the set of kind constraints associated with the data constructors for a type constructor -- solveTypes :: Bool -> [Type] -> [Kind] -> Kind -> UnifyT Kind (Check) Kind solveTypes isData ts kargs tyCon = do ks <- mapM infer ts when isData $ do tyCon =?= foldr FunKind Star kargs forM_ ks $ \k -> k =?= Star when (not isData) $ do tyCon =?= foldr FunKind (head ks) kargs return tyCon -- | -- Default all unknown kinds to the Star kind of types -- starIfUnknown :: Kind -> Kind starIfUnknown (KUnknown _) = Star starIfUnknown (Row k) = Row (starIfUnknown k) starIfUnknown (FunKind k1 k2) = FunKind (starIfUnknown k1) (starIfUnknown k2) starIfUnknown k = k -- | -- Infer a kind for a type -- infer :: Type -> UnifyT Kind Check Kind infer ty = rethrow (mkErrorStack "Error inferring type of value" (Just (TypeError ty)) <>) $ infer' ty infer' :: Type -> UnifyT Kind Check Kind infer' (TypeVar v) = do Just moduleName <- checkCurrentModule <$> get UnifyT . lift $ lookupTypeVariable moduleName (Qualified Nothing (ProperName v)) infer' c@(TypeConstructor v) = do env <- liftCheck getEnv case M.lookup v (types env) of Nothing -> UnifyT . lift . throwError $ mkErrorStack "Unknown type constructor" (Just (TypeError c)) Just (kind, _) -> return kind infer' (TypeApp t1 t2) = do k0 <- fresh k1 <- infer t1 k2 <- infer t2 k1 =?= FunKind k2 k0 return k0 infer' (ForAll ident ty _) = do k1 <- fresh Just moduleName <- checkCurrentModule <$> get k2 <- bindLocalTypeVariables moduleName [(ProperName ident, k1)] $ infer ty k2 =?= Star return Star infer' REmpty = do k <- fresh return $ Row k infer' (RCons _ ty row) = do k1 <- infer ty k2 <- infer row k2 =?= Row k1 return $ Row k1 infer' (ConstrainedType deps ty) = do forM_ deps $ \(className, tys) -> do _ <- infer $ foldl TypeApp (TypeConstructor className) tys return () k <- infer ty k =?= Star return Star infer' _ = error "Invalid argument to infer"
bergmark/purescript
src/Language/PureScript/TypeChecker/Kinds.hs
mit
6,027
0
25
1,300
2,074
1,046
1,028
129
2
-- | Command line tool to process the DSL files. module Main where import AST import Control.Applicative import Control.Monad import Control.Monad (unless) import qualified Data.Set as Set import Errors import Interp import qualified Parser import qualified Renderer import SampleScript import System.Console.ANSI import System.Console.ArgParser import System.Exit import System.IO import System.Process import qualified Text.Parsec as Parsec import qualified Utils -- | Encapsulation of all command line options and switches. data CLIArgs = CLIArgs { infile :: String, outfile :: String, silent :: Bool, latexOff :: Bool } deriving Show -- | `cliParser` parses command-line options for the program. cliParser :: ParserSpec CLIArgs cliParser = CLIArgs `parsedBy` optPos "-" "infile" `Descr` "Source to input file. By default this is stdin." `andBy` optPos "script.tex" "outfile" `Descr` "Destination to output file. By default script.tex" `andBy` boolFlag "silent" `Descr` "Turn off the verbosity" `andBy` boolFlag "latex-off" `Descr` "Turns off automatic call to latexmk" -- | Parse the command line input and run the logic of the program. main :: IO () main = withParseResult cliParser runner -- | Run the logic of the program. runner :: CLIArgs -> IO () runner s = do unless (silent s) (putStrLn "==== Reading in file...") c <- if infile s == "-" then getContents else readFile $ infile s unless (silent s) (putStrLn "==== Parsing...") parsed <- either ((>> exitFailure) . prntErrorC "Parsing Error") return (Parsec.parse Parser.cueSheet (infile s) c) unless (silent s) (putStrLn "==== Compiling...") parsed' <- either ((>> exitFailure) . prntErrorC "Compiling Error") return (transpile parsed) _ <- either ((>> exitFailure) . prntErrorC "Compiling Error") return (checkUnkownCharacters theScript parsed') evaled <- either ((>> exitFailure) . prntErrorC "Processing Error") return (eval theScript parsed') unless (silent s) (putStrLn "==== Rendering...") Renderer.main (outfile s) evaled setSGR [SetConsoleIntensity BoldIntensity, SetColor Foreground Vivid Green] unless (silent s) $ putStrLn $ "Ouput left in " ++ outfile s setSGR [SetConsoleIntensity BoldIntensity, SetColor Foreground Vivid Yellow] when (not (latexOff s) && not (silent s)) $ putStrLn "Generating PDF...This may hang; if it does, interrupt and run again." setSGR [Reset] unless (latexOff s) (createProcess ((proc "latexmk" ["-silent", "-pdf", "-shell-escape", outfile s]){ std_out = Inherit, std_err = Inherit }) *> return ()) return () -- | Print to stderr. prntError :: String -> IO () prntError = hPutStrLn stderr -- | Pretty print (with colors) an error message to stderr. prntErrorC :: (PrettyError a) => String -> a -> IO () prntErrorC hdr bdy = do hSetSGR stderr [SetConsoleIntensity BoldIntensity, SetColor Foreground Vivid Red] prntError (hdr ++ ":") hSetSGR stderr [Reset] prntError $ unlines $ map (" " ++) $ lines $ (prettyError bdy)
rwoll-hmc/project
src/Main.hs
mit
3,229
0
16
738
866
452
414
59
2
module Proteome.Grep.Process where import Control.Monad.Catch (MonadCatch) import qualified Data.Text as Text import Data.Text (isInfixOf) import Path (Abs, File, Path, parseAbsDir, parseAbsFile, toFilePath) import Path.IO (isLocationOccupied) import Ribosome.Menu.Data.MenuItem (MenuItem) import qualified Streamly.Data.Fold as Fold import qualified Streamly.Internal.Unicode.Stream as Streamly import qualified Streamly.Prelude as Streamly import Streamly.Prelude (IsStream, MonadAsync) import qualified Streamly.System.Process as Process import Proteome.Data.GrepError (GrepError) import qualified Proteome.Data.GrepError as GrepError (GrepError (..)) import Proteome.Data.GrepOutputLine (GrepOutputLine) import Proteome.Grep.Parse (parseGrepOutput) import Proteome.System.Path (findExe) patternPlaceholder :: Text patternPlaceholder = "{pattern}" pathPlaceholder :: Text pathPlaceholder = "{path}" replaceOrAppend :: Text -> Text -> [Text] -> [Text] replaceOrAppend placeholder target segments | any (placeholder `isInfixOf`) segments = Text.replace placeholder target <$> segments replaceOrAppend _ target segments = segments <> [target] parseAbsExe :: MonadDeepError e GrepError m => Text -> m (Path Abs File) parseAbsExe exe = hoistEitherAs (GrepError.NoSuchExecutable exe) $ parseAbsFile (toString exe) grepCmdline :: Text -> Text -> Text -> Text -> [Text] -> MonadIO m => MonadDeepError e GrepError m => m (Text, [Text]) grepCmdline cmdline patt cwd destination opt = do when (Text.null exe) $ throwHoist GrepError.Empty absExe <- if absolute exe then parseAbsExe exe else findExe exe destPath <- hoistEitherAs destError $ parseAbsDir (toString (absDestination destination)) unlessM (isLocationOccupied destPath) $ throwHoist destError return (toText (toFilePath absExe), withDir destPath) where absDestination d = if d == "." then cwd else if absolute d then d else cwd <> "/" <> d absolute a = Text.take 1 a == "/" argSegments = opt <> Text.words (Text.strip args) (exe, args) = Text.breakOn " " (Text.strip cmdline) withDir dir = replaceOrAppend pathPlaceholder (toText (toFilePath dir)) withPattern withPattern = replaceOrAppend patternPlaceholder patt argSegments destError = GrepError.NoSuchDestination destination processOutput :: IsStream t => MonadAsync m => MonadCatch m => Text -> [Text] -> t m Word8 processOutput exe args = Process.toBytes (toString exe) (toString <$> args) processLines :: IsStream t => MonadAsync m => MonadCatch m => Text -> [Text] -> t m Text processLines exe args = Streamly.lines (toText <$> Fold.toList) $ Streamly.decodeUtf8 $ processOutput exe args grepMenuItems :: MonadRibo m => IsStream t => MonadAsync m => MonadCatch m => Text -> Text -> [Text] -> t m (MenuItem GrepOutputLine) grepMenuItems cwd exe args = Streamly.mapMaybeM (parseGrepOutput cwd) $ processLines exe args
tek/proteome
packages/proteome/lib/Proteome/Grep/Process.hs
mit
3,025
0
14
567
952
503
449
-1
-1
{-# LANGUAGE RecordWildCards #-} import Data.Foldable (for_) import Test.Hspec (Spec, describe, it, shouldBe) import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith) import Data.List (intercalate) import Proverb (recite) main :: IO () main = hspecWith defaultConfig {configFastFail = True} specs specs :: Spec specs = describe "recite" $ for_ cases test where test Case{..} = it description assertion where assertion = recite input `shouldBe` expected data Case = Case { description :: String , input :: [String] , expected :: String } joinLines :: [String] -> String joinLines = intercalate "\n" cases :: [Case] cases = [ Case { description = "zero pieces" , input = [] , expected = "" } , Case { description = "one piece" , input = ["nail"] , expected = "And all for the want of a nail." } , Case { description = "two pieces" , input = ["nail", "shoe"] , expected = joinLines [ "For want of a nail the shoe was lost." , "And all for the want of a nail." ] } , Case { description = "three pieces" , input = ["nail", "shoe", "horse"] , expected = joinLines [ "For want of a nail the shoe was lost." , "For want of a shoe the horse was lost." , "And all for the want of a nail." ] } , Case { description = "full proverb" , input = [ "nail" , "shoe" , "horse" , "rider" , "message" , "battle" , "kingdom" ] , expected = joinLines [ "For want of a nail the shoe was lost." , "For want of a shoe the horse was lost." , "For want of a horse the rider was lost." , "For want of a rider the message was lost." , "For want of a message the battle was lost." , "For want of a battle the kingdom was lost." , "And all for the want of a nail." ] } , Case { description = "four pieces modernized" , input = ["pin", "gun", "soldier", "battle"] , expected = joinLines [ "For want of a pin the gun was lost." , "For want of a gun the soldier was lost." , "For want of a soldier the battle was lost." , "And all for the want of a pin." ] } ] -- 7571de6f6e531aa674a254616a17074b7f755bcd
exercism/xhaskell
exercises/practice/proverb/test/Tests.hs
mit
3,186
0
9
1,583
468
286
182
58
1
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.SVGAnimatedNumber (setBaseVal, getBaseVal, getAnimVal, SVGAnimatedNumber(..), gTypeSVGAnimatedNumber) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedNumber.baseVal Mozilla SVGAnimatedNumber.baseVal documentation> setBaseVal :: (MonadDOM m) => SVGAnimatedNumber -> Float -> m () setBaseVal self val = liftDOM (self ^. jss "baseVal" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedNumber.baseVal Mozilla SVGAnimatedNumber.baseVal documentation> getBaseVal :: (MonadDOM m) => SVGAnimatedNumber -> m Float getBaseVal self = liftDOM (realToFrac <$> ((self ^. js "baseVal") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedNumber.animVal Mozilla SVGAnimatedNumber.animVal documentation> getAnimVal :: (MonadDOM m) => SVGAnimatedNumber -> m Float getAnimVal self = liftDOM (realToFrac <$> ((self ^. js "animVal") >>= valToNumber))
ghcjs/jsaddle-dom
src/JSDOM/Generated/SVGAnimatedNumber.hs
mit
1,886
0
12
218
474
292
182
27
1
{-# LANGUAGE Arrows #-} module Sample1 where import Control.Arrow import Control.CCA.Types import Prelude hiding (init, exp) import qualified Data.List.Stream as S --this was taken from Paul Liu from his CCA paper --http://code.haskell.org/CCA/test/ --I am tring to rewrite these without arrows (normal FRP) --two different timings exits -- http://www.thev.net/PaulLiu/download/jfp092011.pdf -- http://www.thev.net/PaulLiu/download/icfp066-liu.pdf --exp is a recursive definition for 2^n by using integrals --which is a retarted way to do this --exp with Arrow sr = 44100 :: Int dt = 1 / (fromIntegral sr) --dt =1 exp :: ArrowInit a => a () Double exp = proc () -> do rec let e = 1 + i i <- integral -< e returnA -< e integral :: ArrowInit a => a Double Double integral = proc e -> do rec let i' = i + e * dt i <- init 0 -< i' --init is id when t !=0 returnA -< i --exp with nonArrow --a is a value, b is a state --running at same as fast tuple arrow nth_FRP :: Int -> (b, (b -> (a,b))) -> a nth_FRP n (i,f) = aux n i where aux n i = x `seq` if n == 0 then x else aux (n-1) i' where (x, i') = f i --my old version --running at ~90x {-nth_FRP :: Double -> (Double -> (a,Double)) -> a nth_FRP n f = nth_FRP' n 0 0 f nth_FRP' :: Double -> Double -> Double -> (Double -> (a,Double)) -> a nth_FRP' n t i f = let x = f $! i in if t == n then (fst x) else nth_FRP' n (t+1) (snd x) f -} exp' :: Double -> (Double,Double) exp' i = let e = 1+i i'= i+e*dt in (e,i') {- --4.5x --last $ take n S.exp' exp' :: [Double] exp' = let i = 0: i' e = S.map (+1) i i' = S.zipWith (\x y -> x+y*dt) i e in e -} {- --gives you a different value than arrows with dt !=1 --also is really slow, probably using an integral is a --faster way to do ** than calculating ** from scratch everytime --with the integral, you already ahve most of the computation done nth_FRP n t f = (f t) `seq` if t == n then f t else nth_FRP n (t+1) f exp' :: Double -> Double exp' t = 2**(t* dt) exp'' :: Double -> (Double,Double) exp'' t = (t+1,2**(t*dt)) exp' :: (Double,Double) exp' = let x = (2**(t*dt),t+1) t = snd x in x -} sine :: ArrowInit a => Double -> a () Double sine freq = proc _ -> do rec x <- init i -< r y <- init 0 -< x let r = c * x - y returnA -< r where omh = 2 * pi / (fromIntegral sr) * freq i = sin omh c = 2 * cos omh sineL :: Double -> [Double ] sineL freq = let omh = 2 * pi * freq * dt d = sin omh c = 2 * cos omh r = zipWith (\d2 d1 -> c * d2 - d1 ) d2 d1 d1 = delay 0 d2 d2 = delay d r in r delay = (:) oscSine :: ArrowInit a => Double -> a Double Double oscSine f0 = proc cv -> do let f = f0 * (2 ** cv) phi <- integral -< 2 * pi * f returnA -< sin phi testOsc :: ArrowInit a => (Double -> a Double Double) -> a () Double testOsc f = arr (const 1) >>> f 440 sciFi :: ArrowInit a => a () Double sciFi = proc () -> do und <- oscSine 3.0 -< 0 swp <- integral -< -0.25 audio <- oscSine 440 -< und * 0.2 + swp + 1 returnA -< audio robot :: ArrowInit a => a (Double, Double) Double robot = proc inp -> do let vr = snd inp vl = fst inp vz = vr + vl t <- integral -< vr - vl let t' = t / 10 x <- integral -< vz * cos t' y <- integral -< vz * sin t' returnA -< x / 2 + y / 2 testRobot :: ArrowInit a => a (Double, Double) Double -> a () Double testRobot bot = proc () -> do u <- sine 2 -< () robot -< (u, 1 - u)
santolucito/Euterpea_Projects
CCA/Sample1.hs
mit
3,552
7
14
1,010
1,111
564
547
73
2
module Mutrec where -- Mutually recursive functions data T = K f1 :: [T] -> [T] f1 [] = [] f1 (x:xs) = (x : f2 xs) f2 :: [T] -> [T] f2 [] = [] f2 (y:ys) = (y : f1 ys)
antalsz/hs-to-coq
examples/tests/Mutrec.hs
mit
180
0
7
56
116
64
52
8
1
module Irg.Lab2.GL.Utility ( GameState(..), MouseClicks, ReshapeCallback, DisplayCallback, KeyboardCallback, MouseCallback, getWindowSize ) where --import qualified Graphics.GL.Compatibility33 as GL import qualified Graphics.UI.GLUT as GLUT import Data.IORef import Irg.Lab2.Geometry.Shapes getWindowSize :: Num a => IO (a, a) getWindowSize = do GLUT.Size width height <- GLUT.get GLUT.windowSize return (fromIntegral width,fromIntegral height) data GameState = GameState { drawOrObj :: String, mouseClicks :: MouseClicks, drawnPolys :: [Polygon], leftestPix :: GLUT.GLdouble, rightestPix :: GLUT.GLdouble, upestPix :: GLUT.GLdouble, downestPix :: GLUT.GLdouble } deriving (Eq) type MouseClicks = IORef [(GLUT.GLfloat, GLUT.GLfloat)] type ReshapeCallback = GameState -> GLUT.Size -> IO () type DisplayCallback = GameState -> IO () type KeyboardCallback = GameState -> Char -> GLUT.Position -> IO () type MouseCallback = GameState -> GLUT.MouseButton -> GLUT.KeyState -> GLUT.Position -> IO ()
DominikDitoIvosevic/Uni
IRG/src/Irg/Lab2/GL/Utility.hs
mit
1,029
0
10
158
307
176
131
29
1
{-# LANGUAGE PackageImports #-} {-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-} -- | Reexports "Data.Proxy.Compat" -- from a globally unique namespace. module Data.Proxy.Compat.Repl.Batteries ( module Data.Proxy.Compat ) where import "this" Data.Proxy.Compat
haskell-compat/base-compat
base-compat-batteries/src/Data/Proxy/Compat/Repl/Batteries.hs
mit
282
0
5
31
29
22
7
5
0
{-# LANGUAGE FlexibleContexts #-} module AmrPutAcc (binom, main) where import qualified Data.Array.Accelerate as A import Data.Array.Accelerate (Z(..), (:.)(..)) import qualified Data.Array.Accelerate.CUDA as ACUDA import Control.DeepSeq (deepseq, NFData) import Control.Monad import System.Environment (getEnv) import System.CPUTime -- Pointwise manipulation of vectors an scalars (^*^), (^+^) :: A.Acc (A.Vector FloatRep) -> A.Acc (A.Vector FloatRep) -> A.Acc (A.Vector FloatRep) v1 ^*^ v2 = A.zipWith (*) v1 v2 v1 ^+^ v2 = A.zipWith (+) v1 v2 (-^), (*^) :: A.Exp FloatRep -> A.Acc (A.Vector FloatRep) -> A.Acc (A.Vector FloatRep) c -^ v = A.map (c -) v c *^ v = A.map (c *) v pmax :: A.Acc (A.Vector FloatRep) -> A.Exp FloatRep -> A.Acc (A.Vector FloatRep) pmax v c = A.map (max c) v ppmax :: A.Acc (A.Vector FloatRep) -> A.Acc (A.Vector FloatRep) -> A.Acc (A.Vector FloatRep) ppmax = A.zipWith max type FloatRep = Float --type FloatRep = Double -- I would like to use Double, but my NVIDA card does not support double binom :: A.Exp Int -> A.Acc(A.Vector FloatRep) binom expiry = first where i2f :: A.Exp A.DIM1 -> A.Exp FloatRep i2f = A.fromIntegral . A.unindex1 uPow, dPow :: A.Exp Int -> A.Acc(A.Vector FloatRep) dPow i = A.drop (n+1-i) $ A.reverse $ A.generate (A.lift (Z:.n+1)) (\ix -> d ** i2f ix) uPow i = A.take i $ A.generate (A.lift (Z:.n+1)) (\ix -> u ** i2f ix) finalPut :: A.Acc (A.Vector FloatRep) finalPut = pmax (A.fromIntegral strike -^ st) (0.0) where st = A.fromIntegral s0 *^ (uPow (n+1)^*^ dPow (n+1)) -- for (i in n:1) { -- St<-S0*u.pow[1:i]*d.pow[i:1] -- put[1:i]<-pmax(strike-St,(qUR*put[2:(i+1)]+qDR*put[1:i])) -- } first :: A.Acc (A.Vector FloatRep) first = A.afst $ A.awhile (\ x -> A.unit $ A.the (A.asnd x) A.>* 0) (\ x -> A.lift (prevPut (A.the (A.asnd x)) (A.afst x) , A.map (+(-1)) (A.asnd x))) (A.lift (finalPut, A.unit n)) prevPut :: A.Exp Int -> A.Acc(A.Vector FloatRep) -> A.Acc(A.Vector FloatRep) prevPut i put = ppmax(A.fromIntegral strike -^ st) ((qUR *^ A.tail put) ^+^ (qDR *^ A.init put)) where st = A.fromIntegral s0 *^ (uPow i ^*^ dPow i) -- standard econ parameters strike, bankDays, s0 :: A.Exp Int strike = 100 bankDays = 252 s0 = 100 r, alpha, sigma :: A.Exp FloatRep r = 0.03; alpha = 0.07; sigma = 0.20 n :: A.Exp Int n = expiry*bankDays dt, u, d, stepR, q, qUR :: A.Exp FloatRep dt = A.fromIntegral expiry / A.fromIntegral n u = exp(alpha*dt+sigma*sqrt dt) d = exp(alpha*dt-sigma*sqrt dt) stepR = exp(r*dt) q = (stepR-d)/(u-d) qUR = q/stepR; qDR = (1-q)/stepR arun :: (t -> A.Vector a) -> t -> a arun run x = head $ A.toList $ run x time :: NFData t => t -> IO (t, Integer) time x = do start <- getCPUTime -- In picoseconds; 1 microsecond == 10^6 picoseconds. end <- x `deepseq` getCPUTime return (x, (end - start) `div` 1000000) main :: IO () main = do n <- liftM read getContents -- FIXME: this isn't even close to measuring the real runtime. -- Accelerate is not easy to benchmark at all. (v, runtime) <- time $ arun ACUDA.run $ binom $ A.constant n result <- getEnv "HIPERMARK_RESULT" writeFile result $ show v runtime_file <- getEnv "HIPERMARK_RUNTIME" writeFile runtime_file $ show runtime
HIPERFIT/hipermark-benchmarks
benchmarks/american_options/implementations/haskell_accelerate/AmrPutAcc.hs
mit
3,416
0
18
797
1,511
796
715
73
1
module Probability.Distribution.Markov where import Probability.Random sample_markov x0 next = do x1 <- next x0 xs <- sample_markov x1 next return (x0:xs) sample_markov_n 0 x0 next = return [] sample_markov_n n x0 next = do x1 <- next x0 xs <- sample_markov (n-1) x1 next return (x0:xs) -- I think if next has type (a->Dist a) and not just -- (a->Sample a), then we could compute likelihoods. -- The fastest way would be to represent the transition -- probabilities in a matrix -- at least for integer -- sequences -- but that is less general. Maybe we should -- make a markov_int distribution that takes a starting -- distribution and a transition probability matrix? -- I presume that we would need to make any markov DISTRIBUTION -- have an actual length. Do we want them to be lazy? Strict?
bredelings/BAli-Phy
haskell/Probability/Distribution/Markov.hs
gpl-2.0
817
0
10
160
139
71
68
11
1
-- circulos_en_estrella.hs -- Círculos en estrella. -- José A. Alonso Jiménez <[email protected]> -- Sevilla, 20 de Mayo de 2013 -- --------------------------------------------------------------------- -- --------------------------------------------------------------------- -- Ejercicio. ¿Qué dibujo genera el siguiente programa? -- --------------------------------------------------------------------- import Graphics.Gloss main :: IO () main = display (InWindow "Dibujo" (500,300) (20,20)) white dibujo dibujo :: Picture dibujo = pictures [rotate angulo (translate x 0 (circle 10)) | x <- [50,100..200], angulo <- [ 0, 45..360]]
jaalonso/I1M-Cod-Temas
src/Tema_25/circulos_en_estrella.hs
gpl-2.0
680
0
11
117
127
72
55
7
1
{-# OPTIONS_GHC -fglasgow-exts #-} -- test program for C modules -- Wrapper for gcc, use it like gcc and test the C parser -- module Main (main) where import System.Environment (getArgs, getEnv) import System.CPUTime (getCPUTime) import System.Exit import System.Cmd (rawSystem) import System.IO (appendFile, openTempFile, hClose, hPutStr) import System.Directory (getCurrentDirectory, removeFile) import Control.Exception (evaluate, catchJust, ioErrors) import Numeric (showFFloat) import Data.List (isSuffixOf) import Position import State (run, fatalsHandledBy, liftIO) import CAST import CParser (parseC) main :: IO () main = do logdir <- getEnv "C2HS_CC_LOGDIR" let logFile = logdir ++ "/cc-wrapper.log" args <- getArgs case mungeArgs [] [] args of Ignore -> return () Unknown -> appendFile logFile $ "could not munge gcc args: " ++ show args ++ "\n" Groked cfile args' -> do (outFile, hnd) <- openTempFile logdir "cc-wrapper.i" hClose hnd gccExitcode <- rawSystem "gcc" (["-E", "-o", outFile] ++ args') input <- readFile outFile start <- getCPUTime CHeader decls _ <- run undefined () $ parseC input (Position cfile 1 1) `fatalsHandledBy` \error -> liftIO $ do removeFile outFile (reportFile, hnd) <- openTempFile logdir "cc-wrapper.report" pwd <- getCurrentDirectory hPutStr hnd $ "failed to parse " ++ cfile ++ "\nwith message:\n" ++ show error ++ "\nworking dir: " ++ pwd ++ "\ncommand: " ++ show args ++ "\npreprocessed input follows:\n\n" ++ input hClose hnd appendFile logFile $ "failed to parse " ++ cfile ++ "\n (see " ++ reportFile ++ ")" ++ "\n with message: " ++ show error ++ "\n\n" exitWith (ExitFailure 1) end <- getCPUTime let duration = (fromIntegral (end - start)) / (10^12) removeFile outFile appendFile logFile $ "parsed " ++ cfile ++ " (" ++ show (length decls) ++ " decls, " ++ show (length (lines input)) ++ " lines) in " ++ showFFloat (Just 2) duration "s\n" data MungeResult = Unknown | Ignore | Groked FilePath [String] mungeArgs :: [String] -> String -> [String] -> MungeResult mungeArgs accum [] [] = Unknown mungeArgs accum cfile [] = Groked cfile (reverse accum) mungeArgs accum cfile ("-E":args) = Ignore mungeArgs accum cfile ("-M":args) = Ignore mungeArgs accum cfile ("-o":outfile:args) = mungeArgs accum cfile args mungeArgs accum cfile (cfile':args) | ".c" `isSuffixOf` cfile' || ".hc" `isSuffixOf` cfile' || ".i" `isSuffixOf` cfile' = if null cfile then mungeArgs (cfile':accum) cfile' args else Unknown mungeArgs accum cfile (cfile':args) | ".S" `isSuffixOf` cfile' = Ignore mungeArgs accum cfile (arg:args) = mungeArgs (arg:accum) cfile args
jrockway/c2hs
tests/cparser/CCWrapper.hs
gpl-2.0
3,096
0
28
903
931
476
455
69
3
{-| Module : Sivi.Interface.PrinterThread Description : Thread for doing IO actions Copyright : (c) Maxime ANDRE, 2015 License : GPL-2 Maintainer : [email protected] Stability : experimental Portability : POSIX -} module Sivi.Interface.PrinterThread ( printerThread ) where import Control.Concurrent.Chan import Control.Monad(forever, join) -- | This thread performs IO actions coming from a Chan. Used to atomically do those actions. If we don't print with it, a thread prints some characters, then the following thread prints some characters, etc. printerThread :: Chan (IO ()) -> IO() printerThread pc = forever $ join (readChan pc)
iemxblog/sivi-haskell
src/Sivi/Interface/PrinterThread.hs
gpl-2.0
688
0
9
143
79
44
35
7
1
-- The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: -- -- 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... -- -- By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word. -- -- Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words? import Data.Char import Data.List.Split main :: IO () main = answer >>= putStrLn answer :: IO String answer = do ws <- readFile "p042_words.txt" return . show . length . filter isTriangle . splitOn "," $ filter (/='"') ws -- Find the sum of all the alphabetical numbers of the letters in a word wordVal :: String -> Int wordVal = sum . map alnum -- Given a character give its alphabetical number alnum :: Char -> Int alnum l = ord l - 64 -- List of all triangle numbers up to 100, which seems not to affect the score (tried 1000 as well) triangles :: [Int] triangles = map triangle [1..100] -- Given a number n return the nth triangle number triangle :: Double -> Int triangle n = round $ 0.5*n*(n+1) -- Is a string a triangle word isTriangle :: String -> Bool isTriangle w = wordVal w `elem` triangles
ciderpunx/project_euler_in_haskell
euler042.hs
gpl-2.0
1,470
0
11
320
234
127
107
24
1
{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-} module Bachelor.SeqParse where #define EVENTLOG_CONSTANTS_ONLY #include "EventLogFormat.h" import Bachelor.Parsers import Bachelor.Types import Control.Applicative import Control.Monad import Control.Lens import Data.List import Data.Map.Lens import Data.Maybe import Debug.Trace import GHC.RTS.Events hiding (machine) import qualified Bachelor.DataBase as DB import qualified Bachelor.Util as U import qualified Data.Array.IArray as Array import qualified Data.Attoparsec.ByteString.Lazy as AL import qualified Data.ByteString.Lazy as LB import qualified Data.HashMap.Strict as M import qualified Data.IntMap as IM import qualified Database.PostgreSQL.Simple as PG import qualified System.Directory as Dir import qualified System.IO as IO -- taken from RTSEventsParser.hs instance Eq ThreadStopStatus where NoStatus == NoStatus = True HeapOverflow == HeapOverflow = True StackOverflow == StackOverflow = True ThreadYielding == ThreadYielding = True ThreadBlocked == ThreadBlocked = True ThreadFinished == ThreadFinished = True ForeignCall == ForeignCall = True BlockedOnMVar == BlockedOnMVar = True BlockedOnMVarRead == BlockedOnMVarRead = True -- since GHC-7.8.2/ghc-events-0.4.3.1 BlockedOnBlackHole == BlockedOnBlackHole = True BlockedOnRead == BlockedOnRead = True BlockedOnWrite == BlockedOnWrite = True BlockedOnDelay == BlockedOnDelay = True BlockedOnSTM == BlockedOnSTM = True BlockedOnDoProc == BlockedOnDoProc = True BlockedOnCCall == BlockedOnCCall = True BlockedOnCCall_NoUnblockExc == BlockedOnCCall_NoUnblockExc = True BlockedOnMsgThrowTo == BlockedOnMsgThrowTo = True ThreadMigrating == ThreadMigrating = True BlockedOnMsgGlobalise == BlockedOnMsgGlobalise = True (BlockedOnBlackHoleOwnedBy _) == (BlockedOnBlackHoleOwnedBy _) = True _ == _ = False -- The Parsing state for a specific capability. It contains the Lazy ByteString -- consumed up to the current event, and the last parsed Event. type CapState = (LB.ByteString, Maybe Event) -- The state that a parser of a single EventLog carries. data ParserState = ParserState { _p_caps :: CapState, -- the 'system' capability. _p_cap0 :: CapState, -- capability 0. _p_rtsState :: RTSState, -- the inner state of the runtime _p_pt :: ParserTable -- event types and their parsers, -- generated from the header. } $(makeLenses ''ParserState) instance Show ParserState where show (ParserState (bss,es) (bs0,e0) rts pt) = "\n\n#####BEGIN PARSER STATE\n\n" ++ "System Capability: " ++ "\n" ++ " " ++ (show $ LB.take 10 $ bss) ++ "\n" ++ (show es) ++ "\n" ++ "Capability 0: " ++ "\n" ++ " " ++ (show $ LB.take 10 $ bs0) ++ "\n" ++ (show e0) ++ "\n" ++ "Run-Time State: " ++ (show rts) ++ "\n\n#### END PARSER STATE\n\n" -- the state that the overall parser keeps. -- contains the parser information for every single *.eventlog file, -- as well as the DataBase connection. -- if time permits, this might be extended to contain a message queue, -- containing open messages that have not yet been committed to the -- database. data MultiParserState = MultiParserState { _machineTable :: M.HashMap MachineId ParserState, -- Each machine has its -- own ParserState. _con :: DB.DBInfo -- with a global DataBase connection. } deriving Show $(makeLenses ''MultiParserState) -- paths: testdir = "/home/basti/bachelor/traces/mergesort_small/" {- - each eventLog file has the number of the according machine (this pe) stored - in the filename as base_file#xxx.eventlog, where xxx is the number - that will also be the later MachineId -} extractNumber :: String -> MachineId extractNumber str = read $ reverse $ takeWhile (/= '#') $ drop 9 $ reverse str createParserState :: FilePath -> IO ParserState createParserState fp = do let mid = extractNumber fp bs <- LB.readFile fp case AL.parse headerParser bs of AL.Done bsrest header -> do let pt = mkParserTable header bsdata = LB.drop 4 bsrest --'datb' return ParserState { _p_caps = getFirstCapState bsdata pt 0xFFFF, _p_cap0 = getFirstCapState bsdata pt 0, _p_rtsState = makeRTSState mid, _p_pt = pt } _ -> error $ "failed parsing header of file " ++ fp getFirstCapState :: LB.ByteString -> ParserTable -> Capability -> CapState getFirstCapState bs pt cap = case AL.parse (parseSingleEvent pt cap) bs of AL.Done bsrest res -> (bsrest,res) _ -> error $ "failed parsing the first event for cap " ++ (show cap) ++ "\n" ++ (show $ LB.take 20 bs) -- takes the parser state of a capability -- replaces the event with the next one in the bytstring. parseNextEvent :: CapState -> ParserTable -> Capability -> CapState parseNextEvent (bs,e) pt cap = case AL.parse (parseSingleEvent pt cap) bs of AL.Done bsrest res -> (bsrest,res) _ -> error $ "Failing to parse event: \n\n" ++ "Capability: " ++ (show $ cap) ++ "\n" ++ "Previous Event: " ++ (show $ e) ++ "\n" ++ (show $ LB.take 100 $ bs) -- specific functions to parse the next event for the system cap and the -- 1st capability. -- short function definition through lens magic. parseNextEventSystem :: ParserState -> ParserState parseNextEventSystem pstate = p_caps %~ (\s -> parseNextEvent s (pstate^.p_pt) 0xFFFF) $ pstate parseNextEventNull :: ParserState -> ParserState parseNextEventNull pstate = p_cap0 %~ (\s -> parseNextEvent s (pstate^.p_pt) 0) $ pstate {- Handlers for the different EventTypes. Some do not create GUIEvents, so they just return the new ParserState Some do create GUIEvents, so they return (ParserState,[GUIEvent]) -} {- when Events are handled, we need to know from which Eventlog they where - sourced, so they are annotated with additional Information: -} data AssignedEvent = AssignedEvent { _event :: Event, _machine :: MachineId, _cap :: Int } $(makeLenses ''AssignedEvent) type Handler = RTSState -> AssignedEvent -> (RTSState,[GUIEvent]) {- - This is the main function to handle events, - manipulate the rts state, and generate GUI Events. - -} handleEvents :: Handler handleEvents rts aEvent@(AssignedEvent event@(Event ts spec) mid cap) = case spec of KillProcess pid -> killProcess rts mid pid ts KillMachine mid -> killMachine rts mid ts CreateMachine mid realtime -> let newMachine = MachineState { _m_state = Idle, _m_timestamp = ts, _m_pRunning = 0, _m_pRunnable = 0, _m_pBlocked = 0, _m_pIdle = 0, _m_pTotal = 0 } creationEvent = NewMachine mid in (set rts_machine newMachine $ rts, [creationEvent]) CreateProcess pid -> let newProcess = ProcessState { _p_parent = mid, _p_state = Runnable, _p_timestamp = ts, _p_tRunning = 0, _p_tRunnable = 0, _p_tBlocked = 0, _p_tTotal = 0 } creationEvent = NewProcess mid pid (newMachine,mEvent) = updateProcessCountAndMachineState mid ts (rts^.rts_machine) Nothing (Just Runnable) rts' = set (rts_processes.(at pid)) (Just newProcess) $ set rts_machine newMachine $ rts in (rts', creationEvent : mList [mEvent]) AssignThreadToProcess tid pid -> let newThread = ThreadState { _t_parent = pid, _t_state = Runnable, _t_timestamp = ts } creationEvent = Just $ NewThread mid pid tid oldProcess = (rts^.rts_processes) M.! pid (newProcess,pEvent) = updateThreadCountAndProcessState mid pid ts oldProcess Nothing (Just Runnable) oldProcessState = oldProcess^.p_state newProcessState = newProcess^.p_state (newMachine,mEvent) = updateProcessCountAndMachineState mid ts (rts^.rts_machine) (Just oldProcessState) (Just newProcessState) rts' = set rts_machine newMachine $ set (rts_threads.(at tid)) (Just newThread) $ set (rts_processes.(at pid)) (Just newProcess) $ rts in (rts', mList [creationEvent, pEvent, mEvent]) RunThread tid -> changeThreadState rts mid tid Running ts WakeupThread tid _-> changeThreadState rts mid tid Running ts --the StopThread event has several stopreasons, some of which will only --suspend the thread, one of which will kill it. StopThread tid reason -> if reason == ThreadFinished then do killThread rts mid tid ts --changeThreadState rts mid tid Blocked ts else if reason `elem` blockList then do changeThreadState rts mid tid Blocked ts else do changeThreadState rts mid tid Runnable ts {- - not observed, because EdenTV also does not observe it. ThreadRunnable tid -> changeThreadState rts mid tid Runnable ts -} _ -> (rts,[]) --taken directly from RTSEventsParser.hs, the list of reasons to block --a thread blockList = [ThreadBlocked, BlockedOnMVar, BlockedOnBlackHole, BlockedOnDelay, BlockedOnSTM, BlockedOnDoProc, BlockedOnMsgThrowTo, ThreadMigrating, BlockedOnMsgGlobalise, BlockedOnBlackHoleOwnedBy 0] {- - We often have to deal with lists of type [Maybe GUIEvent], and want to - filter the actual events. - -} mList = (map fromJust).(filter isJust) {- - generalized function for changing the state of a thread, and updating - the parent process and machine. -} changeThreadState :: RTSState -> MachineId -> ThreadId -> RunState-> Timestamp -> (RTSState, [GUIEvent]) changeThreadState rts mid tid state ts = if M.member tid (rts^.rts_threads) then let oldThread = (rts^.rts_threads) M.! tid oldState = oldThread^.t_state pid = oldThread^.t_parent oldProcess = (rts^.rts_processes) M.! pid (newThread,tEvent) = setThreadState mid tid oldThread ts state (newProcess,pEvent) = updateThreadCountAndProcessState mid pid ts oldProcess (Just oldState) (Just state) oldProcessState = oldProcess^.p_state newProcessState = newProcess^.p_state (newMachine,mEvent) = updateProcessCountAndMachineState mid ts (rts^.rts_machine) (Just oldProcessState) (Just newProcessState) rts' = set rts_machine newMachine $ set (rts_threads.(at tid)) (Just newThread) $ set (rts_processes.(at pid)) (Just newProcess) $ rts in (rts', mList [tEvent, pEvent, mEvent]) --ignore 'homeless' threads. else (rts,[]) killThread :: RTSState -> MachineId -> ThreadId -> Timestamp -> (RTSState, [GUIEvent]) killThread rts mid tid ts = if M.member tid (rts^.rts_threads) then let oldThread = (rts^.rts_threads) M.! tid oldState = oldThread^.t_state pid = oldThread^.t_parent oldProcess = (rts^.rts_processes) M.! pid tEvent = GUIEvent { mtpType = Thread mid tid, startTime = oldThread^.t_timestamp, duration = ts - oldThread^.t_timestamp, state = oldState } (newProcess,pEvent) = updateThreadCountAndProcessState mid pid ts oldProcess (Just oldState) Nothing oldProcessState = oldProcess^.p_state newProcessState = newProcess^.p_state (newMachine,mEvent) = updateProcessCountAndMachineState mid ts (rts^.rts_machine) (Just oldProcessState) (Just newProcessState) rts' = set rts_machine newMachine $ set (rts_threads.(at tid)) Nothing$ set (rts_processes.(at pid)) (Just newProcess) $ rts in (rts', tEvent : mList [pEvent, mEvent]) --ignore 'homeless' threads. else (rts,[]) killMachine :: RTSState -> MachineId -> Timestamp -> (RTSState, [GUIEvent]) killMachine rts mid ts = let pids = map fst $ M.toList $ rts^.rts_processes ptEvents = concat $ map (snd.(\pid->killProcess rts mid pid ts)) pids m = rts^.rts_machine mEvent = GUIEvent { mtpType = Machine mid, startTime = _m_timestamp m, duration = ts - _m_timestamp m, state = _m_state m } in (RTSState PreMachine M.empty M.empty, mEvent:ptEvents) killProcess :: RTSState -> MachineId -> ProcessId -> Timestamp -> (RTSState, [GUIEvent]) killProcess rts mid pid ts = let endThread :: (ThreadId,ThreadState) -> GUIEvent endThread (tid,t) = GUIEvent { mtpType = Thread mid tid, startTime = t^.t_timestamp, duration = ts - t^.t_timestamp, state = t^.t_state } tEvents = map endThread $ filter (\(tid,t) -> t^.t_parent == pid) $ M.toList (rts^.rts_threads) rts' = over rts_threads (M.filter (\x -> x^.t_parent/=pid)) $ rts rts'' = set (rts_processes.(at pid)) Nothing $ rts' p = (rts^.rts_processes) M.! pid pEvent = Just $ GUIEvent { mtpType = Process mid pid, startTime = p^.p_timestamp, duration = ts - p^.p_timestamp, state = p^.p_state } (newMachine,mEvent) = updateProcessCountAndMachineState mid ts (rts^.rts_machine) (Just (p^.p_state)) Nothing rts''' = set rts_machine newMachine $ rts'' in (rts''', mList [pEvent,mEvent] ++ tEvents) setThreadState :: MachineId -> ThreadId -> ThreadState -> Timestamp -> RunState -> (ThreadState, Maybe GUIEvent) setThreadState mid tid t ts state | t^.t_state == state = (t,Nothing) | otherwise = (t { _t_state = state, _t_timestamp = ts }, Just $ GUIEvent { mtpType = Thread mid tid, startTime = t^.t_timestamp, duration = ts - t^.t_timestamp, state = t^.t_state }) updateProcessCountAndMachineState :: MachineId -> Timestamp -> MachineState -> (Maybe RunState) -> (Maybe RunState) -> (MachineState, Maybe GUIEvent) updateProcessCountAndMachineState mid ts m oldState newState = let m' = updateProcessCount m oldState newState m'' = setMachineState m' in if _m_state m == _m_state m'' then (m'',Nothing) else (set m_state (_m_state m'')$ set m_timestamp ts $ m'', Just $ GUIEvent { mtpType = Machine mid, startTime = _m_timestamp m, duration = ts - _m_timestamp m, state = _m_state m }) {- takes a state transition within a Process, and the parent MachineId - and updates the Machine State accordingly. -} updateProcessCount :: MachineState -> (Maybe RunState) -> (Maybe RunState) -> MachineState updateProcessCount m oldState newState | oldState == newState = m | otherwise = let m' = case oldState of --decrement the old state counter, or insert the event. (Just Idle) -> m_pIdle %~ decr $ m (Just Running) -> m_pRunning %~ decr $ m (Just Blocked) -> m_pBlocked %~ decr $ m (Just Runnable) -> m_pRunnable %~ decr $ m Nothing -> m_pTotal %~ incr $ m m'' = case newState of --increment the new state counter, or remove the event --from the total (Just Idle) -> m_pIdle %~ incr $ m' (Just Running) -> m_pRunning %~ incr $ m' (Just Blocked) -> m_pBlocked %~ incr $ m' (Just Runnable) -> m_pRunnable %~ incr $ m' Nothing -> m_pTotal %~ decr $ m' in m'' {- - sets the Machine State according to the current Process count. - -} setMachineState :: MachineState -> MachineState setMachineState m -- no Processess Assigned, this Machine is idle | _m_pTotal m == 0 = m {_m_state = Idle} -- all Processes Idle, this machine is idle | _m_pTotal m == _m_pIdle m = m {_m_state = Idle} --if a single process is running, this Machine will be running. | _m_pRunning m >0 = m {_m_state = Running} --if all Processes are blocked, this Machine is blocked. | _m_pBlocked m == _m_pTotal m = m {_m_state = Blocked} --if at least one Process is Runnable, this Machine is runnable. | _m_pRunnable m >0 = m {_m_state = Runnable} --there are blocked and idle processes. mark the machine as blocked. | _m_pBlocked m >0 && _m_pIdle m >0 = m {_m_state = Blocked} | otherwise = error $ "could not determine machine state" ++ show m {- - takes a state transition within a thread and the parent process, - and updates it accordingly. - -} updateThreadCountAndProcessState :: MachineId -> ProcessId -> Timestamp -> ProcessState -> (Maybe RunState) -> (Maybe RunState) -> (ProcessState, Maybe GUIEvent) updateThreadCountAndProcessState mid pid ts p oldState newState = let p' = updateThreadCount p oldState newState p'' = setProcessState p' in if p^.p_state == p''^.p_state then (p'',Nothing) else (set p_state (p''^.p_state) $ set p_timestamp ts $ p'', Just $ GUIEvent { mtpType = Process mid pid, startTime = p^.p_timestamp, duration = ts - p^.p_timestamp, state = p^.p_state }) {- - updates the inner Thread count of a Process. If the Thread was newly - created, oldState is Nothing. If the Thread is being killed, newState - is Nothing. - -} incr x = x + 1 decr x = if (x - 1) >= 0 then x-1 else error "Negative count" updateThreadCount :: ProcessState -> (Maybe RunState) -> (Maybe RunState) -> ProcessState updateThreadCount p oldState newState | oldState == newState = p --for testing, threads cannot be idle. | (oldState == Just Idle) || (newState == Just Idle) = p | otherwise = let p' = case oldState of --decrement the old state counter, or insert the event. (Just Running) -> p_tRunning %~ decr $ p (Just Blocked) -> p_tBlocked %~ decr $ p (Just Runnable) -> p_tRunnable %~ decr $ p Nothing -> p_tTotal %~ incr $ p p'' = case newState of --increment the new state counter, or remove the event --from the total (Just Running) -> p_tRunning %~ incr $ p' (Just Blocked) -> p_tBlocked %~ incr $ p' (Just Runnable) -> p_tRunnable %~ incr $ p' Nothing -> p_tTotal %~ decr $ p' in p'' -- A thread event will adjust the counters of a process event. -- this function will then adjust the internal state. setProcessState :: ProcessState -> ProcessState -- no Threads Assigned, this process is idle. setProcessState p | p^.p_tTotal == 0 = p {_p_state = Idle} --if a single thread is running, this process will be running. | p^.p_tRunning >0 = p {_p_state = Running} --if all threads are blocked, this thread is blocked. | p^.p_tBlocked == p^.p_tTotal = p {_p_state = Blocked} --if at least one Thread is Runnable, this process is runnable. | p^.p_tRunnable >0 = p {_p_state = Runnable} -- instead of parsing a single *.eventlog file, we want to parse a *.parevents -- file, which is a zipfile containing a set of *.eventlog files, one for -- every Machine used. -- because reading from a zipfile lazily seems somewhat troubling, we will -- instead unzip all files beforehand and then read them all as single files. run :: FilePath -> IO() run dir = do -- filter the directory contents into eventlogs. paths <- filter (isSuffixOf ".eventlog") <$> Dir.getDirectoryContents dir -- prepend the directory. let files = map (\x -> dir ++ x) paths -- extract the machine number. mids = map extractNumber paths -- connect to the DataBase, and enter a new trace, with the current -- directory and time. -- create a parserState for each eventLog file. pStates <- zip mids <$> mapM createParserState files -- create the multistate that encompasses all machines. --let mState = MultiParserState { -- _machineTable = M.fromList pStates, -- _con = dbi} -- for testing purposes only: test the first machine --let m1 = fromJust $ (mState^.machineTable^.(at 2)) conn <- DB.mkConnection PG.withTransaction conn $ do dbi <- DB.insertTrace conn dir dbi <- foldM handleMachine dbi pStates dbi <- DB.finalize dbi return () handleMachine :: DB.DBInfo -> (MachineId, ParserState) -> IO DB.DBInfo handleMachine dbi (mid,pstate) = do print $ "Processing Machine no ." ++ (show mid) dbi <- parseSingleEventLog dbi mid pstate return dbi {- - This is the main function for parsing a single event log and storing - the events contained within into the database. - -} parseSingleEventLog :: DB.DBInfo -> MachineId -> ParserState -> IO DB.DBInfo -- event blocks need to be skipped without handling them. -- System EventBlock parseSingleEventLog dbi mid pstate@(ParserState (bss,evs@(Just (Event _ EventBlock{}))) _ rts pt) = parseSingleEventLog dbi mid $ parseNextEventSystem pstate -- Cap 0 EventBlock parseSingleEventLog dbi mid pstate@(ParserState _ (bs0,e0@(Just (Event _ EventBlock{}))) rts pt) = parseSingleEventLog dbi mid $ parseNextEventNull pstate -- both capabilies still have events left. return the earlier one. parseSingleEventLog dbi mid pstate@(ParserState (bss,evs@(Just es@(Event tss specs))) (bs0,ev0@(Just e0@(Event ts0 spec0))) rts pt) = if (tss < ts0) then do let aEvent = AssignedEvent es mid (-1) (newRTS, guiEvents) = handleEvents (pstate^.p_rtsState) aEvent pstate' = set p_rtsState newRTS $ pstate dbi <- foldM DB.insertEvent dbi guiEvents parseSingleEventLog dbi mid $ parseNextEventSystem pstate' else do let aEvent = AssignedEvent e0 mid 0 (newRTS, guiEvents) = handleEvents (pstate^.p_rtsState) aEvent pstate' = set p_rtsState newRTS $ pstate dbi <- foldM DB.insertEvent dbi guiEvents parseSingleEventLog dbi mid $ parseNextEventNull pstate' -- no more system events. parseSingleEventLog dbi mid pstate@(ParserState (bss,evs@Nothing) (bs0,ev0@(Just e0@(Event ts0 spec0))) rts pt) = do let aEvent = AssignedEvent e0 mid 0 (newRTS, guiEvents) = handleEvents (pstate^.p_rtsState) aEvent pstate' = set p_rtsState newRTS $ pstate dbi <- foldM DB.insertEvent dbi guiEvents parseSingleEventLog dbi mid $ parseNextEventNull pstate' -- no more cap0 events. parseSingleEventLog dbi mid pstate@(ParserState (bss,evs@(Just es@(Event tss specs))) (bs0,ev0@Nothing) rts pt) = do let aEvent = AssignedEvent es mid (-1) (newRTS, guiEvents) = handleEvents (pstate^.p_rtsState) aEvent pstate' = set p_rtsState newRTS $ pstate dbi <- foldM DB.insertEvent dbi guiEvents parseSingleEventLog dbi mid $ parseNextEventSystem pstate' -- no more events. parseSingleEventLog dbi mid pstate@(ParserState (bss,evs@Nothing) (bs0,ev0@Nothing) rts pt) = return dbi
brtmr/Eden-Tracelab-cli-tool
src/Bachelor/SeqParse.hs
gpl-3.0
25,957
10
24
8,658
5,907
3,126
2,781
424
11
-- grid is a game written in Haskell -- Copyright (C) 2018 [email protected] -- -- This file is part of grid. -- -- grid 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. -- -- grid 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 grid. If not, see <http://www.gnu.org/licenses/>. -- module Game.LevelPuzzle.File.Version ( version, ) where import MyPrelude import File.Binary -- | w000 version :: [Word8] version = [0x77, 0x30, 0x30, 0x30]
karamellpelle/grid
source/Game/LevelPuzzle/File/Version.hs
gpl-3.0
923
0
5
176
66
50
16
8
1
----------------------------------------------------------------------------- -- | -- Module : Hie.Language.Haskell.Exts.Extension -- Copyright : (c) Niklas Broberg 2009 -- License : BSD-style (see the file LICENSE.txt) -- -- Maintainer : Niklas Broberg, [email protected] -- Stability : transient -- Portability : portable -- -- This entire module should be replaced with -- Language.Haskell.Extension from cabal, but we must -- wait for a release of cabal that includes the -- 'XmlSyntax' and 'RegularPatterns' extensions. -- ----------------------------------------------------------------------------- module Hie.Language.Haskell.Exts.Extension ( -- * Extensions Extension(..), classifyExtension, impliesExts, -- * Extension groups glasgowExts, knownExtensions ) where -- | This datatype is a copy of the one in Cabal's Language.Haskell.Extension module. -- The intention is to eventually import it from Cabal, but we need to wait for -- the next release of Cabal which includes XmlSyntax and RegularPatterns. data Extension = OverlappingInstances | UndecidableInstances | IncoherentInstances | RecursiveDo | ParallelListComp | MultiParamTypeClasses | NoMonomorphismRestriction | FunctionalDependencies | ExplicitForall | Rank2Types | RankNTypes | PolymorphicComponents | ExistentialQuantification | ScopedTypeVariables | ImplicitParams | FlexibleContexts | FlexibleInstances | EmptyDataDecls | CPP | KindSignatures | BangPatterns | TypeSynonymInstances | TemplateHaskell | ForeignFunctionInterface | Arrows | Generics | NoImplicitPrelude | NamedFieldPuns | PatternGuards | GeneralizedNewtypeDeriving | ExtensibleRecords | RestrictedTypeSynonyms | HereDocuments | MagicHash | TypeFamilies | StandaloneDeriving | UnicodeSyntax | PatternSignatures | UnliftedFFITypes | LiberalTypeSynonyms | TypeOperators | RecordWildCards | RecordPuns -- should be deprecated | DisambiguateRecordFields | OverloadedStrings | GADTs | MonoPatBinds | NoMonoPatBinds -- should be deprecated | RelaxedPolyRec | ExtendedDefaultRules | UnboxedTuples | DeriveDataTypeable | ConstrainedClassMethods | PackageImports | ImpredicativeTypes | NewQualifiedOperators | PostfixOperators | QuasiQuotes | TransformListComp | ViewPatterns | XmlSyntax | RegularPatterns | TupleSections | UnknownExtension String deriving (Eq, Ord, Show, Read) -- | Certain extensions imply other extensions, and this function -- makes the implication explicit. This also handles deprecated -- extensions, which imply their replacements. -- The returned valued is the transitive closure of implied -- extensions. impliesExts :: [Extension] -> [Extension] impliesExts = go where go [] = [] go es = let xs = concatMap implE es ys = filter (not . flip elem es) xs in es ++ go ys implE e = case e of TypeFamilies -> [KindSignatures] ScopedTypeVariables -> [TypeOperators, ExplicitForall] XmlSyntax -> [RegularPatterns] RegularPatterns -> [PatternGuards] RankNTypes -> [Rank2Types] Rank2Types -> [PolymorphicComponents] PolymorphicComponents -> [ExplicitForall] LiberalTypeSynonyms -> [ExplicitForall] -- Deprecations RecordPuns -> [NamedFieldPuns] PatternSignatures -> [ScopedTypeVariables] e -> [] -- | The list of extensions enabled by -- GHC's portmanteau -fglasgow-exts flag. glasgowExts :: [Extension] glasgowExts = [ ForeignFunctionInterface , UnliftedFFITypes , GADTs , ImplicitParams , ScopedTypeVariables , UnboxedTuples , TypeSynonymInstances , StandaloneDeriving , DeriveDataTypeable , FlexibleContexts , FlexibleInstances , ConstrainedClassMethods , MultiParamTypeClasses , FunctionalDependencies , MagicHash , PolymorphicComponents , ExistentialQuantification , UnicodeSyntax , PostfixOperators , PatternGuards , LiberalTypeSynonyms , RankNTypes , ImpredicativeTypes , TypeOperators , RecursiveDo , ParallelListComp , EmptyDataDecls , KindSignatures , GeneralizedNewtypeDeriving , TypeFamilies ] -- | List of all known extensions. Poor man's 'Enum' instance -- (we can't enum with the 'UnknownExtension' constructor). knownExtensions :: [Extension] knownExtensions = [ OverlappingInstances , UndecidableInstances , IncoherentInstances , RecursiveDo , ParallelListComp , MultiParamTypeClasses , NoMonomorphismRestriction , FunctionalDependencies , ExplicitForall , Rank2Types , RankNTypes , PolymorphicComponents , ExistentialQuantification , ScopedTypeVariables , ImplicitParams , FlexibleContexts , FlexibleInstances , EmptyDataDecls , CPP , KindSignatures , BangPatterns , TypeSynonymInstances , TemplateHaskell , ForeignFunctionInterface , Arrows , Generics , NoImplicitPrelude , NamedFieldPuns , PatternGuards , GeneralizedNewtypeDeriving , ExtensibleRecords , RestrictedTypeSynonyms , HereDocuments , MagicHash , TypeFamilies , StandaloneDeriving , UnicodeSyntax , PatternSignatures , UnliftedFFITypes , LiberalTypeSynonyms , TypeOperators , RecordWildCards , RecordPuns -- should be deprecated , DisambiguateRecordFields , OverloadedStrings , GADTs , MonoPatBinds , NoMonoPatBinds -- should be deprecated , RelaxedPolyRec , ExtendedDefaultRules , UnboxedTuples , DeriveDataTypeable , ConstrainedClassMethods , PackageImports , ImpredicativeTypes , NewQualifiedOperators , PostfixOperators , QuasiQuotes , TransformListComp , ViewPatterns , XmlSyntax , RegularPatterns , TupleSections ] -- | A clever version of read that returns an 'UnknownExtension' -- if the string is not recognised. classifyExtension :: String -> Extension classifyExtension str = case readsPrec 0 str of [(e,"")] -> e _ -> UnknownExtension str
monsanto/hie
Hie/Language/Haskell/Exts/Extension.hs
gpl-3.0
6,714
0
14
1,895
839
533
306
189
12
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} -- | The Functional First Order language. Explicitly typed. -- -- ArrTy in the Type really means defunctionalised Type module Lang.FunctionalFO where import Data.Foldable (Foldable) import Data.Traversable (Traversable) import Lang.Type {-# ANN module "HLint: ignore Use camelCase" #-} -- | Function definition, -- There are no lambdas so the arguments to the functions are -- declared here. data Function a = Function { fn_name :: a , fn_tvs :: [a] , fn_args :: [(a,Type a)] , fn_res_ty :: Type a , fn_body :: Body a } deriving (Eq,Ord,Show,Functor,Foldable,Traversable) -- | The body of a function: cascades of cases, with branches eventually ending -- in expressions. data Body a = Case (Expr a) [Alt a] | Body (Expr a) deriving (Eq,Ord,Show,Functor,Foldable,Traversable) type Alt a = (Pattern a,Body a) -- | The simple expressions allowed here data Expr a = Fun a [Type a] [Expr a] -- ^ Function (fully) applied to type arguments and arguments | App (Type a) (Type a) (Expr a) (Expr a) -- ^ Defunctionalisated application | Ptr a [Type a] -- ^ Pointer (applied to some types) | Lit Integer -- ^ The integer and its type constructor -- (to be able to infer the type) deriving (Eq,Ord,Show,Functor,Foldable,Traversable) data Pattern a = Default | ConPat { pat_con :: a , pat_ty_args :: [Type a] , pat_args :: [(a,Type a)] } | LitPat Integer deriving (Eq,Ord,Show,Functor,Foldable,Traversable) partitionAlts :: [Alt a] -> (Maybe (Body a),[Alt a]) partitionAlts alts = case alts of (Default,rhs):xs -> (Just rhs,xs) alt:xs -> let (mb,xs') = partitionAlts xs in (mb,alt:xs') [] -> (Nothing,[])
danr/tfp1
Lang/FunctionalFO.hs
gpl-3.0
1,881
0
12
487
533
302
231
38
3
{-# LANGUAGE OverloadedStrings #-} {-- KNOWN_ISSUEs 1. address multiple implementations! (resolved in proofObs instead) --} module ToTPTP where import Control.Monad.State import FOOL.AST import qualified FOOL.AST as F import FOOL.TransExpr import FOOL.PrettyAST import FOOL.TPTP import Boogie.TypeChecker import Boogie.AST import qualified Boogie.AST as B import Boogie.Position import Boogie.Util import Boogie.ProofObs import qualified Data.Map as M import Data.List (reverse , nub, sort, partition) import Pretty {- external interface -} toTPTP :: Task -> Context -> Options -> TransState toTPTP task ctx options = snd $ runState (tptpGen task) initState where initState = TransState ctx task ([]) (BConst True) noPos [] options toWP :: Task -> Context -> Options -> TransState toWP task ctx options = snd $ runState (wpGen task) initState where initState = TransState ctx task ([]) (BConst True) noPos [] options data Options = OPT { -- | Exp flags conditionalLetIns :: Bool } type TS a = State TransState a data TransState = TransState { ctx :: Context, task :: Task, tptp :: [Sentence], currentConjecture :: FOOLTerm, pos :: SourcePos, olds :: [(B.Id, B.Type)], flags :: Options } stich :: TransState -> TPTP stich s = TPTP $ (tptp s) ++ [conj] where conj = Conj (snd $ task s) (currentConjecture s) {- state-manipulating interfaces -} setPos spos s = s {pos = spos} updateContext f s = s {ToTPTP.ctx = f $ ToTPTP.ctx s} addSentence :: Sentence -> TS () addSentence sen = modify $ \s -> s {tptp = (tptp s) ++ [sen]} declareType name id t = do lpos <- gets (lineNo . pos) addSentence $ TypeD (name ++ lpos) (F.TypedVar id t) addAxiom name term = do lpos <- gets (lineNo . pos) addSentence $ FOOL.TPTP.Axiom (name ++ lpos) term expandConj :: (FOOLTerm -> FOOLTerm) -> TS () expandConj f = modify $ \s -> s {currentConjecture = f $ currentConjecture s} registerHavoc :: (B.Id, B.Type) -> TS () registerHavoc (id, t) = do t <- resolveSynon t declareType "havoc_" id (transType t) registerOld :: (B.Id, B.Type) -> TS () registerOld (id, t) = do t <- resolveSynon t declareType "old_" ("old_" ++ id) (transType t) modify $ \s -> s { olds = (id, t) : (olds s) } -- core functions -- | tptpGen models VC with Tuple updates tptpGen :: Task -> TS () tptpGen ((Program decls), taske_id) = do mapM_ frontDecl decls mapM_ imperatives decls assignOlds -- | wpGen models traditional VC Gen (weakest precond.) wpGen :: Task -> TS () wpGen ((Program decls), taske_id) = do mapM_ frontDecl decls mapM_ imperativesWP decls assignOlds assignOlds :: TS () assignOlds = do os <- gets olds if null os then return () else let lrs = zip lhss rhss lhss = map (\(id, t) -> F.Var ("old_" ++ id)) os rhss = map (\(id, t) -> F.Var id) os in expandConj (Let lrs) imperativesWP :: Decl -> TS () imperativesWP decl@(Pos pos d) = do modify $ setPos pos case d of ProcedureDecl pid targs formals rets contracts Nothing -> do return () ProcedureDecl pid targs formals rets contracts (Just (localvars, block)) -> do mapM_ localvarTrans $ localvars ++ [rets] q <- gets currentConjecture q' <- wp (reverse $ map (snd . node) block) q modify $ \s -> s {currentConjecture = q'} -- forget localContext with globalContext modify $ updateContext globalContext ImplementationDecl pid targs formals rets bodies -> do return () otherwise -> return () frontDecl :: Decl -> TS () frontDecl decl@(Pos pos d) = do modify $ setPos pos case d of -- | TypeDecl without `value` creates new types; TypeSynonyms are -- not of our interest in TPTP world, any variables with synonym -- types will be translated with their type resolved TypeDecl types -> mapM_ trans types where trans t = case B.tValue t of Nothing -> declareType "ntypd_" (B.tId t) (I) Just r -> return () -- declareType "ntypd_" (B.tId t) (transType r) AxiomDecl e -> do e' <- transExpr' e -- transExpr' resolves typeSynon addAxiom "axmd_" e' ConstantDecl isU ids t _ _ -> do t <- resolveSynon t mapM_ (\id -> declareType "const_" id (transType t)) ids FunctionDecl _ fid targs formals rets b -> do formals' <- mapM (\(id, t) -> do t <- resolveSynon t return (id, t)) formals declareType "func_" fid (FuncType (map (transType . snd) formals') (transType $ snd rets)) case b of Nothing -> return () Just body -> addAxiom (fid ++ "_fbdy_") term where term = F.Quantified F.Forall paras eq eq = Bin Equal (FunApp fid paras) imp imp = transExpr body paras = map (\(t, i) -> translateParameters t i) (zip formals' [1..]) VarDecl idtws -> mapM_ trans idtws -- not really using the "where" clause at the moment where trans lvar = do t <- resolveSynon (B.itwType lvar) declareType "var_" (B.itwId lvar) (transType $ t) ProcedureDecl pid targs formals rets contracts b -> do frontDecl (Pos pos (VarDecl formals)) -- could improve by id; MAYBE move down to `imperatives`? -- frontDecl (Pos pos (VarDecl rets)) -- this is already move to imperatives handleContracts contracts -- [FIXME] make sure Split handles bodies -> [body] ImplementationDecl pid targs formals rets bodies -> do return () -- fill in handleContracts :: [Contract] -> TS () handleContracts contracts = do mapM_ axiomatize requires goal <- conjoin ensures updateEnsure goal where requires = [c | c@(Requires _ _) <- contracts] ensures = [c | c@(Ensures _ _) <- contracts] axiomatize :: Contract -> TS () axiomatize (Requires isFree e) = do term <- transExpr' e addAxiom ("require_axiom") term conjoin :: [Contract] -> TS FOOLTerm conjoin [] = return $ BConst True conjoin [(Ensures isFree e)] = transExpr' e conjoin ((Ensures isF e):cs) = do t <- conjoin cs return $ Bin F.And ((transExpr e)) t updateEnsure :: FOOLTerm -> TS () updateEnsure goal = do modify $ \s -> s {currentConjecture = goal} imperatives :: Decl -> TS () imperatives decl@(Pos pos d) = do modify $ setPos pos case d of ProcedureDecl pid targs formals rets contracts Nothing -> do return () ProcedureDecl pid targs formals rets contracts (Just (localvars, block)) -> do mapM_ localvarTrans $ localvars ++ [rets] mapM_ statementTrans (reverse block) -- forget localContext with globalContext modify $ updateContext globalContext ImplementationDecl pid targs formals rets bodies -> do return () otherwise -> return () transAssign' :: [((B.Id, [[B.Expression]]), B.Expression)] -> TS [(FOOLTerm, FOOLTerm)] transAssign' as = do vars' <- mapM (\(l, r) -> transExpr' r >>= \r' -> return ((F.Var (fst l)), r')) var_as maps' <- mapM (\(l, r) -> transArrayUpdate' l r >>= \r' -> return ((F.Var (fst l)), r')) map_as return $ (vars' ++ maps') where (var_as, map_as) = partition (null . concat . snd . fst) as transArrayUpdate' :: (B.Id, [[B.Expression]]) -> B.Expression -> TS FOOLTerm transArrayUpdate' (id, index) value = do case concat index of [] -> error "" [i] -> do index' <- transExpr' i value' <- transExpr' value return $ Store (F.Var id) index' value' i:is -> do index' <- transExpr' i -- value' <- transExpr' value x <- transExpr' (gen (B.MapSelection (gen (B.Var id)) [i])) y <- transArrayUpdate' ((show (pretty x)), [is]) value -- FIXME_LATTER dirty hacking with show return $ Store (F.Var id) index' y -- | extend context with localContext; notice this is extension -- instead of replacement, use nestedContext instead of localContext localvarTrans :: [IdTypeWhere] -> TS () localvarTrans idtws = do ctx <- gets ToTPTP.ctx modify $ \s -> s {ToTPTP.ctx = nestedContext bindings idts ctx } mapM_ localvarDecl idtws where bindings = M.fromList idts idts = map (\i -> (itwId i, itwType i)) idtws localvarDecl :: IdTypeWhere -> TS () localvarDecl idtw = do t <- resolveSynon (itwType idtw) declareType "localvar_" id (transType t) where id = itwId idtw statementTrans :: LStatement -> TS () statementTrans lst = do modify $ setPos pos case node st of Predicate _attr spec -> do q <- gets currentConjecture e' <- transExpr' $ specExpr spec case specFree spec of True -> do expandConj (Bin Imply e') False -> do expandConj (Bin F.And e') Assign lhss rhss -> do q <- gets currentConjecture lrs <- transAssign' $ zip lhss rhss expandConj (Let lrs) Havoc ids -> do ctx <- gets ToTPTP.ctx q <- gets currentConjecture let idTypes = map (\id -> exprType ctx (gen (B.Var id))) ids lrs = transAssign $ zip lhss rhss lhss = zip ids (repeat [[]]) idts = zip ids idTypes ids' = map (\(id, t) -> havocNaming pos id t) idts rhss = map (\(id, t) -> havocWithType pos id t) idts in do expandConj (Let lrs) mapM_ registerHavoc (zip ids' idTypes) stmt@(B.Call lhss pid args) -> do ctx <- gets ToTPTP.ctx q <- gets currentConjecture let lrs = [(modifiedTuple, rhsTuple)] rhsTuple = Tuple (map F.Var havocNames) havocNames = (map (\(id, t) -> havocNaming pos id t) (zip modifies idTypes)) modifies = nub $ checkStatement4Tuple ctx stmt lhss idTypes = map (\id -> exprType ctx (gen (B.Var id))) modifies idts = zip modifies idTypes ids' = map (\(id, t) -> havocNaming pos id t) idts modifiedTuple = Tuple (map F.Var modifies) -- in case of no postcondition associated with pid, just be BConst True => q assumeCall = Bin Imply post' assumeCall' = Bin Imply (replaceNs (zip (pArgs) (argsNames)) posts) assumeCall'' = Bin Imply (replaceNs (zip (pRets ++ pArgs) (lhss ++ argsNames)) posts) -- take also lhss into account post' = replaceNs (zip modifies ids') posts pArgs = map (\idtw -> itwId idtw) (psigArgs psig) pRets = map (\idtw -> itwId idtw) (psigRets psig) argsNames = reverse $ takeArgName args psig = case M.lookup pid (ctxProcedures ctx) of Nothing -> error $ "Called an unknown procedure: " ++ pid Just psig -> psig posts = case M.lookup pid (ctxProcedures ctx) of Nothing -> error $ "Called an unknown procedure: " ++ pid Just psig -> extractPostCondition $ psigContracts psig in do mapM_ registerHavoc (zip havocNames idTypes) if (null modifies) then expandConj (\conj -> (assumeCall' conj)) else expandConj (\conj -> (Let lrs (assumeCall'' conj))) While c spec b -> do ctx <- gets ToTPTP.ctx q <- gets currentConjecture when (c == B.Wildcard) wildCardCondition let lrs = [(modifiedTuple, rhsTuple)] modifies = nub $ findTuple ctx b modifiedTuple = Tuple (map F.Var modifies) idTypes = map (\id -> exprType ctx (gen (B.Var id))) modifies havocNames = (map (\(id, t) -> havocNaming pos id t) (zip modifies idTypes)) rhsTuple = Tuple (map F.Var havocNames) assumeInv = Bin Imply invar q -- assume inv (second case) invar = Bin F.And (Uni F.Not c') (loopInv spec) c' = case c of B.Wildcard -> F.Var "wildbool" B.Expr ce -> transExpr ce in do expandConj (Bin Imply invar) expandConj (Let lrs) mapM_ registerHavoc (zip havocNames idTypes) If c tb eb -> do ctx <- gets ToTPTP.ctx q <- gets currentConjecture when (c == B.Wildcard) wildCardCondition let c' = case c of B.Wildcard -> F.Var "wildbool" B.Expr c -> transExpr c in case eb of Nothing -> do th <- (mapM sTrans tb) -- th <- (foldM (flip branchTrans) q) (reverse tb) let rhs = ITE c' (compose th modifiedTuple) modifiedTuple -- th modifiedTuple -- modifies = nub $ findTuple ctx tb modifiedTuple = Tuple (map F.Var modifies) lhs = [(modifiedTuple, rhs)] in expandConj (Let lhs) Just eb -> do th <- (mapM sTrans tb) el <- (mapM sTrans eb) let rhs = ITE c' (compose th modifiedTuple) (compose el modifiedTuple) -- not q in the compose modifies = nub $ (findTuple ctx tb) ++ (findTuple ctx eb) modifiedTuple = Tuple (map F.Var modifies) lhs = [(modifiedTuple, rhs)] in expandConj (Let lhs) otherwise -> return () where st = (snd . node) lst pos = position st branchTrans :: LStatement -> FOOLTerm -> TS FOOLTerm branchTrans lst q = do modify $ setPos pos case node st of Assign lhss rhss -> do return $ Let lrs q where lrs = transAssign $ zip lhss rhss Havoc ids -> do ctx <- gets ToTPTP.ctx let idTypes = map (\id -> exprType ctx (gen (B.Var id))) ids lrs = transAssign $ zip lhss rhss lhss = zip ids (repeat [[]]) idts = zip ids idTypes ids' = map (\(id, t) -> havocNaming pos id t) idts rhss = map (\(id, t) -> havocWithType pos id t) idts in do return $ (Let lrs q) If c tb eb -> do ctx <- gets ToTPTP.ctx let c' = case c of B.Wildcard -> F.Var "wildbool" B.Expr c -> transExpr c in case eb of Nothing -> do th <- (foldM (flip branchTrans) q tb) let rhs = ITE c' (th) modifiedTuple modifies = nub $ findTuple ctx tb modifiedTuple = Tuple (map F.Var modifies) in return $ rhs -- Just eb -> do -- th <- (mapM sTrans tb) -- el <- (mapM sTrans eb) -- let rhs = ITE c' (compose th modifiedTuple) (compose el modifiedTuple) -- not q in the compose -- modifies = nub $ findTuple ctx tb -- modifiedTuple = Tuple (map F.Var modifies) -- lhs = [(modifiedTuple, rhs)] in -- return $ (Let lhs) otherwise -> error "" where st = (snd . node) lst pos = position lst -- | translate statement and return the result, without modifing the state sTrans :: LStatement -> TS (FOOLTerm -> FOOLTerm) sTrans lst = do modify $ setPos pos case node st of Predicate _attr spec -> do case specFree spec of True -> do -- expandConj (Bin Imply e) return id False -> do -- expandConj (Bin F.And e) return id where e = transExpr $ specExpr spec Assign lhss rhss -> do return $ Let lrs where lrs = transAssign $ zip lhss rhss Havoc ids -> do ctx <- gets ToTPTP.ctx let idTypes = map (\id -> exprType ctx (gen (B.Var id))) ids lrs = transAssign $ zip lhss rhss lhss = zip ids (repeat [[]]) idts = zip ids idTypes ids' = map (\(id, t) -> havocNaming pos id t) idts rhss = map (\(id, t) -> havocWithType pos id t) idts in do return $ (Let lrs) If c tb eb -> do ctx <- gets ToTPTP.ctx let c' = case c of B.Wildcard -> F.Var "wildbool" B.Expr c -> transExpr c in case eb of Nothing -> do th <- (mapM sTrans tb) let rhs = \q -> ITE c' (compose th q) modifiedTuple modifies = nub $ findTuple ctx tb modifiedTuple = Tuple (map F.Var modifies) in return $ (rhs) Just eb -> do th <- (mapM sTrans tb) el <- (mapM sTrans eb) let rhs = ITE c' (compose th modifiedTuple) (compose el modifiedTuple) -- not q in the compose modifies = nub $ findTuple ctx tb modifiedTuple = Tuple (map F.Var modifies) lhs = [(modifiedTuple, rhs)] in return $ (Let lhs) -- [FIXME] Call Call lhss pid args -> do ctx <- gets ToTPTP.ctx let lrs = [(modifiedTuple, rhsTuple)] rhsTuple = Tuple (map F.Var havocNames) ids' = map (\(id, t) -> havocNaming pos id t) idts idts = zip modifies idTypes havocNames = (map (\(id, t) -> havocNaming pos id t) (zip modifies idTypes)) modifies = nub $ checkStatement4Tuple ctx (node st) lhss idTypes = map (\id -> exprType ctx (gen (B.Var id))) modifies modifiedTuple = Tuple (map F.Var modifies) -- in case of no postcondition associated with pid, just be BConst True => q argsTypes = map (\e -> exprType ctx e) args argsNames = reverse $ takeArgName args assumeCall = Bin Imply post' --FIXME assumeCall' = Bin Imply (replaceNs (zip pArgs argsNames) posts) assumeCall'' = Bin Imply (replaceNs (zip (pRets ++ pArgs) (lhss ++ argsNames)) posts) -- take also lhss into account pRets = map (\idtw -> itwId idtw) (psigRets psig) post' = replaceNs (zip modifies ids') posts pArgs = map (\idtw -> itwId idtw) (psigArgs psig) psig = case M.lookup pid (ctxProcedures ctx) of Nothing -> error $ "Called an unknown procedure: " ++ pid Just psig -> psig posts = extractPostCondition $ psigContracts psig in do mapM_ registerHavoc (zip ids' idTypes) expandConj assumeCall'' return (\conj -> (Let lrs conj)) -- if (null modifies) -- then return (\conj -> (assumeCall' conj)) -- else return (\conj -> (Let lrs (assumeCall'' conj))) While c spec b -> do ctx <- gets ToTPTP.ctx q <- gets currentConjecture when (c == B.Wildcard) wildCardCondition let lrs = [(modifiedTuple, rhsTuple)] modifies = nub $ findTuple ctx b modifiedTuple = Tuple (map F.Var modifies) idTypes = map (\id -> exprType ctx (gen (B.Var id))) modifies havocNames = (map (\(id, t) -> havocNaming pos id t) (zip modifies idTypes)) rhsTuple = Tuple (map F.Var havocNames) assumeInv = Bin Imply invar q -- assume inv (second case) invar = Bin F.And (Uni F.Not c') (loopInv spec) c' = case c of B.Wildcard -> F.Var "wildbool" B.Expr ce -> transExpr ce in do mapM_ registerHavoc (zip havocNames idTypes) expandConj (Bin Imply invar) return $ \q -> Let lrs q otherwise -> error $ "[ToTPTP] sTrans : otherwise" ++ (show $ pretty (node st)) where st = (snd . node) lst pos = position lst takeArgName :: [B.Expression] -> [String] takeArgName es = foldr (\(Pos pos e) ids -> case e of B.Var id -> ids ++ [id] otherwise -> ids ) [] es replaceNs :: [(String, String)] -> FOOLTerm -> FOOLTerm replaceNs fts term = foldr (\ft ter -> replaceNames ft ter) term fts replaceNames :: (String, String) -> FOOLTerm -> FOOLTerm replaceNames (from, to) term = case term of IConst _ -> term BConst _ -> term F.Var s -> if s == from then F.Var to else term F.TypedVar s t ->if s == from then F.TypedVar to t else term ITE c thn els -> ITE c' thn' els' where c' = replace c thn' = replace thn els' = replace els Tuple terms -> Tuple (map replace terms) FunApp fun terms -> FunApp fun (map replace terms) Store arr a b -> Store (replace arr) (replace a) (replace b) Select arr i -> Select (replace arr) (replace i) F.Bin op a b -> F.Bin op (replace a) (replace b) F.Uni op a -> F.Uni op (replace a) F.Quantified op vars term -> F.Quantified op (map replace vars) (replace term) Let lst term -> Let lst' (replace term) where lst' = map (\(a, b) -> (replace a, replace b)) lst where replace = replaceNames (from, to) translateParameters :: B.FArg -> Int -> FOOLTerm translateParameters (Nothing, t) i = F.TypedVar ("para_" ++ show i) (transType t) translateParameters (Just id, t) _ = F.TypedVar id (transType t) -- | Types in the node can refer to TypeSynonyms; resolveSynon returns -- the resolved type (addressing maps' type in TPTP) resolveSynon :: B.Type -> TS B.Type resolveSynon t = do case t of B.IdType tid _ -> do ctx <- gets ToTPTP.ctx case (M.lookup tid (ctxTypeSynonyms ctx)) of Nothing -> return t Just (_formals, t') -> return t' otherwise -> return t -- | Stateful version of transExpr, for resolving typesyns transExpr' :: Expression -> TS FOOLTerm transExpr' e = case node e of B.Literal v -> return $ translateValue v B.Var id -> return $ F.Var id B.Application id exprs -> return $ FunApp id terms where terms = map transExpr exprs B.MapSelection m i -> case (reverse i) of [] -> error "Expression: MapSelect without index" [i] -> do i' <- transExpr' i m' <- transExpr' m return $ Select m' i' --(transExpr m) (transExpr i) (i:is) -> do i' <- transExpr' i s <- (transExpr' (Pos (position e) $ B.MapSelection m is)) -- return $ Select (transExpr (Pos (position e) $ B.MapSelection m is)) (transExpr i) return $ Select s i' B.MapUpdate m ix rhs -> case (reverse ix) of [] -> error "Expression: MapUpdate without index" [i] -> do m' <- transExpr' m rhs' <- transExpr' rhs i' <- transExpr' i return $ Store m' i' rhs' (i:is) -> do m' <- transExpr' m rhs' <- transExpr' rhs i' <- transExpr' i let m'' = Pos (position e) (B.MapSelection m [i]) in return $ Store m' i' (transExpr $ Pos (position e) $ B.MapUpdate m'' is rhs) B.IfExpr cond tb fb -> do c' <- transExpr' cond tb' <- transExpr' tb fb' <- transExpr' fb return $ ITE c' tb' fb' B.UnaryExpression unop e -> do e' <- transExpr' e return $ Uni op' e' where op' = translateUnOp unop B.BinaryExpression binop e1 e2 -> do e1' <- transExpr' e1 e2' <- transExpr' e2 return $ Bin op' e1' e2' where op' = translateBinOp binop e1' = transExpr e1 e2' = transExpr e2 B.Quantified f qop id bound_vars expr -> do bound_vars' <- mapM (\(id, t) -> resolveSynon t >>= \t' -> return (id, t')) bound_vars return $ transExpr $ Pos (position e) $ B.Quantified f qop id bound_vars' expr -- In Boogie's two-state contexts, old(var) is always referring to -- the value of var before invocation of this procedure (a.k.a all -- the way back) Old e' -> do ctx <- gets ToTPTP.ctx let typ = exprType ctx e' in case (node e') of B.Var id -> do registerOld (id, typ) return $ F.Var ("old_" ++ id) otherwise -> do error "[ToTPTP] transExpr' old used on non-var expr" otherwise -> do error "[ToTPTP] transExpr' case otherwise" loopInv :: [B.SpecClause] -> FOOLTerm loopInv specs = case invs of [] -> BConst True -- No invariants inv:invs -> foldr (\inv -> Bin F.And (transExpr (B.specExpr inv))) (transExpr (B.specExpr inv)) invs where isInv s = case B.specType s of B.LoopInvariant -> True _ -> False invs = filter isInv specs findTuple :: Context -> B.Block -> [B.Id] findTuple ctx block = foldr (checkStatement4Tuple ctx) [] block' where block' = map B.stripToStatement block checkStatement4Tuple :: Context -> B.BareStatement -> [B.Id] -> [B.Id] checkStatement4Tuple ctx bst tup = case bst of B.Havoc ids -> ids ++ tup B.Assign ids _ -> ids' ++ tup where ids' = map fst ids B.While _ _ b -> (findTuple ctx b) ++ tup B.If _ tb (Just eb) -> (findTuple ctx tb ++ findTuple ctx eb) ++ tup B.If _ tb Nothing -> (findTuple ctx tb) ++ tup B.Call lhss pid args -> lhss ++ modifies ++ tup where modifies = case M.lookup pid (ctxProcedures ctx) of Nothing -> error $ "Called an unknown procedure: " ++ pid Just psig -> findModifiesFromContracts $ psigContracts psig _ -> tup -- | Procedures can only modify (global variables) as stated in their contract -- along with their local variables and their return variables -- Hence in a havoc_procedure_modifies tuple, we only need to find the variables stated in the contract findModifiesFromContracts :: [B.Contract] -> [B.Id] findModifiesFromContracts contracts = foldr f [] contracts where f contract ids = case contract of B.Modifies _ mods -> ids ++ mods _ -> ids wildCardCondition :: TS () wildCardCondition = declareType "wildCondition" "wildbool" Boolean extractPostCondition :: [B.Contract] -> FOOLTerm extractPostCondition [] = BConst True extractPostCondition (c:cs) = case c of B.Ensures free e -> Bin F.And (transExpr e) $ extractPostCondition cs _ -> extractPostCondition cs {- naming stuffs -} havocWithType :: SourcePos -> String -> B.Type -> B.Expression havocWithType pos varId t = attachPos pos (B.Var name) where name = havocNaming pos varId t havocNaming :: SourcePos -> String -> B.Type -> String havocNaming pos varId t@(B.MapType _ _ _) = "hv_" ++ l ++ "_" ++ varId ++ "_" ++ mapType t where l = lineNo pos havocNaming pos varId t = "hv_" ++ l ++ "_" ++ varId ++ "_" ++ show t where l = lineNo pos mapType :: B.Type -> String mapType (B.MapType _ domains range) = concatMap (\t -> show t ++ "_") domains ++ "_" ++ show range compose :: [a -> a] -> a -> a compose = foldr (.) id -- | weakest precondition wp_s :: Statement -> FOOLTerm -> TS FOOLTerm wp_s (Pos pos stmt) q = do case stmt of Predicate _attr spec -> do e <- transExpr' $ specExpr spec case specFree spec of True -> return $ Bin Imply e q False -> return $ Bin F.And e q Assign lhss rhss -> do lrs <- transAssign' $ zip lhss rhss return $ Let lrs q Havoc ids -> do ctx <- gets ToTPTP.ctx let idTypes = map (\id -> exprType ctx (gen (B.Var id))) ids lrs = transAssign $ zip lhss rhss lhss = zip ids (repeat [[]]) idts = zip ids idTypes ids' = map (\(id, t) -> havocNaming pos id t) idts rhss = map (\(id, t) -> havocWithType pos id t) idts in do mapM_ registerHavoc (zip ids' idTypes) return $ Let lrs q If c tb eb -> do ctx <- gets ToTPTP.ctx c' <- case c of B.Wildcard -> return $ F.Var "wildbool" B.Expr c -> transExpr' c case eb of Nothing -> do tb' <- wp (reverse $ map (snd . node) tb) q return $ ITE c' tb' q Just eb -> do tb' <- wp (reverse $ map (snd . node) tb) q eb' <- wp (reverse $ map (snd . node) eb) q return $ ITE c' tb' eb' While c spec b -> do ctx <- gets ToTPTP.ctx c' <- case c of B.Wildcard -> return $ F.Var "wildbool" B.Expr c -> transExpr' c let lrs = transAssign $ zip lhss rhss lhss = zip modifies (repeat [[]]) idts = zip modifies idTypes idTypes = map (\id -> exprType ctx (gen (B.Var id))) modifies ids' = map (\(id, t) -> havocNaming pos id t) idts rhss = map (\(id, t) -> havocWithType pos id t) idts modifies = nub $ findTuple ctx b assumeInv = Bin Imply invar q -- assume inv (second case) invar = Bin F.And (Uni F.Not c') (loopInv spec) in do mapM_ registerHavoc (zip ids' idTypes) return $ Let lrs assumeInv Call lhss pid args -> do ctx <- gets ToTPTP.ctx let modifies = nub $ checkStatement4Tuple ctx stmt lhss lrs = transAssign $ zip lhss' rhss lhss' = zip modifies (repeat [[]]) idts = zip modifies idTypes idTypes = map (\id -> exprType ctx (gen (B.Var id))) modifies ids' = map (\(id, t) -> havocNaming pos id t) idts rhss = map (\(id, t) -> havocWithType pos id t) idts post' = replaceNs (zip modifies ids') posts assumeCall = Bin Imply post' q -- in case of no postcondition associated with pid, just be BConst True => q posts = case M.lookup pid (ctxProcedures ctx) of Nothing -> error $ "Called an unknown procedure: " ++ pid Just psig -> extractPostCondition $ psigContracts psig in do mapM_ registerHavoc (zip ids' idTypes) return $ Let lrs assumeCall otherwise -> error "otherwise" wp' :: [Statement] -> FOOLTerm -> TS FOOLTerm wp' stmts q = foldM (flip wp_s) q stmts' where stmts' = reverse stmts wp :: [Statement] -> FOOLTerm -> TS FOOLTerm wp stmts q = case stmts' of [] -> return q s:ss -> do q' <- wp_s s q wp ss q' where stmts' = stmts
emptylambda/BLT
src/ToTPTP.hs
gpl-3.0
29,302
15
30
8,846
10,357
5,162
5,195
639
16
{-# 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.GamesConfiguration.LeaderboardConfigurations.List -- 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) -- -- Returns a list of the leaderboard configurations in this application. -- -- /See:/ <https://developers.google.com/games/ Google Play Game Services Publishing API Reference> for @gamesConfiguration.leaderboardConfigurations.list@. module Network.Google.Resource.GamesConfiguration.LeaderboardConfigurations.List ( -- * REST Resource LeaderboardConfigurationsListResource -- * Creating a Request , leaderboardConfigurationsList , LeaderboardConfigurationsList -- * Request Lenses , lclXgafv , lclUploadProtocol , lclAccessToken , lclUploadType , lclApplicationId , lclPageToken , lclMaxResults , lclCallback ) where import Network.Google.GamesConfiguration.Types import Network.Google.Prelude -- | A resource alias for @gamesConfiguration.leaderboardConfigurations.list@ method which the -- 'LeaderboardConfigurationsList' request conforms to. type LeaderboardConfigurationsListResource = "games" :> "v1configuration" :> "applications" :> Capture "applicationId" Text :> "leaderboards" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Int32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] LeaderboardConfigurationListResponse -- | Returns a list of the leaderboard configurations in this application. -- -- /See:/ 'leaderboardConfigurationsList' smart constructor. data LeaderboardConfigurationsList = LeaderboardConfigurationsList' { _lclXgafv :: !(Maybe Xgafv) , _lclUploadProtocol :: !(Maybe Text) , _lclAccessToken :: !(Maybe Text) , _lclUploadType :: !(Maybe Text) , _lclApplicationId :: !Text , _lclPageToken :: !(Maybe Text) , _lclMaxResults :: !(Maybe (Textual Int32)) , _lclCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LeaderboardConfigurationsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lclXgafv' -- -- * 'lclUploadProtocol' -- -- * 'lclAccessToken' -- -- * 'lclUploadType' -- -- * 'lclApplicationId' -- -- * 'lclPageToken' -- -- * 'lclMaxResults' -- -- * 'lclCallback' leaderboardConfigurationsList :: Text -- ^ 'lclApplicationId' -> LeaderboardConfigurationsList leaderboardConfigurationsList pLclApplicationId_ = LeaderboardConfigurationsList' { _lclXgafv = Nothing , _lclUploadProtocol = Nothing , _lclAccessToken = Nothing , _lclUploadType = Nothing , _lclApplicationId = pLclApplicationId_ , _lclPageToken = Nothing , _lclMaxResults = Nothing , _lclCallback = Nothing } -- | V1 error format. lclXgafv :: Lens' LeaderboardConfigurationsList (Maybe Xgafv) lclXgafv = lens _lclXgafv (\ s a -> s{_lclXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). lclUploadProtocol :: Lens' LeaderboardConfigurationsList (Maybe Text) lclUploadProtocol = lens _lclUploadProtocol (\ s a -> s{_lclUploadProtocol = a}) -- | OAuth access token. lclAccessToken :: Lens' LeaderboardConfigurationsList (Maybe Text) lclAccessToken = lens _lclAccessToken (\ s a -> s{_lclAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). lclUploadType :: Lens' LeaderboardConfigurationsList (Maybe Text) lclUploadType = lens _lclUploadType (\ s a -> s{_lclUploadType = a}) -- | The application ID from the Google Play developer console. lclApplicationId :: Lens' LeaderboardConfigurationsList Text lclApplicationId = lens _lclApplicationId (\ s a -> s{_lclApplicationId = a}) -- | The token returned by the previous request. lclPageToken :: Lens' LeaderboardConfigurationsList (Maybe Text) lclPageToken = lens _lclPageToken (\ s a -> s{_lclPageToken = a}) -- | The maximum number of resource configurations to return in the response, -- used for paging. For any response, the actual number of resources -- returned may be less than the specified \`maxResults\`. lclMaxResults :: Lens' LeaderboardConfigurationsList (Maybe Int32) lclMaxResults = lens _lclMaxResults (\ s a -> s{_lclMaxResults = a}) . mapping _Coerce -- | JSONP lclCallback :: Lens' LeaderboardConfigurationsList (Maybe Text) lclCallback = lens _lclCallback (\ s a -> s{_lclCallback = a}) instance GoogleRequest LeaderboardConfigurationsList where type Rs LeaderboardConfigurationsList = LeaderboardConfigurationListResponse type Scopes LeaderboardConfigurationsList = '["https://www.googleapis.com/auth/androidpublisher"] requestClient LeaderboardConfigurationsList'{..} = go _lclApplicationId _lclXgafv _lclUploadProtocol _lclAccessToken _lclUploadType _lclPageToken _lclMaxResults _lclCallback (Just AltJSON) gamesConfigurationService where go = buildClient (Proxy :: Proxy LeaderboardConfigurationsListResource) mempty
brendanhay/gogol
gogol-games-configuration/gen/Network/Google/Resource/GamesConfiguration/LeaderboardConfigurations/List.hs
mpl-2.0
6,279
0
20
1,447
887
512
375
130
1
module Data.GI.GIR.Arg ( Arg(..) , Direction(..) , Scope(..) , parseArg , parseTransfer ) where import Data.Monoid ((<>)) import Data.Text (Text) import Data.GI.GIR.BasicTypes (Transfer(..), Type) import Data.GI.GIR.Parser import Data.GI.GIR.Type (parseType) data Direction = DirectionIn | DirectionOut | DirectionInout deriving (Show, Eq, Ord) data Scope = ScopeTypeInvalid | ScopeTypeCall | ScopeTypeAsync | ScopeTypeNotified deriving (Show, Eq, Ord) data Arg = Arg { argCName :: Text, -- ^ "C" name for the argument. For a -- escaped name valid in Haskell code, use -- `GI.SymbolNaming.escapedArgName`. argType :: Type, direction :: Direction, mayBeNull :: Bool, argDoc :: Documentation, argScope :: Scope, argClosure :: Int, argDestroy :: Int, argCallerAllocates :: Bool, transfer :: Transfer } deriving (Show, Eq, Ord) parseTransfer :: Parser Transfer parseTransfer = getAttr "transfer-ownership" >>= \case "none" -> return TransferNothing "container" -> return TransferContainer "full" -> return TransferEverything t -> parseError $ "Unknown transfer type \"" <> t <> "\"" parseScope :: Text -> Parser Scope parseScope "call" = return ScopeTypeCall parseScope "async" = return ScopeTypeAsync parseScope "notified" = return ScopeTypeNotified parseScope s = parseError $ "Unknown scope type \"" <> s <> "\"" parseDirection :: Text -> Parser Direction parseDirection "in" = return DirectionIn parseDirection "out" = return DirectionOut parseDirection "inout" = return DirectionInout parseDirection d = parseError $ "Unknown direction \"" <> d <> "\"" parseArg :: Parser Arg parseArg = do name <- getAttr "name" ownership <- parseTransfer scope <- optionalAttr "scope" ScopeTypeInvalid parseScope d <- optionalAttr "direction" DirectionIn parseDirection closure <- optionalAttr "closure" (-1) parseIntegral destroy <- optionalAttr "destroy" (-1) parseIntegral nullable <- optionalAttr "nullable" False parseBool callerAllocates <- optionalAttr "caller-allocates" False parseBool t <- parseType doc <- parseDocumentation return $ Arg { argCName = name , argType = t , argDoc = doc , direction = d , mayBeNull = nullable , argScope = scope , argClosure = closure , argDestroy = destroy , argCallerAllocates = callerAllocates , transfer = ownership }
ford-prefect/haskell-gi
lib/Data/GI/GIR/Arg.hs
lgpl-2.1
2,751
0
11
816
647
356
291
-1
-1
-- Prelude module is implicitly imported -- pi = Prelude.pi func x = x * x * pi
ocozalp/Haskellbook
chapter2/cmp3.hs
unlicense
80
0
6
18
19
10
9
1
1
{-# LANGUAGE OverloadedStrings #-} import Data.Aeson.Types import Data.Conduit import qualified Data.Conduit.List as CL import Data.Conduit.Network import Data.Time.Clock import Data.Time.Format import Network.JsonRpc import System.Locale data TimeReq = TimeReq data TimeRes = TimeRes UTCTime instance FromRequest TimeReq where paramsParser "time" = Just $ const $ return TimeReq paramsParser _ = Nothing instance ToJSON TimeRes where toJSON (TimeRes t) = toJSON $ formatTime defaultTimeLocale "%c" t srv :: AppConduits () () TimeRes TimeReq () () IO -> IO () srv (src, snk) = src $= CL.mapM respond $$ snk respond :: IncomingMsg () TimeReq () () -> IO (Message () () TimeRes) respond (IncomingMsg (MsgRequest (Request ver _ TimeReq i)) Nothing) = do t <- getCurrentTime return $ MsgResponse (Response ver (TimeRes t) i) respond (IncomingError e) = return $ MsgError e respond (IncomingMsg (MsgError e) _) = return $ MsgError $ e respond _ = undefined main :: IO () main = tcpServer V2 (serverSettings 31337 "127.0.0.1") srv
anton-dessiatov/json-rpc
examples/time-server.hs
unlicense
1,066
0
12
197
395
203
192
28
1
module WaveMachine.Audio.Volume where import WaveMachine.Audio.Waves applyVolume :: Double -> WaveFunction -> WaveFunction applyVolume volume orig t = orig t * volume
apoco/wave-machine
src/WaveMachine/Audio/Volume.hs
unlicense
169
0
6
23
45
25
20
4
1
module Main where genretateAMonotonicWalls :: [Integer] genretateAMonotonicWalls = filter (\pof2 -> 0 == (pof2 - 1) `mod` 3) $ powerOfTwo 2 -- 2^n generator powerOfTwo :: Integer -> [Integer] powerOfTwo n = n : (powerOfTwo $ n * 2) printList :: (Show a) => [a] -> IO () printList [] = return () printList (x:xs) = (putStrLn $ show x) >> printList xs main :: IO () main = printList genretateAMonotonicWalls
shashikiranrp/Collatz
Main.hs
apache-2.0
411
0
12
76
179
96
83
10
1
{-# LANGUAGE TupleSections #-} import AdventOfCode (readInputFile) import Control.Arrow (second) runDeer :: (Int, Int, Int) -> [Int] runDeer = (0 : ) . runDeerFrom 0 runDeerFrom :: Int -> (Int, Int, Int) -> [Int] runDeerFrom start d@(speed, run, rest) = running ++ resting ++ runDeerFrom end d where running = [start + speed, start + speed * 2 .. end] resting = replicate rest end end = start + speed * run race :: Int -> [[Int]] -> [(Int, Int)] race n deer = map (second head) results where results = iterate stepRace (map (0,) deer) !! n stepRace :: [(Int, [Int])] -> [(Int, [Int])] stepRace deer = map awardLead deer' where deer' = map (second tail) deer lead = maximum (map (head . snd) deer') awardLead (s, l) = (if head l == lead then succ s else s, l) parseDeer :: String -> (Int, Int, Int) parseDeer s = case words s of [_, "can", "fly", a, "km/s", "for", b, "seconds,", "but", "then", "must", "rest", "for", c, "seconds."] -> (read a, read b, read c) _ -> error ("bad deer: " ++ s) main :: IO () main = do s <- readInputFile let deer = map (runDeer . parseDeer) (lines s) results = race 2503 deer print (maximum (map snd results)) print (maximum (map fst results))
petertseng/adventofcode-hs
bin/14_reindeer_race.hs
apache-2.0
1,238
0
12
283
587
322
265
29
2
import System.IO import Control.Monad import Data.List import Data.Ord main :: IO () main = do hSetBuffering stdout NoBuffering loop loop :: IO () loop = do [sx, sy] <- fmap (map read . words) getLine :: IO [Int] mhs <- replicateM 8 $ fmap read getLine :: IO [Int] let xmax = snd $ maximumBy (comparing fst) $ zip mhs [0..] putStrLn $ if sx == xmax then "FIRE" else "HOLD" loop
lpenz/codingame-haskell-solutions
puzzles/0-easy/kirks-quest-the-descent/solution.hs
apache-2.0
409
0
14
103
183
91
92
15
2
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QColorDialog.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:16 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QColorDialog ( qColorDialogCustomColor ,qColorDialogCustomCount ,QqColorDialogGetColor(..) ,QqColorDialogGetRgba(..) ,qColorDialogSetCustomColor ,qColorDialogSetStandardColor ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui qColorDialogCustomColor :: ((Int)) -> IO (Int) qColorDialogCustomColor (x1) = withUnsignedIntResult $ qtc_QColorDialog_customColor (toCInt x1) foreign import ccall "qtc_QColorDialog_customColor" qtc_QColorDialog_customColor :: CInt -> IO CUInt qColorDialogCustomCount :: (()) -> IO (Int) qColorDialogCustomCount () = withIntResult $ qtc_QColorDialog_customCount foreign import ccall "qtc_QColorDialog_customCount" qtc_QColorDialog_customCount :: IO CInt class QqColorDialogGetColor x1 where qColorDialogGetColor :: x1 -> IO (QColor ()) instance QqColorDialogGetColor (()) where qColorDialogGetColor () = withQColorResult $ qtc_QColorDialog_getColor foreign import ccall "qtc_QColorDialog_getColor" qtc_QColorDialog_getColor :: IO (Ptr (TQColor ())) instance QqColorDialogGetColor ((QColor t1)) where qColorDialogGetColor (x1) = withQColorResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QColorDialog_getColor1 cobj_x1 foreign import ccall "qtc_QColorDialog_getColor1" qtc_QColorDialog_getColor1 :: Ptr (TQColor t1) -> IO (Ptr (TQColor ())) instance QqColorDialogGetColor ((QColor t1, QWidget t2)) where qColorDialogGetColor (x1, x2) = withQColorResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QColorDialog_getColor2 cobj_x1 cobj_x2 foreign import ccall "qtc_QColorDialog_getColor2" qtc_QColorDialog_getColor2 :: Ptr (TQColor t1) -> Ptr (TQWidget t2) -> IO (Ptr (TQColor ())) class QqColorDialogGetRgba x1 where qColorDialogGetRgba :: x1 -> IO (Int) instance QqColorDialogGetRgba (()) where qColorDialogGetRgba () = withUnsignedIntResult $ qtc_QColorDialog_getRgba foreign import ccall "qtc_QColorDialog_getRgba" qtc_QColorDialog_getRgba :: IO CUInt instance QqColorDialogGetRgba ((Int)) where qColorDialogGetRgba (x1) = withUnsignedIntResult $ qtc_QColorDialog_getRgba1 (toCUInt x1) foreign import ccall "qtc_QColorDialog_getRgba1" qtc_QColorDialog_getRgba1 :: CUInt -> IO CUInt qColorDialogSetCustomColor :: ((Int, Int)) -> IO () qColorDialogSetCustomColor (x1, x2) = qtc_QColorDialog_setCustomColor (toCInt x1) (toCUInt x2) foreign import ccall "qtc_QColorDialog_setCustomColor" qtc_QColorDialog_setCustomColor :: CInt -> CUInt -> IO () qColorDialogSetStandardColor :: ((Int, Int)) -> IO () qColorDialogSetStandardColor (x1, x2) = qtc_QColorDialog_setStandardColor (toCInt x1) (toCUInt x2) foreign import ccall "qtc_QColorDialog_setStandardColor" qtc_QColorDialog_setStandardColor :: CInt -> CUInt -> IO () instance QaddAction (QColorDialog ()) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QColorDialog_addAction cobj_x0 cobj_x1 foreign import ccall "qtc_QColorDialog_addAction" qtc_QColorDialog_addAction :: Ptr (TQColorDialog a) -> Ptr (TQAction t1) -> IO () instance QaddAction (QColorDialogSc a) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QColorDialog_addAction cobj_x0 cobj_x1 instance Qmove (QColorDialog ()) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QColorDialog_move1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QColorDialog_move1" qtc_QColorDialog_move1 :: Ptr (TQColorDialog a) -> CInt -> CInt -> IO () instance Qmove (QColorDialogSc a) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QColorDialog_move1 cobj_x0 (toCInt x1) (toCInt x2) instance Qmove (QColorDialog ()) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QColorDialog_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QColorDialog_move_qth" qtc_QColorDialog_move_qth :: Ptr (TQColorDialog a) -> CInt -> CInt -> IO () instance Qmove (QColorDialogSc a) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QColorDialog_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y instance Qqmove (QColorDialog ()) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QColorDialog_move cobj_x0 cobj_x1 foreign import ccall "qtc_QColorDialog_move" qtc_QColorDialog_move :: Ptr (TQColorDialog a) -> Ptr (TQPoint t1) -> IO () instance Qqmove (QColorDialogSc a) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QColorDialog_move cobj_x0 cobj_x1 instance Qrepaint (QColorDialog ()) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QColorDialog_repaint cobj_x0 foreign import ccall "qtc_QColorDialog_repaint" qtc_QColorDialog_repaint :: Ptr (TQColorDialog a) -> IO () instance Qrepaint (QColorDialogSc a) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QColorDialog_repaint cobj_x0 instance Qrepaint (QColorDialog ()) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QColorDialog_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QColorDialog_repaint2" qtc_QColorDialog_repaint2 :: Ptr (TQColorDialog a) -> CInt -> CInt -> CInt -> CInt -> IO () instance Qrepaint (QColorDialogSc a) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QColorDialog_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance Qrepaint (QColorDialog ()) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QColorDialog_repaint1 cobj_x0 cobj_x1 foreign import ccall "qtc_QColorDialog_repaint1" qtc_QColorDialog_repaint1 :: Ptr (TQColorDialog a) -> Ptr (TQRegion t1) -> IO () instance Qrepaint (QColorDialogSc a) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QColorDialog_repaint1 cobj_x0 cobj_x1 instance Qresize (QColorDialog ()) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QColorDialog_resize1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QColorDialog_resize1" qtc_QColorDialog_resize1 :: Ptr (TQColorDialog a) -> CInt -> CInt -> IO () instance Qresize (QColorDialogSc a) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QColorDialog_resize1 cobj_x0 (toCInt x1) (toCInt x2) instance Qqresize (QColorDialog ()) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QColorDialog_resize cobj_x0 cobj_x1 foreign import ccall "qtc_QColorDialog_resize" qtc_QColorDialog_resize :: Ptr (TQColorDialog a) -> Ptr (TQSize t1) -> IO () instance Qqresize (QColorDialogSc a) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QColorDialog_resize cobj_x0 cobj_x1 instance Qresize (QColorDialog ()) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QColorDialog_resize_qth cobj_x0 csize_x1_w csize_x1_h foreign import ccall "qtc_QColorDialog_resize_qth" qtc_QColorDialog_resize_qth :: Ptr (TQColorDialog a) -> CInt -> CInt -> IO () instance Qresize (QColorDialogSc a) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QColorDialog_resize_qth cobj_x0 csize_x1_w csize_x1_h instance QsetGeometry (QColorDialog ()) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QColorDialog_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QColorDialog_setGeometry1" qtc_QColorDialog_setGeometry1 :: Ptr (TQColorDialog a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QColorDialogSc a) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QColorDialog_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance QqsetGeometry (QColorDialog ()) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QColorDialog_setGeometry cobj_x0 cobj_x1 foreign import ccall "qtc_QColorDialog_setGeometry" qtc_QColorDialog_setGeometry :: Ptr (TQColorDialog a) -> Ptr (TQRect t1) -> IO () instance QqsetGeometry (QColorDialogSc a) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QColorDialog_setGeometry cobj_x0 cobj_x1 instance QsetGeometry (QColorDialog ()) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QColorDialog_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h foreign import ccall "qtc_QColorDialog_setGeometry_qth" qtc_QColorDialog_setGeometry_qth :: Ptr (TQColorDialog a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QColorDialogSc 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_QColorDialog_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h instance QsetMouseTracking (QColorDialog ()) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QColorDialog_setMouseTracking cobj_x0 (toCBool x1) foreign import ccall "qtc_QColorDialog_setMouseTracking" qtc_QColorDialog_setMouseTracking :: Ptr (TQColorDialog a) -> CBool -> IO () instance QsetMouseTracking (QColorDialogSc a) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QColorDialog_setMouseTracking cobj_x0 (toCBool x1)
keera-studios/hsQt
Qtc/Gui/QColorDialog.hs
bsd-2-clause
10,788
0
13
1,709
3,443
1,787
1,656
-1
-1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} ------------------------------------------------------------------------------ module OpenArms.Types.Need ( -- * Types Need (..) , columnOffsetsNeed , tableOfNeed , need , insertNeed , insertQueryNeed , selectNeed , updateNeed , fromSqlOfNeed , toSqlOfNeed , id' , name' ) where ------------------------------------------------------------------------------ import OpenArms.Util ------------------------------------------------------------------------------ $(defineTable "need")
dmjio/openarms
src/OpenArms/Types/Need.hs
bsd-2-clause
697
0
7
161
71
47
24
19
0
-- Copyright (c) 2014 Eric McCorkle. All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- 3. Neither the name of the author nor the names of any contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS -- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT -- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -- SUCH DAMAGE. {-# OPTIONS_GHC -Wall -Werror -funbox-strict-fields #-} -- | Functionality for traversing an 'Enumeration'. -- -- This module provides a typeclass, 'Traversal', which represents a -- traversal scheme for 'Enumeration's. Traversals should be largely -- independent of the 'Enumeration', though some variants like -- 'Prioritized' cannot be wholly independent. -- -- Three 'Traversal' instances are provided by this module: -- 'DepthFirst', 'BreadthFirst', and 'Prioritized'. All traversals -- work by maintaining a set of positions, which consist of an -- 'Enumeration' and an index (the next value to give as a first path -- element). At each step, some position is \"expanded\" by replacing -- it with two positions: one with the index as an additional prefix -- element, and one with the index incremented. -- -- 'DepthFirst' is a simple depth-first scheme. It is not guaranteed -- to reach all elements, and in some 'Enumeration's, it may never -- produce an answer. -- -- 'BreadthFirst' is a breadth-first scheme, which tends to be -- better-behaved than 'DepthFirst'. It explores paths in ascending -- order of path length. For 'Enumeration's with infinite-sized -- branches, its behavior is not strictly breadth-first (as this would -- never yield an answer), but it should still behave well for this -- case. -- -- 'Prioritized' is a scheme that uses a scoring function to rank -- paths. At each step, it will select the \"best\" (highest-ranked) -- option and expand it. module Data.Enumeration.Traversal( Traversal(..), DepthFirst, BreadthFirst, Prioritized, scoring, mkPrioritizedTraversal ) where import Data.Enumeration import Data.Enumeration.Traversal.Class import Data.Heap(MaxPrioHeap) import Data.Sequence(Seq, (<|), (|>), ViewL(..), viewl) import qualified Data.Heap as Heap import qualified Data.Sequence as Sequence -- | Depth-first traversal. Note that this style of traversal is not -- guaranteed to be complete (it may deep-dive and never visit some -- possibilities). However, this implementation should continue -- producing results even with infinite-sized branches, so long as the -- depth of any one path isn't too great. newtype DepthFirst ty = DepthFirst { dfStack :: [(Enumeration ty, Integer)] } instance Traversal DepthFirst where mkTraversal enum = DepthFirst { dfStack = [(enum, 0)] } getNext DepthFirst { dfStack = [] } = Nothing getNext DepthFirst { dfStack = (enum, curr) : rest } = case numBranches enum of -- For a leaf, produce a result Just 0 -> Just (fromPath enum [], prefix enum, DepthFirst { dfStack = rest }) Just high -- If we are exhausting the current step, proceed directly to -- the next level | curr + 1 >= high -> getNext DepthFirst { dfStack = (withPrefix enum [curr], 0) : rest } -- Otherwise, keep it on the stack. | otherwise -> getNext DepthFirst { dfStack = (withPrefix enum [curr], 0) : (enum, curr + 1) : rest } -- When there's a step with infinite branches, go ahead and -- jettison the rest of the stack; we'll never get to it -- anyway. Nothing -> getNext DepthFirst { dfStack = [(withPrefix enum [curr], 0), (enum, curr + 1)] } -- | Breadth-first traversal. This style of traversal is guaranteed -- to be complete- that is, it will visit every possibility -- eventually. However, it may take a very long time to reach any -- given possibility. newtype BreadthFirst ty = BreadthFirst { bfQueue :: Seq (Enumeration ty, Integer) } instance Traversal BreadthFirst where mkTraversal enum = BreadthFirst { bfQueue = Sequence.singleton (enum, 0) } getNext BreadthFirst { bfQueue = queue } = case viewl queue of (enum, curr) :< rest -> case numBranches enum of -- For a leaf, produce a result Just 0 -> Just (fromPath enum [], prefix enum, BreadthFirst { bfQueue = rest }) Just high -- If we are exhausting the current head of the queue, remove it | curr + 1 >= high -> getNext BreadthFirst { bfQueue = rest |> (withPrefix enum [curr], 0) } -- Otherwise, keep it on the queue | otherwise -> getNext BreadthFirst { bfQueue = ((enum, curr + 1) <| rest) |> (withPrefix enum [curr], 0) } -- If there's a step with infinite branches, cycle it to the -- back of the queue, so we don't deep-dive into it. Nothing -> getNext BreadthFirst { bfQueue = rest |> (withPrefix enum [curr], 0) |> (enum, curr + 1) } EmptyL -> Nothing -- | Prioritized traversal. Will always pick the highest-scored -- option. Completeness depends entirely on the scoring function. data Prioritized ty = Prioritized { -- | The scoring function used in a 'Prioritized' traversal scheme. scoring :: !((Enumeration ty, Integer) -> Float), priHeap :: !(MaxPrioHeap Float (Enumeration ty, Integer)) } -- | Create a prioritized traversal with a given scoring function. mkPrioritizedTraversal :: ((Enumeration ty, Integer) -> Float) -- ^ The scoring function to use. -> Enumeration ty -- ^ The enumeration to use. -> Prioritized ty mkPrioritizedTraversal scorefunc enum = let initial = (enum, 0) scored = (scorefunc initial, initial) in Prioritized { scoring = scorefunc, priHeap = Heap.singleton scored } inverseDepth :: (Enumeration ty, Integer) -> Float inverseDepth (enum, curr) = case numBranches enum of Just finitemax -> -(fromIntegral (length (prefix enum)) - (fromIntegral curr / fromIntegral finitemax)) Nothing -> -(fromIntegral (length (prefix enum))) instance Traversal Prioritized where mkTraversal = mkPrioritizedTraversal inverseDepth getNext pri @ Prioritized { scoring = scorefunc, priHeap = heap } = case Heap.view heap of Just ((_, (enum, curr)), rest) -> case numBranches enum of -- For a leaf, produce a result Just 0 -> Just (fromPath enum [], prefix enum, pri { priHeap = rest }) -- If we're exhausting the current step, don't keep it in the heap Just high | curr + 1 >= high -> let newelem = (withPrefix enum [curr], 0) scored = (scorefunc newelem, newelem) withNew = Heap.insert scored rest in getNext pri { priHeap = withNew } -- Otherwise, insert the incremented current and the new -- branch into the heap. _ -> let newelem = (withPrefix enum [curr], 0) scored = (scorefunc newelem, newelem) increment = (enum, curr + 1) incscored = (scorefunc increment, increment) withNew = Heap.insert scored rest withInc = Heap.insert incscored withNew in getNext pri { priHeap = withInc } Nothing -> Nothing
emc2/enumeration
src/Data/Enumeration/Traversal.hs
bsd-3-clause
8,970
1
20
2,457
1,388
798
590
99
2
module Main where import ABS (n_div:x:main_ret:i:f:n:obj:reminder:res:the_end) = [0..] main_ :: Method main_ [] this wb k = Assign n (Val (I 1500)) $ Assign x (Sync primality_test [n]) $ k primality_test :: Method primality_test [pn] this wb k = Assign i (Val (I 1)) $ Assign n (Val (I pn)) $ While (ILTE (Attr i) (Attr n)) (\k' -> Assign obj New $ Assign f (Async obj divides [i,n]) $ Assign i (Val (Add (Attr i) (I 1))) $ k' ) $ Return i wb k divides :: Method divides [pd, pn] this wb k = Assign reminder (Val (Mod (I pn) (I pd)) ) $ If (IEq (Attr reminder) (I 0)) (\k' -> Assign res (Val (I 1)) k') (\k' -> Assign res (Val (I 0)) k' ) $ Return res wb k main' :: IO () main' = run' 1000000 main_ (head the_end) main :: IO () main = printHeap =<< run 1000000 main_ (head the_end)
abstools/abs-haskell-formal
benchmarks/3_primality_test_parallel/progs/1500.hs
bsd-3-clause
846
0
18
222
506
256
250
30
1
module Main where import Data.Hashable import Data.Word (Word16, Word8) import Data.Bits ((.|.), (.&.), shiftL, shiftR) import Control.Monad (when) import qualified Data.Text as T import qualified Data.Text.IO as TIO import qualified Data.List as L import qualified Data.HashMap.Strict as HM import qualified Control.Monad.State as S import qualified CommonTypes as CT import qualified BinaryCode as B import qualified Data.ByteString as BS import qualified Parser as P import Debug.Trace import AsmArgs main :: IO () main = do args <- asm16Args when (L.null $ assembly args) $ error "No assembly file given!" when (L.null $ output args) $ error "No output file specified!" text <- TIO.readFile $ assembly args let prog = P.parse text when (printParsed args) $ print prog let bytes = assemble prog BS.writeFile (output args) bytes assemble :: P.Program -> BS.ByteString assemble prog = let asmData = S.execState (asmProgram prog) emptyAsmData words = map right (binary asmData) (bytes, _) = BS.unfoldrN (numBytes asmData) (\(hiByte, words) -> if L.null words then Nothing else let (word:rest) = words byte | hiByte = (toW8 $ word `shiftR` 8, (False, rest)) | otherwise = (toW8 $ word .&. 0xff , (True , word:rest)) in Just byte) (False, words) in bytes where right (Right w) = w numBytes = fromIntegral . (*2) . numWords toW8 :: Integral a => a -> Word8 toW8 = fromIntegral asmProgram :: P.Program -> Assembler () asmProgram prog = mapM_ asmLine prog >> resolveLabels >> reverseBinary asmLine :: P.Line -> Assembler () asmLine = mapM_ asmStatement asmStatement :: P.Statement -> Assembler () asmStatement (P.Instruction opcode valueA valueB) = do addWord $ B.opcode opcode numWs <- S.gets numWords addValue valueA (borLastWord . (`shiftL` 4)) numWs' <- S.gets numWords if numWs' > numWs then addValue valueB (borSndLastWord . (`shiftL` 10)) else addValue valueB (borLastWord . (`shiftL` 10)) asmStatement (P.NonBasicInstruction opcode value) = do addWord $ B.nonBasicOpcode opcode `shiftL` 4 addValue value (borLastWord . (`shiftL` 10)) asmStatement s@(P.Label text) = S.modify (\s -> s {labelMap = HM.insert text (numWords s) (labelMap s)}) asmStatement (P.Comment _) = return () resolveLabels :: Assembler () resolveLabels = S.modify (\s -> let lMap = labelMap s bin' = L.map (either (\l -> maybe (error $ "Couldn't resolve label '" ++ show l ++ "'!") Right (HM.lookup l lMap)) Right) (binary s) in s {binary = bin'}) reverseBinary :: Assembler () reverseBinary = S.modify (\s -> s {binary = L.reverse (binary s)}) addValue :: P.Value -> (Word16 -> Assembler ()) -> Assembler () addValue (P.RamValue address) handleWord = case address of P.AtLiteral lit -> handleWord B.ramAtNextWord >> addWord lit P.AtRegister reg -> handleWord $ B.reg reg + B.ramAtRegOffset P.AtLabel text -> handleWord B.ramAtNextWord >> addLabel text P.AtLiteralPlusReg lit reg -> handleWord (B.reg reg + B.ramAtLitPlusRegOffset) >> addWord lit addValue (P.Register name) handleWord = handleWord $ B.reg name addValue (P.SP) handleWord = handleWord B.sp addValue (P.PC) handleWord = handleWord B.pc addValue (P.O) handleWord = handleWord B.o addValue (P.POP) handleWord = handleWord B.pop addValue (P.PEEK) handleWord = handleWord B.peek addValue (P.PUSH) handleWord = handleWord B.push addValue (P.LabelValue text) handleWord = handleWord B.literalAtNextWord >> addLabel text addValue (P.Literal word) handleWord | word > B.literalAtNextWord = handleWord B.literalAtNextWord >> addWord word | otherwise = handleWord $ word + B.literalOffset borLastWord :: Word16 -> Assembler () borLastWord word = S.modify (\s -> let (Right h:t) = binary s in s {binary = Right (h .|. word) : t}) borSndLastWord :: Word16 -> Assembler () borSndLastWord word = S.modify (\s -> let (h:Right sl:t) = binary s in s {binary = h : Right (sl .|. word) : t}) addWord :: Word16 -> Assembler () addWord word = S.modify (\s -> s {binary = Right word : binary s, numWords = 1 + numWords s}) addLabel :: T.Text -> Assembler () addLabel label = S.modify (\s -> s {binary = Left label : binary s, numWords = 1 + numWords s}) type Assembler = S.State AsmData emptyAsmData = AsmData {binary = [], numWords = 0, labelMap = HM.empty} data AsmData = AsmData { binary :: [AsmWord], numWords :: Word16, labelMap :: LabelMap } deriving (Show) dumpAsmData :: Assembler () dumpAsmData = do asmD <- S.get trace (show asmD) return () type LabelMap = HM.HashMap T.Text Word16 type AsmWord = Either T.Text Word16
dan-t/dcpu16
Assembler.hs
bsd-3-clause
5,093
0
21
1,347
1,908
992
916
119
4
----------------------------------------------------------------------------- -- | -- Module : XMonad.Doc.Configuring -- Description : Brief xmonad tutorial. -- Copyright : (C) 2007 Don Stewart and Andrea Rossato -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : unstable -- Portability : portable -- -- This is a brief tutorial that will teach you how to create a basic -- xmonad configuration. For a more comprehensive tutorial, see the -- <https://xmonad.org/TUTORIAL.html xmonad website>. -- -- For more detailed instructions on extending xmonad with the -- xmonad-contrib library, see "XMonad.Doc.Extending". -- ----------------------------------------------------------------------------- module XMonad.Doc.Configuring ( -- * Configuring xmonad -- $configure -- * A simple example -- $example -- * Checking whether your xmonad.hs is correct -- $check -- * Loading your configuration -- $load ) where -------------------------------------------------------------------------------- -- -- Configuring Xmonad -- -------------------------------------------------------------------------------- {- $configure #Configuring_xmonad# xmonad can be configured by creating and editing the Haskell file: > ~/.xmonad/xmonad.hs If this file does not exist, xmonad will simply use default settings; if it does exist, xmonad will use whatever settings you specify. Note that this file can contain arbitrary Haskell code, which means that you have quite a lot of flexibility in configuring xmonad. HISTORICAL NOTE regarding upgrading from versions (< 0.5) of xmonad or using old documentation: xmonad-0.5 delivered a major change in the way xmonad is configured. Prior to version 0.5, configuring xmonad required editing a source file called Config.hs, manually recompiling xmonad, and then restarting. From version 0.5 onwards, however, you should NOT edit this file or manually compile with ghc --make. All you have to do is edit xmonad.hs and restart with @mod-q@; xmonad does the recompiling itself. The format of the configuration file also changed with version 0.5; enabling simpler and much shorter xmonad.hs files that only require listing those settings which are different from the defaults. While the complicated template.hs (man/xmonad.hs) files listing all default settings are still provided for reference, once you wish to make substantial changes to your configuration, the template.hs style configuration is not recommended. It is fine to use top-level definitions to organize your xmonad.hs, but wherever possible it is better to leave out settings that simply duplicate defaults. -} {- $example #A_simple_example# Here is a basic example, which starts with the default xmonad configuration and overrides the border width, default terminal, and some colours: > -- > -- An example, simple ~/.xmonad/xmonad.hs file. > -- It overrides a few basic settings, reusing all the other defaults. > -- > > import XMonad > > main = xmonad $ def > { borderWidth = 2 > , terminal = "urxvt" > , normalBorderColor = "#cccccc" > , focusedBorderColor = "#cd8b00" } This will run \'xmonad\', the window manager, with your settings passed as arguments. Overriding default settings like this (using \"record update syntax\"), will yield the shortest config file, as you only have to describe values that differ from the defaults. As an alternative, you can copy the template @xmonad.hs@ file (found either in the @man@ directory, if you have the xmonad source, or on the xmonad wiki config archive at <http://haskell.org/haskellwiki/Xmonad/Config_archive>) into your @~\/.xmonad\/@ directory. This template file contains all the default settings spelled out, and you should be able to simply change the ones you would like to change. To see what fields can be customized beyond the ones in the example above, the definition of the 'XMonad.Core.XConfig' data structure can be found in "XMonad.Core". -} {- $check #Checking_whether_your_xmonad.hs_is_correct# After changing your configuration, it is a good idea to check that it is syntactically and type correct. You can do this easily by using an xmonad flag: > $ xmonad --recompile > $ If there is no output, your xmonad.hs has no errors. If there are errors, they will be printed to the console. Patch them up and try again. Note, however, that if you skip this step and try restarting xmonad with errors in your xmonad.hs, it's not the end of the world; xmonad will simply display a window showing the errors and continue with the previous configuration settings. (This assumes that you have the \'xmessage\' utility installed; you probably do.) -} {- $load #Loading_your_configuration# To get xmonad to use your new settings, type @mod-q@. (Remember, the mod key is \'alt\' by default, but you can configure it to be something else, such as your Windows key if you have one.) xmonad will attempt to compile this file, and run it. If everything goes well, xmonad will seamlessly restart itself with the new settings, keeping all your windows, layouts, etc. intact. (If you change anything related to your layouts, you may need to hit @mod-shift-space@ after restarting to see the changes take effect.) If something goes wrong, the previous (default) settings will be used. Note this requires that GHC and xmonad are in the @$PATH@ in the environment from which xmonad is started. -}
xmonad/xmonad-contrib
XMonad/Doc/Configuring.hs
bsd-3-clause
5,525
0
3
981
46
43
3
2
0
module Day7 where import Control.Monad.Identity (Identity) import Data.Bits import Data.Function (fix) import Data.Function.Memoize import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as M import Data.List import qualified Data.Map.Lazy as LM import Data.Maybe import Foreign.C.Types import Text.Parsec data Atom = Value CUShort | Var String deriving (Show, Eq, Ord) data WireInput = Const Atom | And Atom Atom | LShift Atom Atom | RShift Atom Atom | Not Atom | Or Atom Atom deriving (Show, Eq, Ord) partOne = do m <- input return $ eval m "a" partTwo = do m <- input let val1 = eval m "a" let m2 = M.adjust (const (Const (Value val1))) "b" m return $ eval m2 "a" evalList :: HashMap String WireInput -> LM.Map WireInput CUShort evalList m = LM.fromList $ map (\w -> (w,eval' fasterEval m w)) wInputList where wInputList = nub $ map (Const . Var) (M.keys m) ++ M.elems m fasterEval :: HashMap String WireInput -> WireInput -> CUShort fasterEval m w = evalList m LM.! w eval' :: (HashMap String WireInput -> WireInput -> CUShort) -> HashMap String WireInput -> WireInput -> CUShort eval' f m (And x y) = getAtom' f m x .&. getAtom' f m y eval' f m (Const x) = getAtom' f m x eval' f m (Not x) = complement (getAtom' f m x) eval' f m (Or x y) = getAtom' f m x .|. getAtom' f m y eval' f m (RShift x y) = getAtom' f m x `shiftR` fromIntegral (getAtom' f m y) eval' f m (LShift x y) = getAtom' f m x `shiftL` fromIntegral (getAtom' f m y) getAtom' :: (HashMap String WireInput -> WireInput -> CUShort) -> HashMap String WireInput -> Atom -> CUShort getAtom' _ _ (Value i) = i getAtom' f m (Var s) = f m (m M.! s) eval :: HashMap String WireInput -> String -> CUShort eval m = me where e :: String -> CUShort e s = case m M.! s of (Const x) -> getAtom x (And x y) -> getAtom x .&. getAtom y (Or x y) -> getAtom x .|. getAtom y (Not x) -> complement (getAtom x) (RShift x y) -> getAtom x `shiftR` fromIntegral (getAtom y) (LShift x y) -> getAtom x `shiftL` fromIntegral (getAtom y) me :: String -> CUShort me = memoize e getAtom :: Atom -> CUShort getAtom (Value i) = i getAtom (Var s) = me s parseInput :: [String] -> [(String,WireInput)] parseInput = map (either ( error . show) id . parse wireInputParser "") wireInputParser = flip (,) <$> parseNode <* string " -> " <*> many1 letter parseNode = try parseNot <|> try parseAnd <|> try parseOr <|> try parseLShift <|> try parseRShift <|> parseConst parseAtom = try parseValue <|> parseVar parseValue = Value . read <$> many1 digit parseVar = Var <$> many1 letter parseConst = Const <$> parseAtom parseNot = Not <$> (string "NOT " *> parseAtom) parseAnd = And <$> parseAtom <* string " AND " <*> parseAtom parseOr = Or <$> parseAtom <* string " OR " <*> parseAtom parseLShift = LShift <$> parseAtom <* string " LSHIFT " <*> parseAtom parseRShift = RShift <$> parseAtom <* string " RSHIFT " <*> parseAtom input :: IO (HashMap String WireInput) input = M.fromList <$> parseInput <$> lines <$> readFile "day7-input.txt"
z0isch/advent-of-code
src/Day7.hs
bsd-3-clause
3,217
0
16
787
1,326
674
652
79
7
module Folly.FOL where data Term = Fun String [Term] | Var String deriving (Eq,Ord,Show) data EqOp = (:==) | (:!=) deriving (Eq,Ord,Show) data BinOp = (:&) | (:|) | (:=>) | (:<=>) deriving (Eq,Ord,Show) data Formula = EqOp Term EqOp Term | Rel String [Term] | Neg Formula | BinOp Formula BinOp Formula | Quant Quant [String] Formula deriving (Eq,Ord,Show) data Quant = Forall | Exists deriving (Eq,Ord,Show) mkBinOp :: BinOp -> Formula -> Formula -> Formula mkBinOp op f g = BinOp f op g infix 4 === infix 4 != infixr 3 & infixr 3 /\ infixr 2 \/ infixl 1 ==> infix 1 <=> (==>),(&),(/\),(\/),(<=>) :: Formula -> Formula -> Formula (==>) = mkBinOp (:=>) (&) = mkBinOp (:&) (/\) = mkBinOp (:&) (\/) = mkBinOp (:|) (<=>) = mkBinOp (:<=>) (===),(!=) :: Term -> Term -> Formula (===) = \f g -> EqOp f (:==) g (!=) = \f g -> EqOp f (:!=) g data DeclType = Axiom | Conjecture | Question | NegConj | Lemma | Hypothesis | Definition deriving (Eq,Ord,Show) data Decl = Decl DeclType String Formula deriving (Eq,Ord,Show) forall' :: [String] -> Formula -> Formula forall' [] phi = phi forall' xs phi = Quant Forall xs phi exists' :: [String] -> Formula -> Formula exists' [] phi = phi exists' xs phi = Quant Exists xs phi
danr/folly
Folly/FOL.hs
bsd-3-clause
1,333
50
8
349
505
330
175
51
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} module Juno.Types.Message.AER ( AppendEntriesResponse(..), aerTerm, aerNodeId, aerSuccess, aerConvinced , aerIndex, aerHash, aerWasVerified, aerProvenance , AERWire(..) , AlotOfAERs(..), unAlot ) where import Control.Lens import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import Data.ByteString (ByteString) import Data.Serialize (Serialize) import qualified Data.Serialize as S import Data.Thyme.Time.Core () import GHC.Generics import Juno.Types.Base import Juno.Types.Message.Signed data AppendEntriesResponse = AppendEntriesResponse { _aerTerm :: !Term , _aerNodeId :: !NodeID , _aerSuccess :: !Bool , _aerConvinced :: !Bool , _aerIndex :: !LogIndex , _aerHash :: !ByteString , _aerWasVerified:: !Bool , _aerProvenance :: !Provenance } deriving (Show, Generic, Eq) makeLenses ''AppendEntriesResponse instance Ord AppendEntriesResponse where -- This is here to get a set of AERs to order correctly -- Node matters most (apples to apples) -- Term supersedes index always -- Index is really what we're after for how Set AER is used -- Hash matters more than verified due to conflict resolution -- Then verified, which is metadata really, because if everything up to that point is the same then the one that already ran through crypto is more valuable -- After that it doesn't matter. (AppendEntriesResponse t n s c i h v p) <= (AppendEntriesResponse t' n' s' c' i' h' v' p') = (n,t,i,h,v,s,c,p) <= (n',t',i',h',v',s',c',p') newtype AERWire = AERWire (Term,NodeID,Bool,Bool,LogIndex,ByteString) deriving (Show, Generic) instance Serialize AERWire instance WireFormat AppendEntriesResponse where toWire nid pubKey privKey AppendEntriesResponse{..} = case _aerProvenance of NewMsg -> let bdy = S.encode $ AERWire ( _aerTerm , _aerNodeId , _aerSuccess , _aerConvinced , _aerIndex , _aerHash) sig = sign bdy privKey pubKey dig = Digest nid sig pubKey AER in SignedRPC dig bdy ReceivedMsg{..} -> SignedRPC _pDig _pOrig fromWire !ts !ks s@(SignedRPC !dig !bdy) = case verifySignedRPC ks s of Left !err -> Left $! err Right () -> if _digType dig /= AER then error $ "Invariant Failure: attempting to decode " ++ show (_digType dig) ++ " with AERWire instance" else case S.decode bdy of Left !err -> Left $! "Failure to decode AERWire: " ++ err Right (AERWire (t,nid,s',c,i,h)) -> Right $! AppendEntriesResponse t nid s' c i h True $ ReceivedMsg dig bdy ts {-# INLINE toWire #-} {-# INLINE fromWire #-} newtype AlotOfAERs = AlotOfAERs { _unAlot :: Map NodeID (Set AppendEntriesResponse)} deriving (Show, Eq) makeLenses ''AlotOfAERs instance Monoid AlotOfAERs where mempty = AlotOfAERs Map.empty mappend (AlotOfAERs m) (AlotOfAERs m') = AlotOfAERs $ Map.unionWith Set.union m m'
haroldcarr/juno
src/Juno/Types/Message/AER.hs
bsd-3-clause
3,287
0
16
845
820
457
363
81
0
{-# LANGUAGE OverloadedStrings #-} module Examples.Radio(radio) where import Development.NSIS import Development.NSIS.Plugins.EnvVarUpdate import Development.NSIS.Plugins.Sections radio = do name "Radio" outFile "radio.exe" installDir "$DESKTOP/Radio" requestExecutionLevel User -- page Directory page Components page InstFiles section "Core files" [Required] $ do setOutPath "$INSTDIR" file [] "test/Examples/Radio.hs" local <- section "Add to user %PATH%" [] $ do setEnvVarPrepend HKCU "PATH" "$INSTDIR" global <- section "Add to system %PATH%" [] $ do setEnvVarPrepend HKLM "PATH" "$INSTDIR" atMostOneSection [local,global] a <- section "I like Marmite" [] $ return () b <- section "I hate Marmite" [] $ return () c <- section "I don't care" [] $ return () exactlyOneSection [a,b,c]
ndmitchell/nsis
test/Examples/Radio.hs
bsd-3-clause
886
0
11
204
256
118
138
24
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} -- | This module builds Docker (OpenContainer) images. module Stack.Image (imageDocker, imgCmdName, imgDockerCmdName, imgOptsFromMonoid, imgDockerOptsFromMonoid, imgOptsParser, imgDockerOptsParser) where import Control.Applicative import Control.Exception.Lifted import Control.Monad import Control.Monad.Catch hiding (bracket) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader import Control.Monad.Trans.Control import Data.Char (toLower) import qualified Data.Map.Strict as Map import Data.Maybe import Data.Monoid import qualified Data.Set as Set import qualified Data.Text as T import Data.Typeable import Options.Applicative import Path import Path.IO import Stack.Build.Source import Stack.Package import Stack.Types import Stack.Types.Internal import qualified System.Directory as SD import System.IO.Temp import System.FilePath (isPathSeparator) import System.Process type M e m = (HasBuildConfig e, HasConfig e, HasEnvConfig e, HasTerminal e, MonadBaseControl IO m, MonadCatch m, MonadIO m, MonadLogger m, MonadReader e m) -- | Builds a Docker (OpenContainer) image extending the `base` image -- specified in the project's stack.yaml. The new image will contain -- all the executables from the packages in the project as well as any -- other specified files to `add`. Then new image will be extended -- with an ENTRYPOINT specified for each `entrypoint` listed in the -- config file. imageDocker :: M e m => m () imageDocker = do tempDirFP <- liftIO SD.getTemporaryDirectory bracket (liftIO (createTempDirectory tempDirFP "stack-image-docker")) (liftIO . SD.removeDirectoryRecursive) (\dir -> do stageExesInDir dir syncAddContentToDir dir createDockerImage dir extendDockerImageWithEntrypoint dir) -- | Extract all the Package(s) from the stack.yaml config file & -- project cabal files. projectPkgs :: M e m => m [Package] projectPkgs = do econfig <- asks getEnvConfig bconfig <- asks getBuildConfig forM (Map.toList (bcPackages bconfig)) (\(dir,_wanted) -> do cabalfp <- getCabalFileName dir name <- parsePackageNameFromFilePath cabalfp let cfg = PackageConfig { packageConfigEnableTests = True , packageConfigEnableBenchmarks = True , packageConfigFlags = localFlags mempty bconfig name , packageConfigGhcVersion = envConfigGhcVersion econfig , packageConfigPlatform = configPlatform (getConfig bconfig) } readPackage cfg cabalfp) -- | Stage all the Package executables in the usr/local/bin -- subdirectory of a temp directory. stageExesInDir :: M e m => FilePath -> m () stageExesInDir dir = do srcBinPath <- (</> $(mkRelDir "bin")) <$> installationRootLocal destBinPath <- (</> $(mkRelDir "usr/local/bin")) <$> parseAbsDir dir createTree destBinPath pkgs <- projectPkgs forM_ (concatMap (Set.toList . packageExes) pkgs) (\exe -> do exePath <- parseRelFile (T.unpack exe) copyFile (srcBinPath </> exePath) (destBinPath </> exePath)) -- | Add any additional files into the temp directory, respecting the -- (Source, Destination) mapping. syncAddContentToDir :: M e m => FilePath -> m () syncAddContentToDir dir = do config <- asks getConfig bconfig <- asks getBuildConfig dirPath <- parseAbsDir dir let imgAdd = maybe Map.empty imgDockerAdd (imgDocker (configImage config)) forM_ (Map.toList imgAdd) (\(source,dest) -> do sourcePath <- parseRelDir source destPath <- parseAbsDir dest let destFullPath = dirPath </> dropRoot destPath createTree destFullPath copyDirectoryRecursive (bcRoot bconfig </> sourcePath) destFullPath) -- | Derive an image name from the project directory. imageName :: BuildConfig -> String imageName = map toLower . filter (not . isPathSeparator) . toFilePath . dirname . bcRoot -- | Create a general purpose docker image from the temporary -- directory of executables & static content. createDockerImage :: M e m => FilePath -> m () createDockerImage dir = do config <- asks getConfig bconfig <- asks getBuildConfig case maybe Nothing imgDockerBase (imgDocker (configImage config)) of Nothing -> throwM StackImageDockerBaseUnspecifiedException Just base -> do dirPath <- parseAbsDir dir liftIO (do writeFile (toFilePath (dirPath </> $(mkRelFile "Dockerfile"))) (unlines ["FROM " ++ base, "ADD ./ /"]) callProcess "docker" ["build", "-t", imageName bconfig, dir]) -- | Extend the general purpose docker image with entrypoints (if -- specified). extendDockerImageWithEntrypoint :: M e m => FilePath -> m () extendDockerImageWithEntrypoint dir = do config <- asks getConfig bconfig <- asks getBuildConfig let imgEntrypoints = maybe Nothing imgDockerEntrypoints (imgDocker (configImage config)) case imgEntrypoints of Nothing -> return () Just eps -> do dirPath <- parseAbsDir dir forM_ eps (\ep -> liftIO (do writeFile (toFilePath (dirPath </> $(mkRelFile "Dockerfile"))) (unlines [ "FROM " ++ imageName bconfig , "ENTRYPOINT [\"/usr/local/bin/" ++ ep ++ "\"]" , "CMD []"]) callProcess "docker" [ "build" , "-t" , imageName bconfig ++ "-" ++ ep , dir])) -- | The command name for dealing with images. imgCmdName :: String imgCmdName = "image" -- | The command name for building a docker container. imgDockerCmdName :: String imgDockerCmdName = "container" -- | A parser for ImageOptsMonoid. imgOptsParser :: Parser ImageOptsMonoid imgOptsParser = ImageOptsMonoid <$> optional (subparser (command imgDockerCmdName (info imgDockerOptsParser (progDesc "Create a container image (EXPERIMENTAL)")))) -- | A parser for ImageDockerOptsMonoid. imgDockerOptsParser :: Parser ImageDockerOptsMonoid imgDockerOptsParser = ImageDockerOptsMonoid <$> optional (option str (long (imgDockerCmdName ++ "-" ++ T.unpack imgDockerBaseArgName) <> metavar "NAME" <> help "Docker base image name")) <*> pure Nothing <*> pure Nothing -- | Convert image opts monoid to image options. imgOptsFromMonoid :: ImageOptsMonoid -> ImageOpts imgOptsFromMonoid ImageOptsMonoid{..} = ImageOpts { imgDocker = imgDockerOptsFromMonoid <$> imgMonoidDocker } -- | Convert Docker image opts monoid to Docker image options. imgDockerOptsFromMonoid :: ImageDockerOptsMonoid -> ImageDockerOpts imgDockerOptsFromMonoid ImageDockerOptsMonoid{..} = ImageDockerOpts { imgDockerBase = emptyToNothing imgDockerMonoidBase , imgDockerEntrypoints = emptyToNothing imgDockerMonoidEntrypoints , imgDockerAdd = fromMaybe Map.empty imgDockerMonoidAdd } where emptyToNothing Nothing = Nothing emptyToNothing (Just s) | null s = Nothing | otherwise = Just s -- | Stack image exceptions. data StackImageException = StackImageDockerBaseUnspecifiedException deriving (Typeable) instance Exception StackImageException instance Show StackImageException where show StackImageDockerBaseUnspecifiedException = "You must specify a base docker image on which to place your haskell executables."
GaloisInc/stack
src/Stack/Image.hs
bsd-3-clause
9,177
0
26
3,118
1,681
865
816
193
2
-- | The Interval module implements diatonic intervals. module Music.Diatonic.Interval ( Interval( Unison,Min2nd,Maj2nd,Min3rd,Maj3rd,Perf4th, Perf5th,Min6th,Maj6th,Min7th,Maj7th ), compound, octave, min9th, maj9th, perf11th, min13th, maj13th, augment, diminish, steps, semitones ) where import Music.Diatonic.Quality import Music.Diatonic.Equivalence -- | Use these constructors to create 'Interval's. To alter them, use the 'diminish' or 'augment' functions. data Interval = Unison | Min2nd | Maj2nd | Min3rd | Maj3rd | Perf4th | Perf5th | Min6th | Maj6th | Min7th | Maj7th | Aug Interval | Dim Interval | Compound Interval deriving (Eq) instance Qual Interval where quality i | i `elem` [Maj2nd, Maj3rd, Maj6th, Maj7th] = Major quality i | i `elem` [Min2nd, Min3rd, Min6th, Min7th] = Minor quality i | i `elem` [Unison, Perf4th, Perf5th] = Perfect quality (Aug i) = Augmented quality (Dim i) = Diminished quality (Compound i) = quality i instance Show Interval where show i = showq i ++ shown where shown = show . (+ 1) . steps $ i showq (Compound i) = showq i showq (Aug i@(Aug _)) = "A" ++ showq i showq (Dim i@(Dim _)) = "d" ++ showq i showq (Aug i) = "A" ++ (tail . showq $ i) showq (Dim i) = "d" ++ (tail . showq $ i) showq i = case quality i of Major -> "M" Minor -> "m" Perfect -> "P" instance Equiv Interval where equiv i1 i2 = ((semitones i1 `mod` 12 == (semitones i2 `mod` 12)) && ((steps i1 `mod` 7) == (steps i2 `mod` 7))) -- | Augments an 'Interval' by a semitone. The interval type remains the same. augment :: Interval -> Interval augment Min2nd = Maj2nd ; augment Min3rd = Maj3rd augment Min6th = Maj6th ; augment Min7th = Maj7th augment (Compound i) = compound . augment $ i augment (Dim i) = i augment i = Aug i -- | Diminishes an 'Interval' by a semitone. The interval type remains the same. diminish :: Interval -> Interval diminish Maj2nd = Min2nd ; diminish Maj3rd = Min3rd diminish Maj6th = Min6th ; diminish Maj7th = Min7th diminish (Compound i) = compound . diminish $ i diminish (Aug i) = i diminish i = Dim i -- | Returns the number of scale steps in an 'Interval'. steps :: Interval -> Int steps Unison = 0 ; steps Min2nd = 1 ; steps Maj2nd = 1 ; steps Min3rd = 2 steps Maj3rd = 2 ; steps Perf4th = 3 ; steps Perf5th = 4 ; steps Min6th = 5 steps Maj6th = 5 ; steps Min7th = 6 ; steps Maj7th = 6 ; steps (Aug i) = steps i steps (Dim i) = steps i steps (Compound i) = 7 + steps i -- | Returns the number of semitones in an 'Interval'. semitones :: Interval -> Int semitones Unison = 0 ; semitones Min2nd = 1 ; semitones Maj2nd = 2 ; semitones Min3rd = 3 semitones Maj3rd = 4 ; semitones Perf4th = 5 ; semitones Perf5th = 7 ; semitones Min6th = 8 semitones Maj6th = 9 ; semitones Min7th = 10 ; semitones Maj7th = 11 ; semitones (Aug i) = semitones i + 1 semitones (Dim i) = semitones i - 1 semitones (Compound i) = 12 + semitones i -- | Creates compound interval (adds an 'octave') to the specified 'Interval' compound :: Interval -> Interval compound = Compound octave :: Interval octave = compound Unison min9th :: Interval min9th = compound Min2nd maj9th :: Interval maj9th = compound Maj2nd perf11th :: Interval perf11th = compound Perf4th min13th :: Interval min13th = compound Min6th maj13th :: Interval maj13th = compound Maj6th
xpika/music-diatonic
Music/Diatonic/Interval.hs
bsd-3-clause
3,582
0
13
920
1,193
652
541
76
1
module JavaScript.AceAjax.Raw.Ace where import qualified GHCJS.Types as GHCJS import qualified GHCJS.Marshal as GHCJS import qualified Data.Typeable import GHCJS.FFI.TypeScript import GHCJS.DOM.Types (HTMLElement) import JavaScript.AceAjax.Raw.Types foreign import javascript "$1.require($2)" require :: (Ace) -> (GHCJS.JSString) -> IO (GHCJS.JSRef obj0) foreign import javascript "$1.edit($2)" edit :: (Ace) -> (GHCJS.JSString) -> IO (Editor) foreign import javascript "$1.edit($2)" edit1 :: (Ace) -> (HTMLElement) -> IO (Editor) foreign import javascript "$1.createEditSession($2,$3)" createEditSession :: (Ace) -> (Document) -> (TextMode) -> IO (IEditSession) foreign import javascript "$1.createEditSession($2,$3)" createEditSession1 :: (Ace) -> (GHCJS.JSString) -> (TextMode) -> IO (IEditSession)
fpco/ghcjs-from-typescript
ghcjs-ace/JavaScript/AceAjax/Raw/Ace.hs
bsd-3-clause
803
10
8
89
206
131
75
12
0
{-# LANGUAGE OverloadedStrings, GeneralizedNewtypeDeriving, ScopedTypeVariables, FlexibleInstances, DeriveDataTypeable, UndecidableInstances, BangPatterns, OverlappingInstances, DataKinds, GADTs, KindSignatures, NamedFieldPuns #-} -- | Haskell client for Cassandra's CQL protocol -- -- For examples, take a look at the /tests/ directory in the source archive. -- -- Here's the correspondence between CQL and Haskell types: -- -- * ascii - 'ByteString' -- -- * bigint - 'Int64' -- -- * blob - 'Blob' -- -- * boolean - 'Bool' -- -- * counter - 'Counter' -- -- * decimal - 'Decimal' -- -- * double - 'Double' -- -- * float - 'Float' -- -- * int - 'Int' -- -- * text / varchar - 'Text' -- -- * timestamp - 'UTCTime' -- -- * uuid - 'UUID' -- -- * varint - 'Integer' -- -- * timeuuid - 'TimeUUID' -- -- * inet - 'SockAddr' -- -- * list\<a\> - [a] -- -- * map\<a, b\> - 'Map' a b -- -- * set\<a\> - 'Set' b -- -- * tuple<a,b> - '(a,b) -- -- * UDT -- -- ...and you can define your own 'CasType' instances to extend these types, which is -- a very powerful way to write your code. -- -- One way to do things is to specify your queries with a type signature, like this: -- -- > createSongs :: Query Schema () () -- > createSongs = "create table songs (id uuid PRIMARY KEY, title text, artist text, comment text)" -- > -- > insertSong :: Query Write (UUID, Text, Text, Maybe Text) () -- > insertSong = "insert into songs (id, title, artist, comment) values (?, ?, ?)" -- > -- > getOneSong :: Query Rows UUID (Text, Text, Maybe Text) -- > getOneSong = "select title, artist, comment from songs where id=?" -- -- The three type parameters are the query type ('Schema', 'Write' or 'Rows') followed by the -- input and output types, which are given as tuples whose constituent types must match -- the ones in the query CQL. If you do not match them correctly, you'll get a runtime -- error when you execute the query. If you do, then the query becomes completely type -- safe. -- -- Types can be 'Maybe' types, in which case you can read and write a Cassandra \'null\' -- in the table. Cassandra allows any column to be null, but you can lock this out by -- specifying non-Maybe types. -- -- The query types are: -- -- * 'Schema' for modifications to the schema. The output tuple type must be (). -- -- * 'Write' for row inserts and updates, and such. The output tuple type must be (). -- -- * 'Rows' for selects that give a list of rows in response. -- -- The functions to use for these query types are 'executeSchema', -- 'executeWrite', 'executeTrans' and 'executeRows' or 'executeRow' -- respectively. -- -- The following pattern seems to work very well, especially along with your own 'CasType' -- instances, because it gives you a place to neatly add marshalling details that keeps -- away from the body of your code. -- -- > insertSong :: UUID -> Text -> Text -> Maybe Text -> Cas () -- > insertSong id title artist comment = executeWrite QUORUM q (id, title, artist, comment) -- > where q = "insert into songs (id, title, artist, comment) values (?, ?, ?, ?)" -- -- Incidentally, here's Haskell's little-known multi-line string syntax. -- You escape it using \\ and then another \\ where the string starts again. -- -- > str = "multi\ -- > \line" -- -- (gives \"multiline\") -- -- /To do/ -- -- * Add the ability to easily run queries in parallel. -- * Add support for batch queries. -- * Add support for query paging. module Database.Cassandra.CQL ( -- * Initialization Server, Keyspace(..), Pool, newPool, newPool', defaultConfig, -- * Cassandra monad MonadCassandra(..), Cas, runCas, CassandraException(..), CassandraCommsError(..), TransportDirection(..), -- * Auth Authentication (..), -- * Queries Query, Style(..), query, -- * Executing queries Consistency(..), Change(..), executeSchema, executeSchemaVoid, executeWrite, executeRows, executeRow, executeTrans, -- * Value types Blob(..), Counter(..), TimeUUID(..), metadataTypes, CasType(..), CasValues(..), -- * Lower-level interfaces executeRaw, Result(..), TableSpec(..), ColumnSpec(..), Metadata(..), CType(..), Table(..), PreparedQueryID(..), serverStats, ServerStat(..), PoolConfig(..), -- * Misc for UDTs getOption, putOption, getString, putString ) where import Control.Applicative import Control.Concurrent (threadDelay, forkIO) import Control.Concurrent.STM import Control.Exception (IOException, SomeException, MaskingState(..), throwIO, getMaskingState, mask) import Control.Monad.CatchIO import Control.Monad.Reader import Control.Monad.State hiding (get, put) import qualified Control.Monad.RWS import qualified Control.Monad.Error import qualified Control.Monad.Writer import Crypto.Hash (hash, Digest, SHA1) import Data.Bits import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as C8BS import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.Data import Data.Decimal import Data.Either (lefts) import Data.Int import Data.List import Data.Map (Map) import qualified Data.Map as M import Data.Maybe import qualified Data.Foldable as F import Data.Monoid (Monoid) import qualified Data.Sequence as Seq import Data.Serialize hiding (Result) import Data.Set (Set) import qualified Data.Set as S import qualified Data.Pool as P import Data.String import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import Data.Time.Calendar import Data.Time.Clock import Data.Typeable () import Data.UUID (UUID) import qualified Data.UUID as UUID import Data.Word import Network.Socket (Socket, HostName, ServiceName, getAddrInfo, socket, AddrInfo(..), connect, sClose, SockAddr(..), SocketType(..), defaultHints) import Network.Socket.ByteString (sendAll, recv) import Numeric import Unsafe.Coerce import Data.Function (on) import Data.Monoid ((<>)) import Data.Fixed (Pico) import System.Timeout (timeout) import System.Log.Logger (debugM, warningM) defaultConnectionTimeout :: NominalDiffTime defaultConnectionTimeout = 10 defaultIoTimeout :: NominalDiffTime defaultIoTimeout = 300 defaultSessionCreateTimeout :: NominalDiffTime defaultSessionCreateTimeout = 20 defaultBackoffOnError :: NominalDiffTime defaultBackoffOnError = 60 defaultMaxSessionIdleTime :: NominalDiffTime defaultMaxSessionIdleTime = 60 defaultMaxSessions :: Int defaultMaxSessions = 20 type Server = (HostName, ServiceName) data ActiveSession = ActiveSession { actServer :: Server, actSocket :: Socket, actIoTimeout :: NominalDiffTime, actQueryCache :: Map QueryID PreparedQuery } data Session = Session { sessServerIndex :: Int, sessServer :: Server, sessSocket :: Socket } data ServerState = ServerState { ssServer :: Server, ssOrdinal :: Int, ssSessionCount :: Int, ssLastError :: Maybe UTCTime, ssAvailable :: Bool } deriving (Show, Eq) instance Ord ServerState where compare = let compareCount = compare `on` ssSessionCount tieBreaker = compare `on` ssOrdinal in compareCount <> tieBreaker data PoolConfig = PoolConfig { piServers :: [Server], piKeyspace :: Keyspace, piKeyspaceConfig :: Maybe Text, piAuth :: Maybe Authentication, piSessionCreateTimeout :: NominalDiffTime, piConnectionTimeout :: NominalDiffTime, piIoTimeout :: NominalDiffTime, piBackoffOnError :: NominalDiffTime, piMaxSessionIdleTime :: NominalDiffTime, piMaxSessions :: Int } data PoolState = PoolState { psConfig :: PoolConfig, psServers :: TVar (Seq.Seq ServerState) } -- | Exported stats for a server. data ServerStat = ServerStat { statServer :: Server, statSessionCount :: Int, statAvailable :: Bool } deriving (Show) newtype Pool = Pool (PoolState, P.Pool Session) class MonadCatchIO m => MonadCassandra m where getCassandraPool :: m Pool instance MonadCassandra m => MonadCassandra (Control.Monad.Reader.ReaderT a m) where getCassandraPool = lift getCassandraPool instance MonadCassandra m => MonadCassandra (Control.Monad.State.StateT a m) where getCassandraPool = lift getCassandraPool instance (MonadCassandra m, Control.Monad.Error.Error e) => MonadCassandra (Control.Monad.Error.ErrorT e m) where getCassandraPool = lift getCassandraPool instance (MonadCassandra m, Monoid a) => MonadCassandra (Control.Monad.Writer.WriterT a m) where getCassandraPool = lift getCassandraPool instance (MonadCassandra m, Monoid w) => MonadCassandra (Control.Monad.RWS.RWST r w s m) where getCassandraPool = lift getCassandraPool defaultConfig :: [Server] -> Keyspace -> Maybe Authentication -> PoolConfig defaultConfig servers keyspace auth = PoolConfig { piServers = servers, piKeyspace = keyspace, piKeyspaceConfig = Nothing, piAuth = auth, piSessionCreateTimeout = defaultSessionCreateTimeout, piConnectionTimeout = defaultConnectionTimeout, piIoTimeout = defaultIoTimeout, piBackoffOnError = defaultBackoffOnError, piMaxSessionIdleTime = defaultMaxSessionIdleTime, piMaxSessions = defaultMaxSessions } -- | Construct a pool of Cassandra connections. newPool :: [Server] -> Keyspace -> Maybe Authentication -> IO Pool newPool servers keyspace auth = newPool' $ defaultConfig servers keyspace auth newPool' :: PoolConfig -> IO Pool newPool' config@PoolConfig { piServers, piMaxSessions, piMaxSessionIdleTime } = do when (null piServers) $ throwIO $ userError "at least one server required" -- TODO: Shuffle ordinals let servers = Seq.fromList $ map (\(s, idx) -> ServerState s idx 0 Nothing True) $ zip piServers [0..] servers' <- atomically $ newTVar servers let poolState = PoolState { psConfig = config, psServers = servers' } sessions <- P.createPool (newSession poolState) (destroySession poolState) 1 piMaxSessionIdleTime piMaxSessions let pool = Pool (poolState, sessions) _ <- forkIO $ poolWatch pool return pool poolWatch :: Pool -> IO () poolWatch (Pool (PoolState { psConfig, psServers }, _)) = do let loop = do cutoff <- (piBackoffOnError psConfig `addUTCTime`) <$> getCurrentTime debugM "Database.Cassandra.CQL.poolWatch" "starting" sleepTil <- atomically $ do servers <- readTVar psServers let availableAgain = filter (((&&) <$> (not . ssAvailable) <*> (maybe False (<= cutoff) . ssLastError)) . snd) (zip [0..] $ F.toList servers) servers' = F.foldr' (\(idx, server) accum -> Seq.update idx server { ssAvailable = True } accum) servers availableAgain nextWakeup = F.foldr' (\s nwu -> if not (ssAvailable s) && maybe False (<= nwu) (ssLastError s) then fromJust . ssLastError $ s else nwu) cutoff servers' writeTVar psServers servers' return nextWakeup delay <- (sleepTil `diffUTCTime`) <$> getCurrentTime statusDump <- atomically $ readTVar psServers debugM "Database.Cassandra.CQL.poolWatch" $ "completed : delaying for " ++ show delay ++ ", server states : " ++ show statusDump threadDelay (floor $ delay * 1000000) loop loop serverStats :: Pool -> IO [ServerStat] serverStats (Pool (PoolState { psServers }, _)) = atomically $ do servers <- readTVar psServers return $ map (\ServerState { ssServer, ssSessionCount, ssAvailable } -> ServerStat { statServer = ssServer, statSessionCount = ssSessionCount, statAvailable = ssAvailable }) (F.toList servers) newSession :: PoolState -> IO Session newSession poolState@PoolState { psConfig, psServers } = do debugM "Database.Cassandra.CQL.nextSession" "starting" maskingState <- getMaskingState when (maskingState == Unmasked) $ throwIO $ userError "caller MUST mask async exceptions before attempting to create a session" startTime <- getCurrentTime let giveUpAt = piSessionCreateTimeout psConfig `addUTCTime` startTime loop = do timeLeft <- (giveUpAt `diffUTCTime`) <$> getCurrentTime when (timeLeft <= 0) $ throwIO NoAvailableServers debugM "Database.Cassandra.CQL.newSession" "starting attempt to create a new session" sessionZ <- timeout ((floor $ timeLeft * 1000000) :: Int) makeSession `catches` [ Handler $ (\(e :: CassandraCommsError) -> do warningM "Database.Cassandra.CQL.newSession" $ "failed to create a session due to temporary error (will retry) : " ++ show e return Nothing), Handler $ (\(e :: SomeException) -> do warningM "Database.Cassandra.CQL.newSession" $ "failed to create a session due to permanent error (will rethrow) : " ++ show e throwIO e) ] case sessionZ of Just session -> return session Nothing -> loop makeSession = bracketOnError chooseServer restoreCount setup chooseServer = atomically $ do servers <- readTVar psServers let available = filter (ssAvailable . snd) (zip [0..] $ F.toList servers) if null available then retry else do let (idx, best @ ServerState { ssSessionCount }) = minimumBy (compare `on` snd) available updatedBest = best { ssSessionCount = ssSessionCount + 1 } modifyTVar' psServers (Seq.update idx updatedBest) return (updatedBest, idx) restoreCount (_, idx) = do now <- getCurrentTime atomically $ modifyTVar' psServers (Seq.adjust (\s -> s { ssSessionCount = ssSessionCount s - 1, ssLastError = Just now, ssAvailable = False }) idx) setup (ServerState { ssServer }, idx) = setupConnection poolState idx ssServer loop destroySession :: PoolState -> Session -> IO () destroySession PoolState { psServers } Session { sessSocket, sessServerIndex } = mask $ \restore -> do atomically $ modifyTVar' psServers (Seq.adjust (\s -> s { ssSessionCount = ssSessionCount s - 1 }) sessServerIndex) restore (sClose sessSocket) setupConnection :: PoolState -> Int -> Server -> IO Session setupConnection PoolState { psConfig } serverIndex server = do let hints = defaultHints { addrSocketType = Stream } (host, service) = server debugM "Database.Cassandra.CQL.setupConnection" $ "attempting to connect to " ++ host startTime <- getCurrentTime ais <- getAddrInfo (Just hints) (Just host) (Just service) bracketOnError (connectSocket startTime ais) (maybe (return ()) sClose) buildSession where connectSocket startTime ais = foldM (\mSocket ai -> do case mSocket of Nothing -> do let tryConnect = do debugM "Database.Cassandra.CQL.setupConnection" $ "trying address " ++ show ai -- No need to use 'bracketOnError' here because we are already masked. s <- socket (addrFamily ai) (addrSocketType ai) (addrProtocol ai) mConn <- timeout ((floor $ (piConnectionTimeout psConfig) * 1000000) :: Int) (connect s (addrAddress ai)) `onException` sClose s case mConn of Nothing -> sClose s >> return Nothing Just _ -> return $ Just s now <- getCurrentTime if now `diffUTCTime` startTime >= piConnectionTimeout psConfig then return Nothing else tryConnect `catch` (\ (e :: SomeException) -> do debugM "Database.Cassandra.CQL.setupConnection" $ "failed to connect to address " ++ show ai ++ " : " ++ show e return Nothing ) Just _ -> return mSocket ) Nothing ais buildSession (Just s) = do debugM "Database.Cassandra.CQL.setupConnection" $ "made connection, now attempting setup for socket " ++ show s let active = Session { sessServerIndex = serverIndex, sessServer = server, sessSocket = s } evalStateT (introduce psConfig) (activeSession psConfig active) return active buildSession Nothing = throwIO NoAvailableServers data Flag = Compression | Tracing deriving Show putFlags :: [Flag] -> Put putFlags flags = putWord8 $ foldl' (+) 0 $ map toWord8 flags where toWord8 Compression = 0x01 toWord8 Tracing = 0x02 getFlags :: Get [Flag] getFlags = do flagsB <- getWord8 return $ case flagsB .&. 3 of 0 -> [] 1 -> [Compression] 2 -> [Tracing] 3 -> [Compression, Tracing] _ -> error "recvFrame impossible" data Opcode = ERROR | STARTUP | READY | AUTHENTICATE | OPTIONS | SUPPORTED | QUERY | RESULT | PREPARE | EXECUTE | REGISTER | EVENT | BATCH | AUTH_CHALLENGE | AUTH_RESPONSE | AUTH_SUCCESS deriving (Eq, Show) instance Serialize Opcode where put op = putWord8 $ case op of ERROR -> 0x00 STARTUP -> 0x01 READY -> 0x02 AUTHENTICATE -> 0x03 OPTIONS -> 0x05 SUPPORTED -> 0x06 QUERY -> 0x07 RESULT -> 0x08 PREPARE -> 0x09 EXECUTE -> 0x0a REGISTER -> 0x0b EVENT -> 0x0c BATCH -> 0x0d AUTH_CHALLENGE -> 0x0e AUTH_RESPONSE -> 0x0f AUTH_SUCCESS -> 0x10 get = do w <- getWord8 case w of 0x00 -> return ERROR 0x01 -> return STARTUP 0x02 -> return READY 0x03 -> return AUTHENTICATE 0x05 -> return OPTIONS 0x06 -> return SUPPORTED 0x07 -> return QUERY 0x08 -> return RESULT 0x09 -> return PREPARE 0x0a -> return EXECUTE 0x0b -> return REGISTER 0x0c -> return EVENT 0x0d -> return BATCH 0x0e -> return AUTH_CHALLENGE 0x0f -> return AUTH_RESPONSE 0x10 -> return AUTH_SUCCESS _ -> fail $ "unknown opcode 0x"++showHex w "" data Frame a = Frame { _frFlags :: [Flag], _frStream :: Int16, frOpcode :: Opcode, frBody :: a } deriving Show timeout' :: NominalDiffTime -> IO a -> IO a timeout' to = timeout (floor $ to * 1000000) >=> maybe (throwIO CoordinatorTimeout) return recvAll :: NominalDiffTime -> Socket -> Int -> IO ByteString recvAll ioTimeout s n = timeout' ioTimeout $ do bs <- recv s n when (B.null bs) $ throw ShortRead let left = n - B.length bs if left == 0 then return bs else do bs' <- recvAll ioTimeout s left return (bs `B.append` bs') protocolVersion :: Word8 protocolVersion = 3 recvFrame :: Text -> StateT ActiveSession IO (Frame ByteString) recvFrame qt = do s <- gets actSocket ioTimeout <- gets actIoTimeout hdrBs <- liftIO $ recvAll ioTimeout s 9 case runGet parseHeader hdrBs of Left err -> throw $ LocalProtocolError ("recvFrame: " `T.append` T.pack err) qt Right (ver0, flags, stream, opcode, length) -> do let ver = ver0 .&. 0x7f when (ver /= protocolVersion) $ throw $ LocalProtocolError ("unexpected version " `T.append` T.pack (show ver)) qt body <- if length == 0 then pure B.empty else liftIO $ recvAll ioTimeout s (fromIntegral length) --liftIO $ putStrLn $ hexdump 0 (C.unpack $ hdrBs `B.append` body) return $ Frame flags stream opcode body `catch` \exc -> throw $ CassandraIOException exc where parseHeader = do ver <- getWord8 flags <- getFlags stream <- fromIntegral <$> getWord16be opcode <- get length <- getWord32be return (ver, flags, stream, opcode, length) sendFrame :: Frame ByteString -> StateT ActiveSession IO () sendFrame (Frame flags stream opcode body) = do let bs = runPut $ do putWord8 protocolVersion putFlags flags putWord16be (fromIntegral stream) put opcode putWord32be $ fromIntegral $ B.length body putByteString body --liftIO $ putStrLn $ hexdump 0 (C.unpack bs) s <- gets actSocket ioTimeout <- gets actIoTimeout liftIO $ timeout' ioTimeout $ sendAll s bs `catch` \exc -> throw $ CassandraIOException exc class ProtoElt a where getElt :: Get a putElt :: a -> Put encodeElt :: ProtoElt a => a -> ByteString encodeElt = runPut . putElt encodeCas :: CasType a => a -> ByteString encodeCas = runPut . putCas decodeElt :: ProtoElt a => ByteString -> Either String a decodeElt bs = runGet getElt bs decodeCas :: CasType a => ByteString -> Either String a decodeCas bs = runGet getCas bs decodeEltM :: (ProtoElt a, MonadIO m) => Text -> ByteString -> Text -> m a decodeEltM what bs qt = case decodeElt bs of Left err -> throw $ LocalProtocolError ("can't parse" `T.append` what `T.append` ": " `T.append` T.pack err) qt Right res -> return res newtype Long a = Long { unLong :: a } deriving (Eq, Ord, Show, Read) instance Functor Long where f `fmap` Long a = Long (f a) newtype Short a = Short { unShort :: a } deriving (Eq, Ord, Show, Read) instance Functor Short where f `fmap` Short a = Short (f a) instance ProtoElt (Map Text Text) where putElt = putElt . M.assocs getElt = M.fromList <$> getElt instance ProtoElt [(Text, Text)] where putElt pairs = do putWord16be (fromIntegral $ length pairs) forM_ pairs $ \(key, value) -> do putElt key putElt value getElt = do n <- getWord16be replicateM (fromIntegral n) $ do key <- getElt value <- getElt return (key, value) instance ProtoElt Text where putElt = putElt . T.encodeUtf8 getElt = T.decodeUtf8 <$> getElt instance ProtoElt (Long Text) where putElt = putElt . fmap T.encodeUtf8 getElt = fmap T.decodeUtf8 <$> getElt instance ProtoElt ByteString where putElt bs = do putWord16be (fromIntegral $ B.length bs) putByteString bs getElt = do len <- getWord16be getByteString (fromIntegral len) instance ProtoElt (Long ByteString) where putElt (Long bs) = do putWord32be (fromIntegral $ B.length bs) putByteString bs getElt = do len <- getWord32be Long <$> getByteString (fromIntegral len) data TransportDirection = TransportSending | TransportReceiving deriving (Eq, Show) -- | An exception that indicates an error originating in the Cassandra server. data CassandraException = ServerError Text Text | ProtocolError Text Text | BadCredentials Text Text | UnavailableException Text Consistency Int Int Text | Overloaded Text Text | IsBootstrapping Text Text | TruncateError Text Text | WriteTimeout Text Consistency Int Int Text Text | ReadTimeout Text Consistency Int Int Bool Text | SyntaxError Text Text | Unauthorized Text Text | Invalid Text Text | ConfigError Text Text | AlreadyExists Text Keyspace Table Text | Unprepared Text PreparedQueryID Text deriving (Show, Typeable) instance Exception CassandraException where -- | All errors at the communications level are reported with this exception -- ('IOException's from socket I/O are always wrapped), and this exception -- typically would mean that a retry is warranted. -- -- Note that this exception isn't guaranteed to be a transient one, so a limit -- on the number of retries is likely to be a good idea. -- 'LocalProtocolError' probably indicates a corrupted database or driver -- bug. data CassandraCommsError = AuthenticationException Text | LocalProtocolError Text Text | MissingAuthenticationError Text Text | ValueMarshallingException TransportDirection Text Text | CassandraIOException IOException | CreateKeyspaceError Text Text | ShortRead | NoAvailableServers | CoordinatorTimeout deriving (Show, Typeable) instance Exception CassandraCommsError throwError :: MonadCatchIO m => Text -> ByteString -> m a throwError qt bs = do case runGet parseError bs of Left err -> throw $ LocalProtocolError ("failed to parse error: " `T.append` T.pack err) qt Right exc -> throw exc where parseError :: Get CassandraException parseError = do code <- getWord32be case code of 0x0000 -> ServerError <$> getElt <*> pure qt 0x000A -> ProtocolError <$> getElt <*> pure qt 0x0100 -> BadCredentials <$> getElt <*> pure qt 0x1000 -> UnavailableException <$> getElt <*> getElt <*> (fromIntegral <$> getWord32be) <*> (fromIntegral <$> getWord32be) <*> pure qt 0x1001 -> Overloaded <$> getElt <*> pure qt 0x1002 -> IsBootstrapping <$> getElt <*> pure qt 0x1003 -> TruncateError <$> getElt <*> pure qt 0x1100 -> WriteTimeout <$> getElt <*> getElt <*> (fromIntegral <$> getWord32be) <*> (fromIntegral <$> getWord32be) <*> getElt <*> pure qt 0x1200 -> ReadTimeout <$> getElt <*> getElt <*> (fromIntegral <$> getWord32be) <*> (fromIntegral <$> getWord32be) <*> ((/=0) <$> getWord8) <*> pure qt 0x2000 -> SyntaxError <$> getElt <*> pure qt 0x2100 -> Unauthorized <$> getElt <*> pure qt 0x2200 -> Invalid <$> getElt <*> pure qt 0x2300 -> ConfigError <$> getElt <*> pure qt 0x2400 -> AlreadyExists <$> getElt <*> getElt <*> getElt <*> pure qt 0x2500 -> Unprepared <$> getElt <*> getElt <*> pure qt _ -> fail $ "unknown error code 0x"++showHex code "" type UserId = String type Password = String data Authentication = PasswordAuthenticator UserId Password type Credentials = Long ByteString authCredentials :: Authentication -> Credentials authCredentials (PasswordAuthenticator user password) = Long $ C8BS.pack $ "\0" ++ user ++ "\0" ++ password authenticate :: Authentication -> StateT ActiveSession IO () authenticate auth = do let qt = "<auth_response>" sendFrame $ Frame [] 0 AUTH_RESPONSE $ encodeElt $ authCredentials auth fr2 <- recvFrame qt case frOpcode fr2 of AUTH_SUCCESS -> return () ERROR -> throwError qt (frBody fr2) op -> throw $ LocalProtocolError ("introduce: unexpected opcode " `T.append` T.pack (show op)) qt introduce :: PoolConfig -> StateT ActiveSession IO () introduce PoolConfig { piKeyspace, piKeyspaceConfig, piAuth } = do let qt = "<startup>" sendFrame $ Frame [] 0 STARTUP $ encodeElt $ ([("CQL_VERSION", "3.0.0")] :: [(Text, Text)]) fr <- recvFrame qt case frOpcode fr of AUTHENTICATE -> maybe (throw $ MissingAuthenticationError "introduce: server expects auth but none provided" "<credentials>") authenticate piAuth READY -> return () ERROR -> throwError qt (frBody fr) op -> throw $ LocalProtocolError ("introduce: unexpected opcode " `T.append` T.pack (show op)) qt let Keyspace ksName = piKeyspace case piKeyspaceConfig of Nothing -> return () Just cfg -> do let q = query $ cfg :: Query Schema () () res <- executeInternal q () QUORUM case res of SchemaChange _ _ _ -> return () _ -> throw $ CreateKeyspaceError ("introduce: failed to create a keyspace: " `T.append` T.pack (show res)) (queryText q) let q = query $ "USE " `T.append` ksName :: Query Rows () () res <- executeInternal q () ONE case res of SetKeyspace ks -> return () _ -> throw $ LocalProtocolError ("introduce: expected SetKeyspace, but got " `T.append` T.pack (show res)) (queryText q) withSession :: MonadCassandra m => (Pool -> StateT ActiveSession IO a) -> m a withSession code = do pool@(Pool (PoolState { psConfig }, sessions)) <- getCassandraPool liftIO $ mask $ \restore -> do (session, local') <- P.takeResource sessions a <- restore (evalStateT (code pool) (activeSession psConfig session)) `catches` [ Handler $ \(exc :: CassandraException) -> P.putResource local' session >> throwIO exc, Handler $ \(exc :: SomeException) -> P.destroyResource sessions local' session >> throwIO exc ] P.putResource local' session return a activeSession :: PoolConfig -> Session -> ActiveSession activeSession poolConfig session = ActiveSession { actServer = sessServer session, actSocket = sessSocket session, actIoTimeout = piIoTimeout poolConfig, actQueryCache = M.empty } -- | The name of a Cassandra keyspace. See the Cassandra documentation for more -- information. newtype Keyspace = Keyspace Text deriving (Eq, Ord, Show, IsString, ProtoElt) -- | The name of a Cassandra table (a.k.a. column family). newtype Table = Table Text deriving (Eq, Ord, Show, IsString, ProtoElt) -- | A fully qualified identification of a table that includes the 'Keyspace'. data TableSpec = TableSpec Keyspace Table deriving (Eq, Ord, Show) instance ProtoElt TableSpec where putElt _ = error "formatting TableSpec is not implemented" getElt = TableSpec <$> getElt <*> getElt -- | Information about a table column. data ColumnSpec = ColumnSpec TableSpec Text CType deriving Show -- | The specification of a list of result set columns. data Metadata = Metadata [ColumnSpec] deriving Show -- | Cassandra data types as used in metadata. data CType = CCustom Text | CAscii | CBigint | CBlob | CBoolean | CCounter | CDecimal | CDouble | CFloat | CInt | CText | CTimestamp | CUuid | CVarint | CTimeuuid | CInet | CList CType | CMap CType CType | CSet CType | CMaybe CType | CUDT [CType] | CTuple [CType] deriving (Eq) instance Show CType where show ct = case ct of CCustom name -> T.unpack name CAscii -> "ascii" CBigint -> "bigint" CBlob -> "blob" CBoolean -> "boolean" CCounter -> "counter" CDecimal -> "decimal" CDouble -> "double" CFloat -> "float" CInt -> "int" CText -> "text" CTimestamp -> "timestamp" CUuid -> "uuid" CVarint -> "varint" CTimeuuid -> "timeuuid" CInet -> "inet" CList t -> "list<"++show t++">" CMap t1 t2 -> "map<"++show t1++","++show t2++">" CSet t -> "set<"++show t++">" CMaybe t -> "nullable "++show t CUDT ts -> "udt<" ++ (intercalate "," $ fmap show ts) ++ ">" CTuple ts -> "tuple<" ++ (intercalate "," $ fmap show ts) ++ ">" equivalent :: CType -> CType -> Bool equivalent (CTuple a) (CTuple b) = all (\ (x,y) -> x `equivalent` y) $ zip a b equivalent (CMaybe a) (CMaybe b) = a == b equivalent (CMaybe a) b = a == b equivalent a (CMaybe b) = a == b equivalent a b = a == b -- | A type class for types that can be used in query arguments or column values in -- returned results. -- -- To define your own newtypes for Cassandra data, you only need to define 'getCas', -- 'putCas' and 'casType', like this: -- -- > newtype UserId = UserId UUID deriving (Eq, Show) -- > -- > instance CasType UserId where -- > getCas = UserId <$> getCas -- > putCas (UserId i) = putCas i -- > casType (UserId i) = casType i -- -- The same can be done more simply using the /GeneralizedNewtypeDeriving/ language -- extension, e.g. -- -- > {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- > -- > ... -- > newtype UserId = UserId UUID deriving (Eq, Show, CasType) -- -- If you have a more complex type you want to store as a Cassandra blob, you could -- write an instance like this (assuming it's an instance of the /cereal/ package's -- 'Serialize' class): -- -- > instance CasType User where -- > getCas = decode . unBlob <$> getCas -- > putCas = putCas . Blob . encode -- > casType _ = CBlob class CasType a where getCas :: Get a putCas :: a -> Put -- | For a given Haskell type given as ('undefined' :: a), tell the caller how Cassandra -- represents it. casType :: a -> CType casNothing :: a casNothing = error "casNothing impossible" casObliterate :: a -> ByteString -> Maybe ByteString casObliterate _ bs = Just bs instance CasType a => CasType (Maybe a) where getCas = Just <$> getCas putCas Nothing = return () putCas (Just a) = putCas a casType _ = CMaybe (casType (undefined :: a)) casNothing = Nothing casObliterate (Just a) bs = Just bs casObliterate Nothing _ = Nothing instance CasType ByteString where getCas = getByteString =<< remaining putCas = putByteString casType _ = CAscii instance CasType Int64 where getCas = fromIntegral <$> getWord64be putCas = putWord64be . fromIntegral casType _ = CBigint -- | If you wrap this round a 'ByteString', it will be treated as a /blob/ type -- instead of /ascii/ (if it was a plain 'ByteString' type). newtype Blob = Blob { unBlob :: ByteString } deriving (Eq, Ord, Show) instance CasType Blob where getCas = Blob <$> (getByteString =<< remaining) putCas (Blob bs) = putByteString bs casType _ = CBlob instance CasType Bool where getCas = (/= 0) <$> getWord8 putCas True = putWord8 1 putCas False = putWord8 0 casType _ = CBoolean -- | A Cassandra distributed counter value. newtype Counter = Counter { unCounter :: Int64 } deriving (Eq, Ord, Show, Read) instance CasType Counter where getCas = Counter . fromIntegral <$> getWord64be putCas (Counter c) = putWord64be (fromIntegral c) casType _ = CCounter instance CasType Integer where getCas = do ws <- B.unpack <$> (getByteString =<< remaining) return $ if null ws then 0 else let i = foldl' (\i w -> i `shiftL` 8 + fromIntegral w) 0 ws in if head ws >= 0x80 then i - 1 `shiftL` (length ws * 8) else i putCas i = putByteString . B.pack $ if i < 0 then encodeNeg $ positivize 0x80 i else encodePos i where encodePos :: Integer -> [Word8] encodePos i = reverse $ enc i where enc i | i == 0 = [0] enc i | i < 0x80 = [fromIntegral i] enc i = fromIntegral i : enc (i `shiftR` 8) encodeNeg :: Integer -> [Word8] encodeNeg i = reverse $ enc i where enc i | i == 0 = [] enc i | i < 0x100 = [fromIntegral i] enc i = fromIntegral i : enc (i `shiftR` 8) positivize :: Integer -> Integer -> Integer positivize bits i = case bits + i of i' | i' >= 0 -> i' + bits _ -> positivize (bits `shiftL` 8) i casType _ = CVarint instance CasType Decimal where getCas = Decimal <$> (fromIntegral . min 0xff <$> getWord32be) <*> getCas putCas (Decimal places mantissa) = do putWord32be (fromIntegral places) putCas mantissa casType _ = CDecimal instance CasType Double where getCas = unsafeCoerce <$> getWord64be putCas dbl = putWord64be (unsafeCoerce dbl) casType _ = CDouble instance CasType Float where getCas = unsafeCoerce <$> getWord32be putCas dbl = putWord32be (unsafeCoerce dbl) casType _ = CFloat epoch :: UTCTime epoch = UTCTime (fromGregorian 1970 1 1) 0 instance CasType UTCTime where getCas = do ms <- getWord64be let difft = realToFrac $ (fromIntegral ms :: Pico) / 1000 return $ addUTCTime difft epoch putCas utc = do let seconds = realToFrac $ diffUTCTime utc epoch :: Pico ms = round (seconds * 1000) :: Word64 putWord64be ms casType _ = CTimestamp instance CasType Int where getCas = fromIntegral <$> getWord32be putCas = putWord32be . fromIntegral casType _ = CInt instance CasType Text where getCas = T.decodeUtf8 <$> (getByteString =<< remaining) putCas = putByteString . T.encodeUtf8 casType _ = CText instance CasType UUID where getCas = do mUUID <- UUID.fromByteString . L.fromStrict <$> (getByteString =<< remaining) case mUUID of Just uuid -> return uuid Nothing -> fail "malformed UUID" putCas = putByteString . L.toStrict . UUID.toByteString casType _ = CUuid -- | If you wrap this round a 'UUID' then it is treated as a /timeuuid/ type instead of -- /uuid/ (if it was a plain 'UUID' type). newtype TimeUUID = TimeUUID { unTimeUUID :: UUID } deriving (Eq, Data, Ord, Read, Show, Typeable) instance CasType TimeUUID where getCas = TimeUUID <$> getCas putCas (TimeUUID uuid) = putCas uuid casType _ = CTimeuuid instance CasType SockAddr where getCas = do len <- remaining case len of 4 -> SockAddrInet 0 <$> getWord32le 16 -> do a <- getWord32be b <- getWord32be c <- getWord32be d <- getWord32be return $ SockAddrInet6 0 0 (a,b,c,d) 0 _ -> fail "malformed Inet" putCas sa = do case sa of SockAddrInet _ w -> putWord32le w SockAddrInet6 _ _ (a,b,c,d) _ -> putWord32be a >> putWord32be b >> putWord32be c >> putWord32be d _ -> fail $ "address type not supported in formatting Inet: " ++ show sa casType _ = CInet instance CasType a => CasType [a] where getCas = do n <- getWord32be replicateM (fromIntegral n) $ do len <- getWord32be bs <- getByteString (fromIntegral len) case decodeCas bs of Left err -> fail err Right x -> return x putCas xs = do putWord32be (fromIntegral $ length xs) forM_ xs $ \x -> do let bs = encodeCas x putWord32be (fromIntegral $ B.length bs) putByteString bs casType _ = CList (casType (undefined :: a)) instance (CasType a, Ord a) => CasType (Set a) where getCas = S.fromList <$> getCas putCas = putCas . S.toList casType _ = CSet (casType (undefined :: a)) instance (CasType a, Ord a, CasType b) => CasType (Map a b) where getCas = do n <- getWord32be items <- replicateM (fromIntegral n) $ do len_a <- getWord32be bs_a <- getByteString (fromIntegral len_a) a <- case decodeCas bs_a of Left err -> fail err Right x -> return x len_b <- getWord32be bs_b <- getByteString (fromIntegral len_b) b <- case decodeCas bs_b of Left err -> fail err Right x -> return x return (a,b) return $ M.fromList items putCas m = do let items = M.toList m putWord32be (fromIntegral $ length items) forM_ items $ \(a,b) -> do putOption a putOption b casType _ = CMap (casType (undefined :: a)) (casType (undefined :: b)) getString :: Get Text getString = do len <- getWord16be bs <- getByteString (fromIntegral len) return $ T.decodeUtf8 bs putString :: Text -> Put putString x = do putWord16be (fromIntegral $ B.length val) putByteString val where val = T.encodeUtf8 x getOption :: CasType a => Get a getOption = do len <- getWord32be bs <- getByteString (fromIntegral len) case decodeCas bs of Left err -> fail err Right x -> return x putOption :: CasType a => a -> Put putOption x = do let bs = encodeCas x putWord32be (fromIntegral $ B.length bs) putByteString bs instance (CasType a, CasType b) => CasType (a,b) where getCas = do x <- getOption y <- getOption return (x,y) putCas (x,y) = do putOption x putOption y casType _ = CTuple [casType (undefined :: a), casType (undefined :: b)] instance (CasType a, CasType b, CasType c) => CasType(a,b,c) where getCas = do x <- getOption y <- getOption z <- getOption return (x,y,z) putCas (x,y,z) = do putOption x putOption y putOption z casType _ = CTuple [casType (undefined :: a), casType (undefined :: b), casType (undefined :: c)] instance (CasType a,CasType b, CasType c, CasType d) => CasType(a,b,c,d) where getCas = do w <- getOption x <- getOption y <- getOption z <- getOption return (w,x,y,z) putCas (w,x,y,z) = do putOption w putOption x putOption y putOption z casType _ = CTuple [casType (undefined :: a), casType (undefined :: b), casType (undefined :: c), casType (undefined :: d)] instance (CasType a,CasType b, CasType c, CasType d, CasType e) => CasType(a,b,c,d,e) where getCas = do v <- getOption w <- getOption x <- getOption y <- getOption z <- getOption return (v,w,x,y,z) putCas (v,w,x,y,z) = do putOption v putOption w putOption x putOption y putOption z casType _ = CTuple [casType (undefined :: a), casType (undefined :: b), casType (undefined :: c), casType (undefined :: d), casType (undefined :: e)] instance ProtoElt CType where putElt _ = error "formatting CType is not implemented" getElt = do op <- getWord16be case op of 0x0000 -> CCustom <$> getElt 0x0001 -> pure CAscii 0x0002 -> pure CBigint 0x0003 -> pure CBlob 0x0004 -> pure CBoolean 0x0005 -> pure CCounter 0x0006 -> pure CDecimal 0x0007 -> pure CDouble 0x0008 -> pure CFloat 0x0009 -> pure CInt --0x000a -> pure CVarchar -- Server seems to use CText even when 'varchar' is specified -- i.e. they're interchangeable in the CQL and always -- 'text' in the protocol. 0x000b -> pure CTimestamp 0x000c -> pure CUuid 0x000d -> pure CText 0x000e -> pure CVarint 0x000f -> pure CTimeuuid 0x0010 -> pure CInet 0x0020 -> CList <$> getElt 0x0021 -> CMap <$> getElt <*> getElt 0x0022 -> CSet <$> getElt 0x0030 -> CUDT <$> getEltUdt 0x0031 -> CTuple <$> getElt _ -> fail $ "unknown data type code 0x"++showHex op "" getEltUdt = do _ <- getString _ <- getString n <- getWord16be replicateM (fromIntegral n) $ do _ <- getString getElt instance ProtoElt Metadata where putElt _ = error "formatting Metadata is not implemented" getElt = do flags <- getWord32be colCount <- fromIntegral <$> getWord32be gtSpec <- if (flags .&. 1) /= 0 then Just <$> getElt else pure Nothing cols <- replicateM colCount $ do tSpec <- case gtSpec of Just spec -> pure spec Nothing -> getElt ColumnSpec tSpec <$> getElt <*> getElt return $ Metadata cols instance ProtoElt [CType] where getElt = do n <- getWord16be replicateM (fromIntegral n) getElt putElt x = do putWord16be (fromIntegral $ length x) forM_ x putElt newtype PreparedQueryID = PreparedQueryID ByteString deriving (Eq, Ord, Show, ProtoElt) newtype QueryID = QueryID (Digest SHA1) deriving (Eq, Ord, Show) -- | The first type argument for Query. Tells us what kind of query it is. data Style = Schema -- ^ A query that modifies the schema, such as DROP TABLE or CREATE TABLE | Write -- ^ A query that writes data, such as an INSERT or UPDATE | Rows -- ^ A query that returns a list of rows, such as SELECT -- | The text of a CQL query, along with type parameters to make the query type safe. -- The type arguments are 'Style', followed by input and output column types for the -- query each represented as a tuple. -- -- The /DataKinds/ language extension is required for 'Style'. data Query :: Style -> * -> * -> * where Query :: QueryID -> Text -> Query style i o deriving Show queryText :: Query s i o -> Text queryText (Query _ txt) = txt instance IsString (Query style i o) where fromString = query . T.pack -- | Construct a query. Another way to construct one is as an overloaded string through -- the 'IsString' instance if you turn on the /OverloadedStrings/ language extension, e.g. -- -- > {-# LANGUAGE OverloadedStrings #-} -- > ... -- > -- > getOneSong :: Query Rows UUID (Text, Text, Maybe Text) -- > getOneSong = "select title, artist, comment from songs where id=?" query :: Text -> Query style i o query cql = Query (QueryID . hash . T.encodeUtf8 $ cql) cql data PreparedQuery = PreparedQuery PreparedQueryID Metadata deriving Show data Change = CREATED | UPDATED | DROPPED deriving (Eq, Ord, Show) instance ProtoElt Change where putElt _ = error $ "formatting Change is not implemented" getElt = do str <- getElt :: Get Text case str of "CREATED" -> pure CREATED "UPDATED" -> pure UPDATED "DROPPED" -> pure DROPPED _ -> fail $ "unexpected change string: "++show str -- | A low-level query result used with 'executeRaw'. data Result vs = Void | RowsResult Metadata [vs] | SetKeyspace Text | Prepared PreparedQueryID Metadata | SchemaChange Change Keyspace Table deriving Show instance Functor Result where f `fmap` Void = Void f `fmap` RowsResult meta rows = RowsResult meta (f `fmap` rows) f `fmap` SetKeyspace ks = SetKeyspace ks f `fmap` Prepared pqid meta = Prepared pqid meta f `fmap` SchemaChange ch ks t = SchemaChange ch ks t instance ProtoElt (Result [Maybe ByteString]) where putElt _ = error "formatting RESULT is not implemented" getElt = do kind <- getWord32be case kind of 0x0001 -> pure Void 0x0002 -> do meta@(Metadata colSpecs) <- getElt let colCount = length colSpecs rowCount <- fromIntegral <$> getWord32be rows <- replicateM rowCount $ replicateM colCount $ do len <- getWord32be if len == 0xffffffff then return Nothing else Just <$> getByteString (fromIntegral len) return $ RowsResult meta rows 0x0003 -> SetKeyspace <$> getElt 0x0004 -> Prepared <$> getElt <*> getElt 0x0005 -> SchemaChange <$> getElt <*> getElt <*> getElt _ -> fail $ "bad result kind: 0x"++showHex kind "" prepare :: Query style i o -> StateT ActiveSession IO PreparedQuery prepare (Query qid cql) = do cache <- gets actQueryCache case qid `M.lookup` cache of Just pq -> return pq Nothing -> do sendFrame $ Frame [] 0 PREPARE $ encodeElt (Long cql) fr <- recvFrame cql case frOpcode fr of RESULT -> do res <- decodeEltM "RESULT" (frBody fr) cql case (res :: Result [Maybe ByteString]) of Prepared pqid meta -> do let pq = PreparedQuery pqid meta modify $ \act -> act { actQueryCache = M.insert qid pq (actQueryCache act) } return pq _ -> throw $ LocalProtocolError ("prepare: unexpected result " `T.append` T.pack (show res)) cql ERROR -> throwError cql (frBody fr) _ -> throw $ LocalProtocolError ("prepare: unexpected opcode " `T.append` T.pack (show (frOpcode fr))) cql data CodingFailure = Mismatch Int CType CType | WrongNumber Int Int | DecodeFailure Int String | NullValue Int CType instance Show CodingFailure where show (Mismatch i t1 t2) = "at value index "++show (i+1)++", Haskell type specifies "++show t1++", but database metadata says "++show t2 show (WrongNumber i1 i2) = "wrong number of values: Haskell type specifies "++show i1++" but database metadata says "++show i2 show (DecodeFailure i why) = "failed to decode value index "++show (i+1)++": "++why show (NullValue i t) = "at value index "++show (i+1)++" received a null "++show t++" value but Haskell type is not a Maybe" class CasNested v where encodeNested :: Int -> v -> [CType] -> Either CodingFailure [Maybe ByteString] decodeNested :: Int -> [(CType, Maybe ByteString)] -> Either CodingFailure v countNested :: v -> Int instance CasNested () where encodeNested !i () [] = Right [] encodeNested !i () ts = Left $ WrongNumber i (i + length ts) decodeNested !i [] = Right () decodeNested !i vs = Left $ WrongNumber i (i + length vs) countNested _ = 0 instance (CasType a, CasNested rem) => CasNested (a, rem) where encodeNested !i (a, rem) (ta:trem) | ta `equivalent` casType a = case encodeNested (i+1) rem trem of Left err -> Left err Right brem -> Right $ ba : brem where ba = casObliterate a . encodeCas $ a encodeNested !i (a, _) (ta:_) = Left $ Mismatch i (casType a) ta encodeNested !i vs [] = Left $ WrongNumber (i + countNested vs) i decodeNested !i ((ta, mba):rem) | ta `equivalent` casType (undefined :: a) = case (decodeCas <$> mba, casType (undefined :: a), decodeNested (i+1) rem) of (Nothing, CMaybe _, Right arem) -> Right (casNothing, arem) (Nothing, _, _) -> Left $ NullValue i ta (Just (Left err), _, _) -> Left $ DecodeFailure i err (_, _, Left err) -> Left err (Just (Right a), _, Right arem) -> Right (a, arem) decodeNested !i ((ta, _):rem) = Left $ Mismatch i (casType (undefined :: a)) ta decodeNested !i [] = Left $ WrongNumber (i + 1 + countNested (undefined :: rem)) i countNested _ = let n = 1 + countNested (undefined :: rem) in seq n n -- | A type class for a tuple of 'CasType' instances, representing either a list of -- arguments for a query, or the values in a row of returned query results. class CasValues v where encodeValues :: v -> [CType] -> Either CodingFailure [Maybe ByteString] decodeValues :: [(CType, Maybe ByteString)] -> Either CodingFailure v instance CasValues () where encodeValues () types = encodeNested 0 () types decodeValues vs = decodeNested 0 vs instance CasType a => CasValues a where encodeValues a = encodeNested 0 (a, ()) decodeValues vs = (\(a, ()) -> a) <$> decodeNested 0 vs instance (CasType a, CasType b) => CasValues (a, b) where encodeValues (a, b) = encodeNested 0 (a, (b, ())) decodeValues vs = (\(a, (b, ())) -> (a, b)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c) => CasValues (a, b, c) where encodeValues (a, b, c) = encodeNested 0 (a, (b, (c, ()))) decodeValues vs = (\(a, (b, (c, ()))) -> (a, b, c)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d) => CasValues (a, b, c, d) where encodeValues (a, b, c, d) = encodeNested 0 (a, (b, (c, (d, ())))) decodeValues vs = (\(a, (b, (c, (d, ())))) -> (a, b, c, d)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e) => CasValues (a, b, c, d, e) where encodeValues (a, b, c, d, e) = encodeNested 0 (a, (b, (c, (d, (e, ()))))) decodeValues vs = (\(a, (b, (c, (d, (e, ()))))) -> (a, b, c, d, e)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f) => CasValues (a, b, c, d, e, f) where encodeValues (a, b, c, d, e, f) = encodeNested 0 (a, (b, (c, (d, (e, (f, ())))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, ())))))) -> (a, b, c, d, e, f)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g) => CasValues (a, b, c, d, e, f, g) where encodeValues (a, b, c, d, e, f, g) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, ()))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, ()))))))) -> (a, b, c, d, e, f, g)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h) => CasValues (a, b, c, d, e, f, g, h) where encodeValues (a, b, c, d, e, f, g, h) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, ())))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, ())))))))) -> (a, b, c, d, e, f, g, h)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i) => CasValues (a, b, c, d, e, f, g, h, i) where encodeValues (a, b, c, d, e, f, g, h, i) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, ()))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, ()))))))))) -> (a, b, c, d, e, f, g, h, i)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j) => CasValues (a, b, c, d, e, f, g, h, i, j) where encodeValues (a, b, c, d, e, f, g, h, i, j) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, ())))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, ())))))))))) -> (a, b, c, d, e, f, g, h, i, j)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j, CasType k) => CasValues (a, b, c, d, e, f, g, h, i, j, k) where encodeValues (a, b, c, d, e, f, g, h, i, j, k) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, ()))))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, ()))))))))))) -> (a, b, c, d, e, f, g, h, i, j, k)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j, CasType k, CasType l) => CasValues (a, b, c, d, e, f, g, h, i, j, k, l) where encodeValues (a, b, c, d, e, f, g, h, i, j, k, l) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, ())))))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, ())))))))))))) -> (a, b, c, d, e, f, g, h, i, j, k, l)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j, CasType k, CasType l, CasType m) => CasValues (a, b, c, d, e, f, g, h, i, j, k, l, m) where encodeValues (a, b, c, d, e, f, g, h, i, j, k, l, m) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, ()))))))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, ()))))))))))))) -> (a, b, c, d, e, f, g, h, i, j, k, l, m)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j, CasType k, CasType l, CasType m, CasType n) => CasValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n) where encodeValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, ())))))))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, ())))))))))))))) -> (a, b, c, d, e, f, g, h, i, j, k, l, m, n)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j, CasType k, CasType l, CasType m, CasType n, CasType o) => CasValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) where encodeValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, ()))))))))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, ()))))))))))))))) -> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j, CasType k, CasType l, CasType m, CasType n, CasType o, CasType p) => CasValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) where encodeValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, ())))))))))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, ())))))))))))))))) -> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j, CasType k, CasType l, CasType m, CasType n, CasType o, CasType p, CasType q) => CasValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q) where encodeValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, ()))))))))))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, ()))))))))))))))))) -> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j, CasType k, CasType l, CasType m, CasType n, CasType o, CasType p, CasType q, CasType r) => CasValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r) where encodeValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, ())))))))))))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, ())))))))))))))))))) -> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j, CasType k, CasType l, CasType m, CasType n, CasType o, CasType p, CasType q, CasType r, CasType s) => CasValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s) where encodeValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, (s, ()))))))))))))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, (s, ()))))))))))))))))))) -> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j, CasType k, CasType l, CasType m, CasType n, CasType o, CasType p, CasType q, CasType r, CasType s, CasType t) => CasValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t) where encodeValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, (s, (t, ())))))))))))))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, (s, (t, ())))))))))))))))))))) -> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j, CasType k, CasType l, CasType m, CasType n, CasType o, CasType p, CasType q, CasType r, CasType s, CasType t, CasType u) => CasValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u) where encodeValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, (s, (t,(u, ()))))))))))))))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, (s, (t, (u, ()))))))))))))))))))))) -> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j, CasType k, CasType l, CasType m, CasType n, CasType o, CasType p, CasType q, CasType r, CasType s, CasType t, CasType u, CasType v) => CasValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v) where encodeValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u,v) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, (s, (t,(u, (v, ())))))))))))))))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, (s, (t, (u, (v, ())))))))))))))))))))))) -> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j, CasType k, CasType l, CasType m, CasType n, CasType o, CasType p, CasType q, CasType r, CasType s, CasType t, CasType u, CasType v, CasType w) => CasValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w) where encodeValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, (s, (t,(u, (v, (w, ()))))))))))))))))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, (s, (t, (u, (v, (w, ()))))))))))))))))))))))) -> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j, CasType k, CasType l, CasType m, CasType n, CasType o, CasType p, CasType q, CasType r, CasType s, CasType t, CasType u, CasType v, CasType w, CasType x) => CasValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x) where encodeValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, (s, (t,(u, (v, (w, (x, ())))))))))))))))))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, (s, (t, (u, (v, (w, (x, ())))))))))))))))))))))))) -> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j, CasType k, CasType l, CasType m, CasType n, CasType o, CasType p, CasType q, CasType r, CasType s, CasType t, CasType u, CasType v, CasType w, CasType x, CasType y) => CasValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y) where encodeValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, (s, (t,(u, (v, (w, (x, (y, ()))))))))))))))))))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, (s, (t, (u, (v, (w, (x, (y, ()))))))))))))))))))))))))) -> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y)) <$> decodeNested 0 vs instance (CasType a, CasType b, CasType c, CasType d, CasType e, CasType f, CasType g, CasType h, CasType i, CasType j, CasType k, CasType l, CasType m, CasType n, CasType o, CasType p, CasType q, CasType r, CasType s, CasType t, CasType u, CasType v, CasType w, CasType x, CasType y, CasType z) => CasValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z) where encodeValues (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z) = encodeNested 0 (a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, (s, (t,(u, (v, (w, (x, (y, (z, ())))))))))))))))))))))))))) decodeValues vs = (\(a, (b, (c, (d, (e, (f, (g, (h, (i, (j, (k, (l, (m, (n, (o, (p, (q, (r, (s, (t, (u, (v, (w, (x, (y, (z, ())))))))))))))))))))))))))) -> (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z)) <$> decodeNested 0 vs -- | Cassandra consistency level. See the Cassandra documentation for an explanation. data Consistency = ANY | ONE | TWO | THREE | QUORUM | ALL | LOCAL_QUORUM | EACH_QUORUM | SERIAL | LOCAL_SERIAL | LOCAL_ONE deriving (Eq, Ord, Show, Bounded, Enum) instance ProtoElt Consistency where putElt c = putWord16be $ case c of ANY -> 0x0000 ONE -> 0x0001 TWO -> 0x0002 THREE -> 0x0003 QUORUM -> 0x0004 ALL -> 0x0005 LOCAL_QUORUM -> 0x0006 EACH_QUORUM -> 0x0007 SERIAL -> 0x0008 LOCAL_SERIAL -> 0x0009 LOCAL_ONE -> 0x000A getElt = do w <- getWord16be case w of 0x0000 -> pure ANY 0x0001 -> pure ONE 0x0002 -> pure TWO 0x0003 -> pure THREE 0x0004 -> pure QUORUM 0x0005 -> pure ALL 0x0006 -> pure LOCAL_QUORUM 0x0007 -> pure EACH_QUORUM 0x0008 -> pure SERIAL 0x0009 -> pure LOCAL_SERIAL 0x000A -> pure LOCAL_ONE _ -> fail $ "unknown consistency value 0x"++showHex w "" -- | A low-level function in case you need some rarely-used capabilities. executeRaw :: (MonadCassandra m, CasValues i) => Query style any_i any_o -> i -> Consistency -> m (Result [Maybe ByteString]) executeRaw query i cons = withSession (\_ -> executeInternal query i cons) executeInternal :: CasValues values => Query style any_i any_o -> values -> Consistency -> StateT ActiveSession IO (Result [Maybe ByteString]) executeInternal query i cons = do (PreparedQuery pqid queryMeta) <- prepare query values <- case encodeValues i (metadataTypes queryMeta) of Left err -> throw $ ValueMarshallingException TransportSending (T.pack $ show err) (queryText query) Right values -> return values sendFrame $ Frame [] 0 EXECUTE $ runPut $ do putElt pqid putElt cons putWord8 0x01 putWord16be (fromIntegral $ length values) forM_ values $ \mValue -> case mValue of Nothing -> putWord32be 0xffffffff Just value -> do let enc = encodeCas value putWord32be (fromIntegral $ B.length enc) putByteString enc fr <- recvFrame (queryText query) case frOpcode fr of RESULT -> decodeEltM "RESULT" (frBody fr) (queryText query) ERROR -> throwError (queryText query) (frBody fr) _ -> throw $ LocalProtocolError ("execute: unexpected opcode " `T.append` T.pack (show (frOpcode fr))) (queryText query) -- | Execute a query that returns rows. executeRows :: (MonadCassandra m, CasValues i, CasValues o) => Consistency -- ^ Consistency level of the operation -> Query Rows i o -- ^ CQL query to execute -> i -- ^ Input values substituted in the query -> m [o] executeRows cons q i = do res <- executeRaw q i cons case res of RowsResult meta rows -> decodeRows q meta rows _ -> throw $ LocalProtocolError ("expected Rows, but got " `T.append` T.pack (show res)) (queryText q) -- | Execute a lightweight transaction. The consistency level is implicit and -- is SERIAL. executeTrans :: (MonadCassandra m, CasValues i) => Query Write i () -- ^ CQL query to execute -> i -- ^ Input values substituted in the query -> m Bool executeTrans q i = do res <- executeRaw q i SERIAL case res of RowsResult _ ((el:row):rows) -> case decodeCas $ fromJust el of Left s -> error $ "executeTrans: decode result failure=" ++ s Right b -> return b _ -> throw $ LocalProtocolError ("expected Rows, but got " `T.append` T.pack (show res)) (queryText q) -- | Helper for 'executeRows' useful in situations where you are only expecting one row -- to be returned. executeRow :: (MonadCassandra m, CasValues i, CasValues o) => Consistency -- ^ Consistency level of the operation -> Query Rows i o -- ^ CQL query to execute -> i -- ^ Input values substituted in the query -> m (Maybe o) executeRow cons q i = do rows <- executeRows cons q i return $ listToMaybe rows decodeRows :: (MonadCatchIO m, CasValues values) => Query Rows any_i values -> Metadata -> [[Maybe ByteString]] -> m [values] decodeRows query meta rows0 = do let rows1 = flip map rows0 $ \cols -> decodeValues (zip (metadataTypes meta) cols) case lefts rows1 of (err:_) -> throw $ ValueMarshallingException TransportReceiving (T.pack $ show err) (queryText query) [] -> return () let rows2 = flip map rows1 $ \(Right v) -> v return $ rows2 -- | Execute a write operation that returns void. executeWrite :: (MonadCassandra m, CasValues i) => Consistency -- ^ Consistency level of the operation -> Query Write i () -- ^ CQL query to execute -> i -- ^ Input values substituted in the query -> m () executeWrite cons q i = do res <- executeRaw q i cons case res of Void -> return () _ -> throw $ LocalProtocolError ("expected Void, but got " `T.append` T.pack (show res)) (queryText q) -- | Execute a schema change, such as creating or dropping a table. executeSchema :: (MonadCassandra m, CasValues i) => Consistency -- ^ Consistency level of the operation -> Query Schema i () -- ^ CQL query to execute -> i -- ^ Input values substituted in the query -> m (Change, Keyspace, Table) executeSchema cons q i = do res <- executeRaw q i cons case res of SchemaChange ch ks ta -> return (ch, ks, ta) _ -> throw $ LocalProtocolError ("expected SchemaChange, but got " `T.append` T.pack (show res)) (queryText q) -- | Executes a schema change that has a void result such as creating types executeSchemaVoid :: (MonadCassandra m, CasValues i) => Consistency -- ^ Consistency level of the operation -> Query Schema i () -- ^ CQL query to execute -> i -- ^ Input values substituted in the query -> m () executeSchemaVoid cons q i = do res <- executeRaw q i cons case res of Void -> return () _ -> throw $ LocalProtocolError ("expected Void, but got " `T.append` T.pack (show res)) (queryText q) -- | A helper for extracting the types from a metadata definition. metadataTypes :: Metadata -> [CType] metadataTypes (Metadata colspecs) = map (\(ColumnSpec _ _ typ) -> typ) colspecs -- | The monad used to run Cassandra queries in. newtype Cas a = Cas (ReaderT Pool IO a) deriving (Functor, Applicative, Monad, MonadIO, MonadCatchIO) instance MonadCassandra Cas where getCassandraPool = Cas ask -- | Execute Cassandra queries. runCas :: Pool -> Cas a -> IO a runCas pool (Cas code) = runReaderT code pool
alphaHeavy/cassandra-cql
Database/Cassandra/CQL.hs
bsd-3-clause
76,172
1
35
23,812
26,886
14,921
11,965
1,403
17
module Main where import Lib import Test.QuickCheck import Test.QuickCheck.Checkers import Test.QuickCheck.Classes main :: IO () main = do putStrLn "Excercises from Chapter 25: Composing Types" putStrLn "Some examples commented out in main function." putStrLn "Use 'stack ghci' to start ghci to play around. Enjoy." --mapM_ (putStrLn . fizzBuzz) [1..100] --mapM_ putStrLn $ reverse $ fizzbuzzList [1..100] --mapM_ putStrLn $ fizzbuzzList' [1..100] --mapM_ putStrLn $ fizzbuzzFromTo 1 100
backofhan/HaskellExercises
CH25/app/Main.hs
bsd-3-clause
506
0
7
85
61
34
27
10
1
{-# LANGUAGE ExistentialQuantification #-} module Main where import Text.ParserCombinators.Parsec hiding (spaces) import System.Environment import Control.Monad import Control.Monad.Error import System.IO import Data.IORef data LispVal = Atom String | List [LispVal] | DottedList [LispVal] LispVal | Number Integer | String String | Bool Bool | PrimitiveFunc ([LispVal] -> ThrowsError LispVal) | Func { params :: [String], vararg :: (Maybe String), body :: [LispVal], closure :: Env } | IOFunc ([LispVal] -> IOThrowsError LispVal) | Port Handle instance Show LispVal where show = showVal data LispError = NumArgs Integer [LispVal] | TypeMismatch String LispVal | Parser ParseError | BadSpecialForm String LispVal | NotFunction String String | UnboundVar String String | Default String data Unpacker = forall a. Eq a => AnyUnpacker (LispVal -> ThrowsError a) showError :: LispError -> String showError (UnboundVar message varname) = message ++ ": " ++ varname showError (BadSpecialForm message form) = message ++ ": " ++ show form showError (NotFunction message func) = message ++ ": " ++ show func showError (NumArgs expected found) = "Expected " ++ show expected ++ " args; found values " ++ unwordsList found showError (TypeMismatch expected found) = "Invalid type: expected " ++ expected ++ ", found " ++ show found showError (Parser parseErr) = "Parse error at " ++ show parseErr instance Show LispError where show = showError instance Error LispError where noMsg = Default "An error has occurred" strMsg = Default type ThrowsError = Either LispError type Env = IORef [(String, IORef LispVal)] type IOThrowsError = ErrorT LispError IO trapError action = catchError action (return . show) extractValue :: ThrowsError a -> a extractValue (Right val) = val spaces :: Parser () spaces = skipMany1 space symbol :: Parser Char symbol = oneOf "!#$%&|*+=-/:<=>?@^_~" parseString :: Parser LispVal parseString = do char '"' x <- many (noneOf "\"") char '"' return $ String x parseAtom :: Parser LispVal parseAtom = do first <- letter <|> symbol rest <- many (letter <|> digit <|> symbol) let atom = first:rest return $ case atom of "#t" -> Bool True "#f" -> Bool False _ -> Atom atom parseNumber :: Parser LispVal parseNumber = liftM (Number . read) $ many1 digit parseList :: Parser LispVal parseList = liftM List $ sepBy parseExpr spaces parseDottedList :: Parser LispVal parseDottedList = do head <- endBy parseExpr spaces tail <- char '.' >> spaces >> parseExpr return $ DottedList head tail parseQuoted :: Parser LispVal parseQuoted = do char '\'' x <- parseExpr return $ List [Atom "quote", x] parseBothList :: Parser LispVal parseBothList = do char '(' x <- try parseList <|> parseDottedList char ')' return x parseExpr :: Parser LispVal parseExpr = parseAtom <|> parseString <|> parseNumber <|> parseQuoted <|> parseBothList showVal :: LispVal -> String showVal (String contents) = "\"" ++ contents ++ "\"" showVal (Atom name) = name showVal (Number contents) = show contents showVal (Bool True) = "#t" showVal (Bool False) = "#f" showVal (List contents) = "(" ++ unwordsList contents ++ ")" showVal (DottedList head tail) = "(" ++ unwordsList head ++ " . " ++ showVal tail ++ ")" showVal (PrimitiveFunc _) = "<primitive>" showVal (Func {params = args, vararg = varargs, body = body, closure = env}) = "(lambda (" ++ unwords (map show args) ++ (case varargs of Nothing -> "" Just arg -> " . " ++ arg) ++ ") ...)" showVal (Port _) = "<IO port>" showVal (IOFunc _) = "<IO primitive>" unwordsList :: [LispVal] -> String unwordsList = unwords . map showVal apply :: LispVal -> [LispVal] -> IOThrowsError LispVal apply (PrimitiveFunc func) args = liftThrows $ func args apply (Func params varargs body closure) args = if num params /= num args && varargs == Nothing then throwError $ NumArgs (num params) args else (liftIO $ bindVars closure $ zip params args) >>= bindVarArgs varargs >>= evalBody where remainingArgs = drop (length params) args num = toInteger . length evalBody env = liftM last $ mapM (eval env) body bindVarArgs arg env = case arg of Just argName -> liftIO $ bindVars env [(argName, List $ remainingArgs)] Nothing -> return env apply (IOFunc func) args = func args primitives :: [(String, [LispVal] -> ThrowsError LispVal)] primitives = [("+", numericBinop (+)), ("-", numericBinop (-)), ("*", numericBinop (*)), ("/", numericBinop div), ("=", numBoolBinop (==)), ("<", numBoolBinop (<)), (">", numBoolBinop (>)), ("/=", numBoolBinop (/=)), (">=", numBoolBinop (>=)), ("<=", numBoolBinop (<=)), ("&&", boolBoolBinop (&&)), ("||", boolBoolBinop (||)), ("string=?", strBoolBinop (==)), ("string<?", strBoolBinop (<)), ("string>?", strBoolBinop (>)), ("string<=?", strBoolBinop (<=)), ("string>=?", strBoolBinop (>=)), ("mod", numericBinop mod), ("quotient", numericBinop quot), ("remainder", numericBinop rem), ("car", car), ("cdr", cdr), ("cons", cons), ("eq?", eqv), ("eqv?", eqv), ("equal?", equal)] ioPrimitives :: [(String, [LispVal] -> IOThrowsError LispVal)] ioPrimitives = [("apply", applyProc), ("open-input-file", makePort ReadMode), ("open-output-file", makePort WriteMode), ("close-input-port", closePort), ("close-output-port", closePort), ("read", readProc), ("write", writeProc), ("read-contents", readContents), ("read-all", readAll)] primitiveBindings :: IO Env primitiveBindings = nullEnv >>= (flip bindVars $ map (makeFunc IOFunc) ioPrimitives ++ map (makeFunc PrimitiveFunc) primitives) where makeFunc constructor (var, func) = (var, constructor func) applyProc :: [LispVal] -> IOThrowsError LispVal applyProc [func, List args] = apply func args applyProc (func:args) = apply func args makePort :: IOMode -> [LispVal] -> IOThrowsError LispVal makePort mode [String filename] = liftM Port $ liftIO $ openFile filename mode closePort :: [LispVal] -> IOThrowsError LispVal closePort [Port port] = liftIO $ hClose port >> (return $ Bool True) closePort _ = return $ Bool False readProc :: [LispVal] -> IOThrowsError LispVal readProc [] = readProc [Port stdin] readProc [Port port] = (liftIO $ hGetLine port) >>= liftThrows . readExpr writeProc :: [LispVal] -> IOThrowsError LispVal writeProc [obj] = writeProc [obj, Port stdout] write [obj, Port port] = liftIO $ hPrint port obj >> (return $ Bool True) readContents :: [LispVal] -> IOThrowsError LispVal readContents [String filename] = liftM String $ liftIO $ readFile filename load :: String -> IOThrowsError [LispVal] load filename = (liftIO $ readFile filename) >>= liftThrows . readExprList readAll :: [LispVal] -> IOThrowsError LispVal readAll [String filename] = liftM List $ load filename numericBinop :: (Integer -> Integer -> Integer) -> [LispVal] -> ThrowsError LispVal numericBinop op [] = throwError $ NumArgs 2 [] numericBinop op singleVal@[_] = throwError $ NumArgs 2 singleVal numericBinop op params = mapM unpackNum params >>= return . Number . foldl1 op boolBinop :: (LispVal -> ThrowsError a) -> (a -> a -> Bool) -> [LispVal] -> ThrowsError LispVal boolBinop unpacker op args = if length args /= 2 then throwError $ NumArgs 2 args else do left <- unpacker $ args !! 0 right <- unpacker $ args !! 1 return $ Bool $ left `op` right numBoolBinop = boolBinop unpackNum strBoolBinop = boolBinop unpackStr boolBoolBinop = boolBinop unpackBool unpackStr :: LispVal -> ThrowsError String unpackStr (String s) = return s unpackStr (Number s) = return $ show s unpackStr (Bool s) = return $ show s unpackStr noString = throwError $ TypeMismatch "string" noString unpackBool :: LispVal -> ThrowsError Bool unpackBool (Bool b) = return b unpackBool notBool = throwError $ TypeMismatch "bool" notBool unpackNum :: LispVal -> ThrowsError Integer unpackNum (Number n) = return n unpackNum (String n) = let parsed = reads n in if null parsed then throwError $ TypeMismatch "number" $ String n else return $ fst $ parsed !! 0 unpackNum (List [n]) = unpackNum n unpackNum notNum = throwError $ TypeMismatch "number" notNum car :: [LispVal] -> ThrowsError LispVal car [List (x:xs)] = return x car [DottedList (x:xs) _] = return x car [badArg] = throwError $ TypeMismatch "pair" badArg car badArgList = throwError $ NumArgs 1 badArgList cdr :: [LispVal] -> ThrowsError LispVal cdr [List (x:xs)] = return $ List xs cdr [DottedList [_] x] = return x cdr [DottedList (_:xs) x] = return $ DottedList xs x cdr [badArg] = throwError $ TypeMismatch "pair" badArg cdr badArgList = throwError $ NumArgs 1 badArgList cons :: [LispVal] -> ThrowsError LispVal cons [x1, List []] = return $ List [x1] cons [x, List xs] = return $ List $ x:xs cons [x, DottedList xs xlast] = return $ DottedList (x:xs) xlast cons [x1, x2] = return $ DottedList [x1] x2 cons badArgList = throwError $ NumArgs 2 badArgList eqv :: [LispVal] -> ThrowsError LispVal eqv [(Bool arg1), (Bool arg2)] = return $ Bool $ arg1 == arg2 eqv [(Number arg1), (Number arg2)] = return $ Bool $ arg1 == arg2 eqv [(String arg1), (String arg2)] = return $ Bool $ arg1 == arg2 eqv [(Atom arg1), (Atom arg2)] = return $ Bool $ arg1 == arg2 eqv [(DottedList xs x), (DottedList ys y)] = eqv [List $ xs ++ [x], List $ ys ++ [y]] eqv [(List arg1), (List arg2)] = return $ Bool $ (length arg1 == length arg2) && (all eqvPair $ zip arg1 arg2) where eqvPair (x1, x2) = case eqv [x1, x2] of Left err -> False Right (Bool val) -> val eqv [_, _] = return $ Bool False eqv badArgList = throwError $ NumArgs 2 badArgList unpackEquals :: LispVal -> LispVal -> Unpacker -> ThrowsError Bool unpackEquals arg1 arg2 (AnyUnpacker unpacker) = do unpacked1 <- unpacker arg1 unpacked2 <- unpacker arg2 return $ unpacked1 == unpacked2 `catchError` (const $ return False) equal :: [LispVal] -> ThrowsError LispVal equal [arg1, arg2] = do primitiveEquals <- liftM or $ mapM (unpackEquals arg1 arg2) [AnyUnpacker unpackNum, AnyUnpacker unpackStr, AnyUnpacker unpackBool] eqvEquals <- eqv [arg1, arg2] return $ Bool $ (primitiveEquals || let (Bool x) = eqvEquals in x) equal badArgList = throwError $ NumArgs 2 badArgList eval :: Env -> LispVal -> IOThrowsError LispVal eval env val@(String _) = return val eval env val@(Number _) = return val eval env val@(Bool _) = return val eval env (Atom id) = getVar env id eval env (List [Atom "quote", val]) = return val eval env (List [Atom "if", pred, conseq, alt]) = do result <- eval env pred case result of Bool False -> eval env alt otherwise -> eval env conseq eval env (List [Atom "set!", Atom var, form]) = eval env form >>= setVar env var eval env (List [Atom "define", Atom var, form]) = eval env form >>= defineVar env var eval env (List (Atom "define" : List (Atom var : params) : body)) = makeNormalFunc env params body >>= defineVar env var eval env (List (Atom "define" : DottedList (Atom var : params) varargs : body)) = makeVarArgs varargs env params body >>= defineVar env var eval env (List (Atom "lambda" : List params : body)) = makeNormalFunc env params body eval env (List (Atom "lambda" : DottedList params varargs : body)) = makeVarArgs varargs env params body eval env (List (Atom "lambda" : varargs@(Atom _) : body)) = makeVarArgs varargs env [] body eval env (List [Atom "load", String filename]) = load filename >>= liftM last . mapM (eval env) -- eval env (List (Atom func:args)) = mapM (eval env) args >>= liftThrows . apply func eval env (List (function : args)) = do func <- eval env function argVals <- mapM (eval env) args apply func argVals eval env badForm = throwError $ BadSpecialForm "Unrecognized special form" badForm flushStr :: String -> IO () flushStr str = putStr str >> hFlush stdout readPrompt :: String -> IO String readPrompt prompt = flushStr prompt >> getLine evalString :: Env -> String -> IO String evalString env expr = runIOThrows $ liftM show $ (liftThrows $ readExpr expr) >>= eval env evalAndPrint :: Env -> String -> IO () evalAndPrint env expr = evalString env expr >>= putStrLn until_ :: Monad m => (a -> Bool) -> m a -> (a -> m ()) -> m () until_ pred prompt action = do result <- prompt if pred result then return () else action result >> until_ pred prompt action runOne :: [String] -> IO () runOne args = do env <- primitiveBindings >>= flip bindVars [("args", List $ map String $ drop 1 args)] (runIOThrows $ liftM show $ eval env (List [Atom "load", String (args !! 0)])) >>= hPutStrLn stderr runRepl :: IO () runRepl = primitiveBindings >>= until_ (== "quit") (readPrompt "Lisp>>>") . evalAndPrint nullEnv :: IO Env nullEnv = newIORef [] liftThrows :: ThrowsError a -> IOThrowsError a liftThrows (Left err) = throwError err liftThrows (Right val) = return val runIOThrows :: IOThrowsError String -> IO String runIOThrows action = runErrorT (trapError action) >>= return . extractValue isBound :: Env -> String -> IO Bool isBound envRef var = readIORef envRef >>= return . maybe False (const True) . lookup var getVar :: Env ->String -> IOThrowsError LispVal getVar envRef var = do env <- liftIO $ readIORef envRef maybe (throwError $ UnboundVar "Getting an unbound variable" var) (liftIO . readIORef) (lookup var env) setVar :: Env -> String -> LispVal -> IOThrowsError LispVal setVar envRef var value = do env <- liftIO $ readIORef envRef maybe (throwError $ UnboundVar "Setting an unbound variable" var) (liftIO . (flip writeIORef value)) (lookup var env) return value defineVar :: Env -> String -> LispVal -> IOThrowsError LispVal defineVar envRef var value = do alreadyDefined <- liftIO $ isBound envRef var if alreadyDefined then setVar envRef var value >> return value else liftIO $ do valueRef <- newIORef value env <- readIORef envRef writeIORef envRef ((var, valueRef) : env) return value bindVars :: Env -> [(String, LispVal)] -> IO Env bindVars envRef bindings = readIORef envRef >>= extendEnv bindings >>= newIORef where extendEnv bindings env = liftM (++ env) (mapM addBinding bindings) addBinding (var, value) = do ref <- newIORef value return (var, ref) makeFunc varargs env params body = return $ Func (map showVal params) varargs body env makeNormalFunc = makeFunc Nothing makeVarArgs = makeFunc . Just . showVal readOrThrow :: Parser a -> String -> ThrowsError a readOrThrow parser input = case parse parser "lisp" input of Left err -> throwError $ Parser err Right val -> return val readExpr = readOrThrow parseExpr readExprList = readOrThrow (endBy parseExpr spaces) main :: IO () main = do args <- getArgs if null args then runRepl else runOne $ args
alexmacedo/scheme48
src/Main.hs
bsd-3-clause
16,303
0
16
4,347
5,906
2,998
2,908
356
3
module Language.POL.Syntax ( Contract ( Zero, Data , Give , And, Or , If, IfNot , When, Anytime, Until ) , zero, pdata , give , and, or , ifobs, ifnot , when, anytime, until , foldAnd, foldOr , foldLeaves, mapLeaves ) where import Data.POL.Observable ( ObservableT ) import Prelude hiding ( and, or, until ) import Text.Printf ( printf ) import Control.Monad ( liftM2, mplus ) import Control.Arrow ( first, second ) import qualified Data.Set as Set ( empty, null, member , insert, delete, deleteFindMax , union, fold , fromList, toAscList ) import qualified Data.Map as Map ( empty, member , insert, insertWith , unionWith , foldWithKey , toList ) import Data.Set ( Set ) import Data.Map ( Map ) infixr 3 `And` infixr 2 `Or` data Contract a p l m = Zero | Data a p | Give (Contract a p l m) | And (Contract a p l m) (Contract a p l m) | Or (Contract a p l m) (Contract a p l m) | If (ObservableT l m Bool) (Contract a p l m) | IfNot (ObservableT l m Bool) (Contract a p l m) | When (ObservableT l m Bool) (Contract a p l m) | Anytime (ObservableT l m Bool) (Contract a p l m) | Until (ObservableT l m Bool) (Contract a p l m) deriving (Eq, Ord) instance (Show a, Show p, Show l) => Show (Contract a p l m) where show Zero = "zero" show (Data a p) = printf "pdata %s %s" (show a) (show p) show (Give c) = printf "give (%s)" (show c) show (c1 `And` c2) = printf "(%s) `and` (%s)" (show c1) (show c2) show (c1 `Or` c2) = printf "(%s) `or` (%s)" (show c1) (show c2) show (If o c) = printf "ifobs (%s) (%s)" (show o) (show c) show (IfNot o c) = printf "ifnot (%s) (%s)" (show o) (show c) show (When o c) = printf "when (%s) (%s)" (show o) (show c) show (Anytime o c) = printf "anytime (%s) (%s)" (show o) (show c) show (Until o c) = printf "until (%s) (%s)" (show o) (show c) zero :: Contract a p l m zero = Zero pdata :: a -> p -> Contract a p l m pdata = Data give :: Contract a p l m -> Contract a p l m give Zero = zero -- (R1) give (Give c) = c -- (R2) give c = Give c infixr 3 `and` and :: (Ord a, Ord p, Ord l) => Contract a p l m -> Contract a p l m -> Contract a p l m c `and` Zero = c -- (R3) Zero `and` c = c -- (R4) (Give c1) `and` (Give c2) = give (c1 `and` c2) -- (R5) c1 `and` c2 = sortAnd (c1 `And` c2) -- (~R6) infixr 2 `or` or :: (Ord a, Ord p, Ord l) => Contract a p l m -> Contract a p l m -> Contract a p l m c `or` d | c == d = c -- (R7) c1 `or` c2 = sortOr (c1 `Or` c2) -- new (R9-12) ifobs :: (Ord a, Ord p, Ord l) => ObservableT l m Bool -> Contract a p l m -> Contract a p l m ifobs _ Zero = zero ifobs o (Give c) = give (ifobs o c) -- (R13) ifobs o (c1 `And` c2) = (ifobs o c1) `and` (ifobs o c2) -- (R15) ifobs o (c1 `Or` c2) = (ifobs o c1) `or` (ifobs o c2) -- (R17) ifobs o (If p c) | o == p = ifobs o c -- (R19) ifobs o (IfNot p _) | o == p = zero -- (R20) ifobs o (Until p _) | o == p = zero -- (R24) ifobs o (When p c) | o == p = ifobs o c -- (R23) ifobs o c = If o c ifnot :: (Ord a, Ord p, Ord l) => ObservableT l m Bool -> Contract a p l m -> Contract a p l m ifnot _ Zero = zero ifnot o (Give c) = give (ifnot o c) -- (R14) ifnot o (c1 `And` c2) = (ifnot o c1) `and` (ifnot o c2) -- (R16) ifnot o (c1 `Or` c2) = (ifnot o c1) `or` (ifnot o c2) -- (R18) ifnot o (If p _) | o == p = zero -- (R21) ifnot o (IfNot p c) | o == p = ifnot o c -- (R22) ifnot o (Until p c) | o == p = until o c -- (R25) ifnot o c = IfNot o c when :: (Ord a, Ord p, Ord l) => ObservableT l m Bool -> Contract a p l m -> Contract a p l m when = liftM2 (.) flat deep where flat _ Zero = zero -- (R26) flat o (Give c) = give (when o c) -- (R27) flat o (c1 `And` c2) = (when o c1) `and` (when o c2) -- (R28) flat o c | allAnytime o c = c -- (R32) flat o c = When o c deep o = mapLeaves reduce' where reduce' (If p c) | o == p = c -- (R29) reduce' (IfNot p _) | o == p = zero -- (R30) reduce' (When p c) | o == p = c -- (R31) reduce' (Until p _) | o == p = zero -- (R33) reduce' c = c anytime :: (Ord a, Ord p, Ord l) => ObservableT l m Bool -> Contract a p l m -> Contract a p l m anytime = liftM2 (.) flat deep where flat _ Zero = zero -- (R34) flat o c = Anytime o c deep o = mapLeaves reduce' where reduce' (If p c) | o == p = c -- (R36) reduce' (IfNot p _) | o == p = zero -- (R37) reduce' (When p c) | o == p = c -- (R38) reduce' (Anytime p c) | o == p = c -- (R39) reduce' (Until p _) | o == p = zero -- (R40) reduce' c = c until :: (Ord a, Ord p, Ord l) => ObservableT l m Bool -> Contract a p l m -> Contract a p l m until = liftM2 (.) flat deep where flat _ Zero = zero -- (R41) flat o c = Until o c deep o = mapLeaves reduce' where reduce' (If p _) | o == p = zero -- (R43) reduce' (IfNot p c) | o == p = c -- (R44) reduce' (When p _) | o == p = zero -- (R45) reduce' (Anytime p _) | o == p = zero -- (R46) reduce' (Until p c) | o == p = c -- (R47) reduce' c = c foldAnd :: (Contract a p l m -> x -> x) -> x -> Contract a p l m -> x foldAnd f x (left `And` right) = foldAnd f (foldAnd f x left) right foldAnd f x tree = f tree x foldOr :: (Contract a p l m -> x -> x) -> x -> Contract a p l m -> x foldOr f x (left `Or` right) = foldOr f (foldOr f x left) right foldOr f x tree = f tree x foldLeaves :: (Contract a p l m -> x -> x) -> x -> Contract a p l m -> x foldLeaves f x (l `And` r) = foldLeaves f (foldLeaves f x l) r foldLeaves f x (l `Or` r) = foldLeaves f (foldLeaves f x l) r foldLeaves f x tree = f tree x allAnytime :: Eq l => ObservableT l m Bool -> Contract a p l m -> Bool allAnytime o = foldLeaves isAnytime True where isAnytime (Anytime p _) x = x && o == p isAnytime _ _ = False mapLeaves :: (Ord a, Ord p, Ord l) => (Contract a p l m -> Contract a p l m) -> Contract a p l m -> Contract a p l m mapLeaves f (l `And` r) = mapLeaves f l `and` mapLeaves f r mapLeaves f (l `Or` r) = mapLeaves f l `or` mapLeaves f r mapLeaves f c = f c sortAnd :: (Ord a, Ord p, Ord l) => Contract a p l m -> Contract a p l m sortAnd = unfoldAnd . foldAnd consFoldedAnd nullFoldedAnd data FoldedAnd a p l m = FoldedAnd { ifs :: Map (ObservableT l m Bool, Contract a p l m) (Int, Int) , occs :: Map (Contract a p l m) Int } nullFoldedAnd :: FoldedAnd a p l m nullFoldedAnd = FoldedAnd { ifs = Map.empty , occs = Map.empty } (+|+) :: (Int,Int) -> (Int,Int) -> (Int,Int) (+|+) (a,b) (c,d) = (a+c,b+d) consFoldedAnd :: (Ord a, Ord p, Ord l) => Contract a p l m -> FoldedAnd a p l m -> FoldedAnd a p l m consFoldedAnd (If o c) fa = fa { ifs = Map.insertWith (+|+) (o,c) (1,0) (ifs fa) } consFoldedAnd (IfNot o c) fa = fa { ifs = Map.insertWith (+|+) (o,c) (0,1) (ifs fa) } consFoldedAnd c fa = fa { occs = Map.insertWith (+) c 1 (occs fa) } unfoldAnd :: (Ord a, Ord p, Ord l) => FoldedAnd a p l m -> Contract a p l m unfoldAnd fa = (foldr1 And . expand . join) [occs fa, ifs'] where ifs' = Map.foldWithKey merge Map.empty (ifs fa) merge (o,c) (a,b) | a > b = Map.insert (If o c) (a-b) . Map.insert c b | a < b = Map.insert (IfNot o c) (b-a) . Map.insert c a | otherwise = Map.insert c a join :: (Ord a, Num b) => [Map a b] -> Map a b join = foldr (Map.unionWith (+)) Map.empty expand :: Map a Int -> [a] expand = Map.foldWithKey (((++) .) . flip replicate) [] sortOr :: (Ord a, Ord p, Ord l) => Contract a p l m -> Contract a p l m sortOr = unfoldOr . foldOr consFoldedOr nullFoldedOr data FoldedOr a p l m = FoldedOr { ols :: Set (Contract a p l m) , ands :: Set (Contract a p l m) , als :: Map (Contract a p l m) Int } nullFoldedOr :: FoldedOr a p l m nullFoldedOr = FoldedOr { ols = Set.empty , ands = Set.empty , als = Map.empty } consFoldedOr :: (Ord a, Ord p, Ord l) => Contract a p l m -> FoldedOr a p l m -> FoldedOr a p l m consFoldedOr c@(_ `And` _) = fld addAnd . fld addAls where fld = flip (flip . foldr) (expandAnd c) consFoldedOr c = addOl c addAls :: (Ord a, Ord p, Ord l) => Contract a p l m -> FoldedOr a p l m -> FoldedOr a p l m addAls c r | Set.member c (ands r) = r addAls c r = foldAnd (liftM2 (.) mvOl addAl) r c addAnd :: (Ord a, Ord p, Ord l) => Contract a p l m -> FoldedOr a p l m -> FoldedOr a p l m addAnd c r = r { ands = Set.insert c (ands r) } addOl :: (Ord a, Ord p, Ord l) => Contract a p l m -> FoldedOr a p l m -> FoldedOr a p l m addOl c r | Map.member c (als r) = addAl c $ addAnd c r addOl c r = r { ols = Set.insert c (ols r) } addAl :: (Ord a, Ord p, Ord l) => Contract a p l m -> FoldedOr a p l m -> FoldedOr a p l m addAl c r = r { als = Map.insertWith (+) c 1 (als r) } mvOl :: (Ord a, Ord p, Ord l) => Contract a p l m -> FoldedOr a p l m -> FoldedOr a p l m mvOl c r | Set.member c (ols r) = addAl c $ addAnd c $ r { ols = Set.delete c (ols r) } mvOl _ r = r expandAnd :: Contract a p l m -> [Contract a p l m] expandAnd = map (foldr1 And) . expandAnd' expandAnd' :: Contract a p l m -> [[Contract a p l m]] expandAnd' (c `And` d) = do cs <- expandAnd' c ds <- expandAnd' d return (cs ++ ds) expandAnd' (c `Or` d) = expandAnd' c `mplus` expandAnd' d expandAnd' c = return [c] unfoldOr :: (Ord a, Ord p, Ord l) => FoldedOr a p l m -> Contract a p l m unfoldOr r = foldr1 Or $ Set.toAscList $ ols r `Set.union` factors (freq (als r)) (ands r) freq :: (Ord a, Ord b) => Map a b -> Set (b,a) freq = Set.fromList . map (uncurry (flip (,))) . Map.toList factors :: (Ord a, Ord p, Ord l) => Set (Int, Contract a p l m) -> Set (Contract a p l m) -> Set (Contract a p l m) factors ls ts | Set.null ls = Set.empty | Set.null ts = Set.empty | otherwise = maybe lessfreq (flip Set.insert lessfreq) fact where (leaf, ls') = first snd $ Set.deleteFindMax ls (fact, ts') = factor leaf ts lessfreq = factors ls' ts' factor :: (Ord a, Ord p, Ord l) => Contract a p l m -> Set (Contract a p l m) -> (Maybe (Contract a p l m), Set (Contract a p l m)) factor leaf = first consTree . Set.fold (reduce leaf) empty where consTree ls | Set.null ls = Nothing | otherwise = Just $ and leaf $ foldr1 or $ Set.toAscList ls empty = (Set.empty, Set.empty) reduce :: (Ord a, Ord p, Ord l) => Contract a p l m -> Contract a p l m -> (Set (Contract a p l m), Set (Contract a p l m)) -> (Set (Contract a p l m), Set (Contract a p l m)) reduce leaf tree@(And _ _) | inTree = first (Set.insert reducedTree) where (inTree, ls) = foldAnd (red leaf) (False, Set.empty) tree reducedTree = (foldr1 And . Set.toAscList) ls reduce leaf tree | leaf == tree = first (Set.insert zero) | otherwise = second (Set.insert tree) red :: (Ord a, Ord p, Ord l) => Contract a p l m -> Contract a p l m -> (Bool, Set (Contract a p l m)) -> (Bool, Set (Contract a p l m)) red leaf tleaf ls | not (fst ls) && tleaf == leaf = first (const True) ls | otherwise = second (Set.insert tleaf) ls -- vim: ft=haskell:sts=2:sw=2:et:nu:ai
ZjMNZHgG5jMXw/privacy-option
Language/POL/Syntax.hs
bsd-3-clause
12,647
0
12
4,603
6,139
3,156
2,983
279
9
-- | DOT AST. See <http://www.graphviz.org/doc/info/lang.html>. module Language.Dot.Syntax where data Graph = Graph GraphStrictness GraphDirectedness (Maybe Id) [Statement] deriving (Eq, Show) data GraphStrictness = StrictGraph | UnstrictGraph deriving (Eq, Show) data GraphDirectedness = DirectedGraph | UndirectedGraph deriving (Eq, Show) data Id = NameId String | StringId String | IntegerId Integer | FloatId Float | XmlId Xml deriving (Eq, Show) data Statement = NodeStatement NodeId [Attribute] | EdgeStatement [Entity] [Attribute] | AttributeStatement AttributeStatementType [Attribute] | AssignmentStatement Id Id | SubgraphStatement Subgraph deriving (Eq, Show) data AttributeStatementType = GraphAttributeStatement | NodeAttributeStatement | EdgeAttributeStatement deriving (Eq, Show) data Attribute = AttributeSetTrue Id | AttributeSetValue Id Id deriving (Eq, Show) data NodeId = NodeId Id (Maybe Port) deriving (Eq, Show) data Port = PortI Id (Maybe Compass) | PortC Compass deriving (Eq, Show) data Compass = CompassN | CompassE | CompassS | CompassW | CompassNE | CompassNW | CompassSE | CompassSW deriving (Eq, Show) data Subgraph = NewSubgraph (Maybe Id) [Statement] | SubgraphRef Id deriving (Eq, Show) data Entity = ENodeId EdgeType NodeId | ESubgraph EdgeType Subgraph deriving (Eq, Show) data EdgeType = NoEdge | DirectedEdge | UndirectedEdge deriving (Eq, Show) data Xml = XmlEmptyTag XmlName [XmlAttribute] | XmlTag XmlName [XmlAttribute] [Xml] | XmlText String deriving (Eq, Show) data XmlName = XmlName String deriving (Eq, Show) data XmlAttribute = XmlAttribute XmlName XmlAttributeValue deriving (Eq, Show) data XmlAttributeValue = XmlAttributeValue String deriving (Eq, Show)
bsl/language-dot
src/Language/Dot/Syntax.hs
bsd-3-clause
1,872
0
8
397
532
303
229
73
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} module BankObject where import GHC.Generics import Control.Applicative (empty) import Data.Int import Data.Time import Data.Aeson import Data.Aeson.Types() import qualified Data.Text as T import Data.Monoid import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.FromRow import Database.PostgreSQL.Simple.ToRow import Database.PostgreSQL.Simple.ToField data TagType = TagType { tagTypeId :: Int64, tagTypeName :: T.Text, tagTypeKind :: T.Text } deriving (Generic, Show) instance ToJSON TagType where toJSON (TagType idV nameV kindV) = object ["id" .= idV, "name" .= nameV, "kind" .= kindV] toEncoding (TagType idV nameV kindV) = pairs $ "id" .= idV <> "name" .= nameV <> "kind" .= kindV instance FromJSON TagType where parseJSON (Object v) = TagType <$> v .: "id" <*> v .: "name" <*> v .: "kind" parseJSON _ = empty instance ToRow TagType instance FromRow TagType data Tag = Tag { tagBankObjectId :: Int64, tagTagTypeId :: Int64, tagValue :: Value } deriving (Generic, Show) instance ToJSON Tag where toJSON (Tag tagBankObjectIdV tagTypeIdV valueV) = object ["tagBankObjectId" .= tagBankObjectIdV, "tagTypeId" .= tagTypeIdV, "value" .= valueV] toEncoding (Tag tagBankObjectIdV tagTypeIdV valueV) = pairs $ "tagBankObjectId" .= tagBankObjectIdV <> "tagTypeId" .= tagTypeIdV <> "value" .= valueV instance FromJSON Tag where parseJSON (Object v) = Tag <$> v .: "tagBankObjectId" <*> v .: "tagTypeId" <*> v .: "value" parseJSON _ = empty instance FromRow Tag instance ToRow Tag data BankObjectTag = BankObjectTag { bankObjectTagTypeName :: T.Text, bankObjectTagValue :: Value } deriving (Generic, Show) instance ToJSON BankObjectTag where toJSON (BankObjectTag bankObjectTagTypeNameV bankObjectTagValueV) = object ["name" .= bankObjectTagTypeNameV, "value" .= bankObjectTagValueV] toEncoding (BankObjectTag bankObjectTagTypeNameV bankObjectTagValueV) = pairs $ "name" .= bankObjectTagTypeNameV <> "value" .= bankObjectTagValueV instance FromJSON BankObjectTag where parseJSON (Object v) = BankObjectTag <$> v .: "name" <*> v .: "value" parseJSON _ = empty instance FromRow BankObjectTag data BankObject = BankObject { bankObjectId :: Int64, bankObjectName :: T.Text, bankObjectCreated :: UTCTime, bankObjectUpdated :: UTCTime, bankObjectTags :: [BankObjectTag] } deriving (Generic, Show) instance ToJSON BankObject where toJSON (BankObject idV nameV createdV updatedV tagsV) = object ["id" .= idV, "name" .= nameV, "created" .= createdV, "updated" .= updatedV, "tags" .= tagsV] toEncoding (BankObject idV nameV createdV updatedV tagsV) = pairs $ "id" .= idV <> "name" .= nameV <> "created" .= createdV <> "updated" .= updatedV <> "tags" .= tagsV instance FromJSON BankObject where parseJSON (Object v) = BankObject <$> v .: "id" <*> v .: "name" <*> v .: "created" <*> v .: "updated" <*> v .: "tags" parseJSON _ = empty instance ToRow BankObject where toRow (BankObject bankObjectIdV bankObjectNameV bankObjectCreatedV bankObjectUpdatedV _) = [ toField bankObjectIdV , toField bankObjectNameV , toField bankObjectCreatedV , toField bankObjectUpdatedV ] instance FromRow BankObject where fromRow = BankObject <$> field <*> field <*> field <*> field <*> pure []
paradoxix/haskellplayground
src/BankObject.hs
bsd-3-clause
3,776
0
15
984
992
530
462
91
0
module Main where import qualified PPTest.Builders.Dfa import qualified PPTest.Builders.Lalr import qualified PPTest.Builders.Lr1 import qualified PPTest.Builders.Nfa import qualified PPTest.Grammars.Ebnf import qualified PPTest.Grammars.Lexical import qualified PPTest.Grammars.LexicalHelper import qualified PPTest.Lexers.Dfa import qualified PPTest.Other.LexerDfaParserLr import qualified PPTest.Parsers.Lr import qualified PPTest.Rule import qualified PPTest.Template import qualified PPTest.Templates.Dfa import qualified PPTest.Templates.Lr import Test.Hspec main :: IO () main = hspec $ describe "PPTest" $ do PPTest.Grammars.Ebnf.specs PPTest.Rule.specs PPTest.Builders.Lr1.specs PPTest.Builders.Lalr.specs PPTest.Parsers.Lr.specs PPTest.Templates.Lr.specs PPTest.Grammars.LexicalHelper.specs PPTest.Grammars.Lexical.specs PPTest.Builders.Nfa.specs PPTest.Builders.Dfa.specs PPTest.Lexers.Dfa.specs PPTest.Other.LexerDfaParserLr.specs PPTest.Templates.Dfa.specs PPTest.Template.specs
chlablak/platinum-parsing
test/Spec.hs
bsd-3-clause
1,062
0
8
143
227
141
86
33
1