code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-} module Web.Authenticate.SQRL.Client.Types where import Web.Authenticate.SQRL.Types import Data.ByteString (ByteString) import Data.Text (Text) import Control.Exception (SomeException) import Data.Maybe (fromMaybe) import qualified Crypto.Ed25519.Exceptions as ED25519 type FullRealm = Text type Password = Text newtype PublicLockKey = PublicLockKey { publicLockKey :: ByteString } newtype RescueCode = RescueCode { rescueCode :: Text } --newtype PrivateIdentityKey = PrivateIdentityKey { privateIdentityKey :: ByteString } newtype PrivateMasterKey = PrivateMasterKey { privateMasterKey :: ByteString } deriving (Show, Eq) newtype PrivateUnlockKey = PrivateUnlockKey { privateUnlockKey :: ByteString } deriving (Show, Eq) newtype PrivateLockKey = PrivateLockKey { privateLockKey :: ByteString } deriving (Show, Eq) class (PublicKey pub, DomainKey priv, Signature sig) => KeyPair priv pub sig | priv -> pub sig where -- | Generates a public key from a 'DomainKey'. generatePublic :: priv -> pub generatePublic = mkPublicKey . ED25519.exportPublic . ED25519.generatePublic . fromMaybe (error "KeyPair.generatePublic: importPrivate returned Nothing.") . ED25519.importPrivate . domainKey signData :: priv -> pub -> ByteString -> sig signData priv' pub' bs = let ED25519.Sig sig = ED25519.sign bs priv pub priv = fromMaybe (error "KeyPair.signData: importPrivate returned Nothing.") $ ED25519.importPrivate $ domainKey priv' pub = fromMaybe (error "KeyPair.signData: importPublic returned Nothing.") $ ED25519.importPublic $ publicKey pub' in mkSignature sig instance KeyPair DomainIdentityKey IdentityKey IdentitySignature class PrivateKey k where privateKey :: k -> ByteString mkPrivateKey :: ByteString -> k instance PrivateKey PrivateMasterKey where privateKey = privateMasterKey mkPrivateKey = PrivateMasterKey instance PrivateKey PrivateUnlockKey where privateKey = privateUnlockKey mkPrivateKey = PrivateUnlockKey instance PrivateKey PrivateLockKey where privateKey = privateLockKey mkPrivateKey = PrivateLockKey newtype DomainLockKey = DomainLockKey { domainLockKey :: ByteString } deriving (Show, Eq) newtype DomainIdentityKey = DomainIdentityKey { domainIdentityKey :: ByteString } deriving (Show, Eq) class DomainKey k where domainKey :: k -> ByteString mkDomainKey :: ByteString -> k instance DomainKey DomainLockKey where domainKey = domainLockKey mkDomainKey = DomainLockKey instance DomainKey DomainIdentityKey where domainKey = domainIdentityKey mkDomainKey = DomainIdentityKey data ClientErr = ClientErrNone | ClientErrLoginAborted | ClientErrAskAborted | ClientErrAssocAborted | ClientErrNoProfile | ClientErrWrongPassword | ClientErrSecureStorage String | ClientErrDecryptionFailed String | ClientErrThrown SomeException | ClientErrOther String deriving (Show)
TimLuq/sqrl-auth-client-hs
src/Web/Authenticate/SQRL/Client/Types.hs
Haskell
mit
2,990
module TriggerSpec (spec) where import Helper import Trigger normalize :: String -> [String] normalize = normalizeErrors . normalizeTiming . normalizeSeed . lines . stripAnsiColors where normalizeTiming :: [String] -> [String] normalizeTiming = mkNormalize "Finished in " normalizeSeed :: [String] -> [String] normalizeSeed = mkNormalize "Randomized with seed " mkNormalize :: String -> [String] -> [String] mkNormalize message = map f where f line | message `isPrefixOf` line = message ++ "..." | otherwise = line normalizeErrors :: [String] -> [String] normalizeErrors xs = case xs of y : ys | "Spec.hs:" `isPrefixOf` y -> "Spec.hs:..." : normalizeErrors (removeErrorDetails ys) y : ys -> y : normalizeErrors ys [] -> [] removeErrorDetails :: [String] -> [String] removeErrorDetails xs = case xs of (_ : _ : ' ' : '|' : _) : ys -> removeErrorDetails ys _ -> xs stripAnsiColors xs = case xs of '\ESC' : '[' : ';' : ys | 'm' : zs <- dropWhile isNumber ys -> stripAnsiColors zs '\ESC' : '[' : ys | 'm' : zs <- dropWhile isNumber ys -> stripAnsiColors zs y : ys -> y : stripAnsiColors ys [] -> [] spec :: Spec spec = do describe "reloadedSuccessfully" $ do context "with GHC < 8.2.1" $ do it "detects success" $ do reloadedSuccessfully "Ok, modules loaded: Spec." `shouldBe` True context "with GHC >= 8.2.1" $ do context "with a single module" $ do it "detects success" $ do reloadedSuccessfully "Ok, 1 module loaded." `shouldBe` True context "with multiple modules" $ do it "detects success" $ do reloadedSuccessfully "Ok, 5 modules loaded." `shouldBe` True context "with GHC >= 8.2.2" $ do context "with a single module" $ do it "detects success" $ do reloadedSuccessfully "Ok, one module loaded." `shouldBe` True context "with multiple modules" $ do it "detects success" $ do reloadedSuccessfully "Ok, four modules loaded." `shouldBe` True describe "triggerAll" $ around_ withSomeSpec $ do it "runs all specs" $ do withSession ["Spec.hs", "--no-color"] $ \session -> do writeFile "Spec.hs" failingSpec (False, xs) <- silence (trigger session >> triggerAll session) normalize xs `shouldBe` [ modulesLoaded Ok ["Spec"] , "" , "foo" , "bar FAILED [1]" , "" , "Failures:" , "" , " Spec.hs:9:3: " , " 1) bar" , "" , " To rerun use: --match \"/bar/\"" , "" , "Randomized with seed ..." , "" , "Finished in ..." , "2 examples, 1 failure" , "Summary {summaryExamples = 2, summaryFailures = 1}" ] describe "trigger" $ around_ withSomeSpec $ do it "reloads and runs specs" $ do withSession ["Spec.hs", "--no-color"] $ \session -> do result <- silence (trigger session >> trigger session) fmap normalize result `shouldBe` (True, [ modulesLoaded Ok ["Spec"] , "" , "foo" , "bar" , "" , "Finished in ..." , "2 examples, 0 failures" , "Summary {summaryExamples = 2, summaryFailures = 0}" ]) context "with a module that does not compile" $ do it "stops after reloading" $ do withSession ["Spec.hs"] $ \session -> do writeFile "Spec.hs" (passingSpec ++ "foo = bar") (False, xs) <- silence (trigger session >> trigger session) normalize xs `shouldBe` [ "[1 of 1] Compiling Spec ( Spec.hs, interpreted )" , "" , "Spec.hs:..." , modulesLoaded Failed [] ] context "with a failing spec" $ do it "indicates failure" $ do withSession ["Spec.hs"] $ \session -> do writeFile "Spec.hs" failingSpec (False, xs) <- silence (trigger session) xs `shouldContain` modulesLoaded Ok ["Spec"] xs `shouldContain` "2 examples, 1 failure" it "only reruns failing specs" $ do withSession ["Spec.hs", "--no-color"] $ \session -> do writeFile "Spec.hs" failingSpec (False, xs) <- silence (trigger session >> trigger session) normalize xs `shouldBe` [ modulesLoaded Ok ["Spec"] , "" , "bar FAILED [1]" , "" , "Failures:" , "" , " Spec.hs:9:3: " , " 1) bar" , "" , " To rerun use: --match \"/bar/\"" , "" , "Randomized with seed ..." , "" , "Finished in ..." , "1 example, 1 failure" , "Summary {summaryExamples = 1, summaryFailures = 1}" ] context "after a failing spec passes" $ do it "runs all specs" $ do withSession ["Spec.hs", "--no-color"] $ \session -> do writeFile "Spec.hs" failingSpec _ <- silence (trigger session) writeFile "Spec.hs" passingSpec (True, xs) <- silence (trigger session) normalize xs `shouldBe` [ "[1 of 1] Compiling Spec ( Spec.hs, interpreted )" , modulesLoaded Ok ["Spec"] , "" , "bar" , "" , "Finished in ..." , "1 example, 0 failures" , "Summary {summaryExamples = 1, summaryFailures = 0}" , "" , "foo" , "bar" , "" , "Finished in ..." , "2 examples, 0 failures" , "Summary {summaryExamples = 2, summaryFailures = 0}" ] context "with a module that does not expose a spec" $ do it "only reloads" $ do withSession ["Spec.hs"] $ \session -> do writeFile "Spec.hs" "module Foo where" silence (trigger session >> trigger session) `shouldReturn` (True, modulesLoaded Ok ["Foo"] ++ "\n") context "with an hspec-meta spec" $ do it "reloads and runs spec" $ do withSession ["Spec.hs", "--no-color"] $ \session -> do writeFile "Spec.hs" passingMetaSpec result <- silence (trigger session >> trigger session) fmap normalize result `shouldBe` (True, [ modulesLoaded Ok ["Spec"] , "" , "foo" , "bar" , "" , "Finished in ..." , "2 examples, 0 failures" , "Summary {summaryExamples = 2, summaryFailures = 0}" ])
hspec/sensei
test/TriggerSpec.hs
Haskell
mit
6,731
module Bonlang.Runtime.Bool ( or' , and' , negate' ) where import Bonlang.Lang import qualified Bonlang.Lang.Bool as B import qualified Data.Map as M import Prelude hiding (negate) booleanOp :: PrimFunc -> BonlangValue booleanOp f = BonlangClosure { cParams = ["b0", "b1"] , cEnv = M.empty , cBody = BonlangPrimFunc f } or', and' :: BonlangValue or' = booleanOp B.or and' = booleanOp B.and negate' :: BonlangValue negate' = BonlangClosure { cParams = ["b0"] , cEnv = M.empty , cBody = BonlangPrimFunc B.negate }
charlydagos/bonlang
src/Bonlang/Runtime/Bool.hs
Haskell
mit
753
{-# LANGUAGE TemplateHaskell #-} module Language.SillyStack.Instructions where import Control.Lens import Control.Monad.State data Thing = TInt Integer | TInstruction Instruction deriving (Eq, Ord, Show) data Instruction = PUSH Thing | POP | ADD deriving (Eq, Ord, Show) data SillyState = SillyState { _stack :: [Thing] --, _programCounter :: Integer } deriving (Eq, Ord, Show) makeLenses ''SillyState emptyState :: SillyState emptyState = SillyState [] type SillyVMT a = StateT SillyState IO a push :: Thing -> SillyVMT () push t = do s <- use stack stack .= t : s pop :: SillyVMT Thing pop = do s <- use stack stack .= init s return . last $ s add :: SillyVMT () add = do TInt x1 <- pop TInt x2 <- pop s <- use stack stack .= (TInt (x1 + x2)) : s
relrod/sillystack
src/Language/SillyStack/Instructions.hs
Haskell
bsd-2-clause
858
cd ../books cd ../src runghc Converter.hs\ --title "Numeric Haskell: A Vector Tutorial" \ --language "en-us" \ --author "hackage" \ --toc "http://www.haskell.org/haskellwiki/Numeric_Haskell:_A_Vector_Tutorial" \ --folder "../books"
thlorenz/WebToInk
scripts/make-numerichaskellvectortutorial.hs
Haskell
bsd-2-clause
254
module Analysis.Types.SortsTests where import Test.QuickCheck import Control.Applicative import Analysis.Types.Sorts import Control.Applicative() maxComplexity = 5 allSorts = foldl mkSorts [Ann,Eff] [1..(maxComplexity + 1)] where mkSorts s _ = s ++ concatMap (\x -> map (Arr x) s) s instance Arbitrary Sort where arbitrary = (!!) allSorts <$> choose (0,maxComplexity) shrink x = case x of Eff -> [] Ann -> [] Arr a b -> merge a b where merge a b = [Eff,Ann,a,b] ++ [Arr x y | (x,y) <- shrink (a,b)]
netogallo/polyvariant
test/Analysis/Types/SortsTests.hs
Haskell
bsd-3-clause
548
import Data.Char (chr, ord) import Common.Utils (if') import Common.Numbers.Primes (testPrime) type Mask = [Int] substitute :: Mask -> Int -> Int substitute mask d = read (map (\x -> chr (x + ord '0')) (map (\x -> if' (x == -1) d x) mask)) goMask :: Int -> Int -> Int -> Mask -> Int goMask top dep free mask = if dep == 0 then if' (free == 3) (compute mask) maxBound else minimum $ map (\x -> goMask top (dep - 1) (free' x) (mask ++ [x])) can where free' x = free + (if' (x == -1) 1 0) can | top == dep = -1 : [1 .. 9] | dep == 1 = [1, 3, 7, 9] | otherwise = [-1 .. 9] compute :: Mask -> Int compute mask = if' (total == 8) (head primes) maxBound where can = if' (head mask == -1) [1 .. 9] [0 .. 9] converted = map (substitute mask) can primes = filter testPrime converted total = length primes main = print $ goMask 6 6 0 [] -- consider all valid masks, we can get some key observations: -- 0. the answer is 6-digit long; -- 1. the last digit must be 1,3,7,9; -- 2. there should be exactly 3 free digits, otherwise, there will be at least 3 generated numbers divisable by 3.
foreverbell/project-euler-solutions
src/51.hs
Haskell
bsd-3-clause
1,159
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_HADDOCK show-extensions #-} {-| Module : $Header$ Copyright : (c) 2016 Deakin Software & Technology Innovation Lab License : BSD3 Maintainer : Rhys Adams <rhys.adams@deakin.edu.au> Stability : unstable Portability : portable Persistence for job states and yet-to-be-run 'ScheduleCommand's. -} module Eclogues.Persist ( -- * 'Action' Action, Context -- ** Running , withPersistDir, atomically -- * View , allIntents, allEntities, allContainers -- * Mutate , insert, updateStage, casStage, updateSatis, updateSpec, delete , scheduleIntent, deleteIntent , insertBox, sealBox, deleteBox , insertFile, deleteFilesAttachedTo , insertContainer, deleteContainer ) where import Eclogues.Prelude import Eclogues.Persist.Stage1 () import Eclogues.Scheduling.Command (ScheduleCommand) import qualified Eclogues.Job as Job import Control.Monad.Base (MonadBase, liftBase) import Control.Monad.Logger (LoggingT, runStderrLoggingT) import Control.Monad.Reader (ReaderT) import qualified Data.HashMap.Strict as HM import Database.Persist.TH (mkPersist, sqlSettings, mkMigrate, share, persistLowerCase) import Database.Persist ((==.), (=.)) import qualified Database.Persist as P import qualified Database.Persist.Sql as PSql import Database.Persist.Sqlite (withSqlitePool) import Path (toFilePath) -- Table definitions. share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Job name Job.Name spec Job.Spec stage Job.Stage satis Job.Satisfiability uuid UUID UniqueName name Box name Job.Name stage Job.Sealed UniqueBoxName name File name Job.FileId uuid UUID entityName Job.Name UniqueEntityFile name entityName UniqueFileUUID uuid ScheduleIntent command ScheduleCommand UniqueCommand command Container name Job.ContainerId uuid UUID UniqueContainerName name UniqueContainerUUID uuid |] -- Hide away the implementation details. -- | All 'Action's run in a Context. newtype Context = Context PSql.ConnectionPool -- | An interaction with the persistence backend. newtype Action r = Action (ReaderT PSql.SqlBackend IO r) deriving (Functor, Applicative, Monad) instance Show (Action ()) where show _ = "Action" -- | You can join up Actions by running them sequentially. instance Semigroup (Action ()) where (<>) = (*>) instance Monoid (Action ()) where mempty = pure () mappend = (<>) -- | Run some action that might persist things inside the given directory. -- Logs to stderr. withPersistDir :: Path Abs Dir -> (Context -> LoggingT IO a) -> IO a withPersistDir path f = runStderrLoggingT $ withSqlitePool ("WAL=off " <> path' <> "/eclogues.db3") 1 act where act pool = do PSql.runSqlPool (PSql.runMigration migrateAll) pool f (Context pool) path' = fromString $ toFilePath path -- | Apply some Action in a transaction. atomically :: (MonadBase IO m) => Context -> Action r -> m r atomically (Context pool) (Action a) = liftBase $ PSql.runSqlPool a pool -- | Does not insert files. insert :: Job.Status -> Action () insert status = Action $ P.insert_ job where job = Job { jobName = status ^. Job.name , jobSpec = status ^. Job.spec , jobStage = status ^. Job.stage , jobSatis = status ^. Job.satis , jobUuid = status ^. Job.uuid } insertBox :: Job.BoxStatus -> Action () insertBox status = Action . P.insert_ $ Box (status ^. Job.name) (status ^. Job.sealed) insertContainer :: Job.ContainerId -> UUID -> Action () insertContainer n = Action . P.insert_ . Container n insertFile :: Job.Name -> Job.FileId -> UUID -> Action () insertFile jn fn u = Action . P.insert_ $ File fn u jn updateStage :: Job.Name -> Job.Stage -> Action () updateStage name st = Action $ P.updateWhere [JobName ==. name] [JobStage =. st] casStage :: Job.Name -> Job.Stage -> Job.Stage -> Action () casStage name st st' = Action $ P.updateWhere [JobName ==. name, JobStage ==. st] [JobStage =. st'] updateSatis :: Job.Name -> Job.Satisfiability -> Action () updateSatis name st = Action $ P.updateWhere [JobName ==. name] [JobSatis =. st] updateSpec :: Job.Name -> Job.Spec -> Action () updateSpec name st = Action $ P.updateWhere [JobName ==. name] [JobSpec =. st] sealBox :: Job.Name -> Action () sealBox name = Action $ P.updateWhere [BoxName ==. name] [BoxStage =. Job.Sealed] delete :: Job.Name -> Action () delete = Action . P.deleteBy . UniqueName deleteBox :: Job.Name -> Action () deleteBox = Action . P.deleteBy . UniqueBoxName deleteContainer :: Job.ContainerId -> Action () deleteContainer = Action . P.deleteBy . UniqueContainerName deleteFilesAttachedTo :: Job.Name -> Action () deleteFilesAttachedTo name = Action $ P.deleteWhere [FileEntityName ==. name] scheduleIntent :: ScheduleCommand -> Action () scheduleIntent = Action . P.insert_ . ScheduleIntent deleteIntent :: ScheduleCommand -> Action () deleteIntent = Action . P.deleteBy . UniqueCommand getAll :: (PSql.SqlBackend ~ PSql.PersistEntityBackend a, PSql.PersistEntity a) => (a -> b) -> Action [b] getAll f = Action $ fmap (f . P.entityVal) <$> P.selectList [] [] allIntents :: Action [ScheduleCommand] allIntents = getAll scheduleIntentCommand allEntities :: Action [Job.AnyStatus] allEntities = do fs <- HM.fromListWith (++) <$> getAll toPair js <- getAll toMkStatus bs <- getAll toMkBoxStatus pure $ toStatus fs <$> js ++ bs where toMkStatus (Job n spec st satis uuid) = (n, Job.AJob . Job.mkStatus spec st satis uuid) toMkBoxStatus (Box n sealed) = (n, Job.ABox . Job.mkBoxStatus n sealed) toPair (File n u jn) = (jn, [(n, u)]) toStatus m (n, mk) = mk . maybe mempty HM.fromList $ HM.lookup n m allContainers :: Action [(Job.ContainerId, UUID)] allContainers = getAll (\(Container n u) -> (n, u))
rimmington/eclogues
eclogues-impl/app/api/Eclogues/Persist.hs
Haskell
bsd-3-clause
6,281
{-# LANGUAGE PostfixOperators #-} {-# OPTIONS_HADDOCK prune #-} ---------------------------------------------------------------------------- -- | -- Module : ForSyDe.Atom.ExB -- Copyright : (c) George Ungureanu, 2015-2017 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : ugeorge@kth.se -- Stability : experimental -- Portability : portable -- -- This module exports the core entities of the extended behavior -- layer: interfaces for atoms and common patterns of atoms. It does -- /NOT/ export any implementation or instantiation of any specific -- behavior extension type. For an overview about atoms, layers and -- patterns, please refer to the "ForSyDe.Atom" module documentation. -- -- __IMPORTANT!!!__ -- see the <ForSyDe-Atom.html#naming_conv naming convention> rules -- on how to interpret, use and develop your own constructors. ---------------------------------------------------------------------------- module ForSyDe.Atom.ExB ( -- * Atoms ExB (..), -- * Patterns res11, res12, res13, res14, res21, res22, res23, res24, res31, res32, res33, res34, res41, res42, res43, res44, res51, res52, res53, res54, res61, res62, res63, res64, res71, res72, res73, res74, res81, res82, res83, res84, filter, filter', degen, ignore11, ignore12, ignore13, ignore14, ignore21, ignore22, ignore23, ignore24, ignore31, ignore32, ignore33, ignore34, ignore41, ignore42, ignore43, ignore44 ) where import Prelude hiding (filter) import ForSyDe.Atom.Utility.Tuple infixl 4 /.\, /*\, /&\, /!\ -- | Class which defines the atoms for the extended behavior layer. -- -- As its name suggests, this layer is extending the behavior of the -- wrapped entity/function by expanding its domains set with symbols -- having clearly defined semantics (e.g. special events with known -- responses). -- -- The types associated with this layer can simply be describes as: -- -- <<fig/eqs-exb-types.png>> -- -- where \(\alpha\) is a base type and \(b\) is the type extension, -- i.e. a set of symbols with clearly defined semantics. -- -- Extended behavior atoms are functions of these types, defined as -- interfaces in the 'ExB' type class. class Functor b => ExB b where -- | Extends a value (from a layer below) with a set of symbols with -- known semantics, as described by a type instantiating this class. extend :: a -> b a -- | Basic functor operator. Lifts a function (from a layer below) -- into the domain of the extended behavior layer. -- -- <<fig/eqs-exb-atom-func.png>> (/.\) :: (a -> a') -> b a -> b a' -- | Applicative operator. Defines a resolution between two extended -- behavior symbols. -- -- <<fig/eqs-exb-atom-app.png>> (/*\) :: b (a -> a') -> b a -> b a' -- | Predicate operator. Generates a defined behavior based on an -- extended Boolean predicate. -- -- <<fig/eqs-exb-atom-phi.png>> (/&\) :: b Bool -> b a -> b a -- | Degenerate operator. Degenerates a behavior-extended value into -- a non-extended one (from a layer below), based on a kernel -- value. Used also to throw exceptions. -- -- <<fig/eqs-exb-atom-deg.png>> (/!\) :: a -> b a -> a -- | -- <<fig/eqs-exb-pattern-resolution.png>> -- -- The @res@ behavior pattern lifts a function on values to the -- extended behavior domain, and applies a resolution between two -- extended behavior symbols. -- -- Constructors: @res[1-8][1-4]@. res22 :: ExB b => (a1 -> a2 -> (a1', a2')) -- ^ function on values -> b a1 -- ^ first input -> b a2 -- ^ second input -> (b a1', b a2') -- ^ tupled output res11 f b1 = (f /.\ b1) res21 f b1 b2 = (f /.\ b1 /*\ b2) res31 f b1 b2 b3 = (f /.\ b1 /*\ b2 /*\ b3) res41 f b1 b2 b3 b4 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4) res51 f b1 b2 b3 b4 b5 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5) res61 f b1 b2 b3 b4 b5 b6 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6) res71 f b1 b2 b3 b4 b5 b6 b7 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 /*\ b7) res81 f b1 b2 b3 b4 b5 b6 b7 b8 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 /*\ b7 /*\ b8) res12 f b1 = (f /.\ b1 |<) res22 f b1 b2 = (f /.\ b1 /*\ b2 |<) res32 f b1 b2 b3 = (f /.\ b1 /*\ b2 /*\ b3 |<) res42 f b1 b2 b3 b4 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 |<) res52 f b1 b2 b3 b4 b5 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 |<) res62 f b1 b2 b3 b4 b5 b6 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 |<) res72 f b1 b2 b3 b4 b5 b6 b7 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 /*\ b7 |<) res82 f b1 b2 b3 b4 b5 b6 b7 b8 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 /*\ b5 /*\ b8 |<) res13 f b1 = (f /.\ b1 |<<) res23 f b1 b2 = (f /.\ b1 /*\ b2 |<<) res33 f b1 b2 b3 = (f /.\ b1 /*\ b2 /*\ b3 |<<) res43 f b1 b2 b3 b4 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 |<<) res53 f b1 b2 b3 b4 b5 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 |<<) res63 f b1 b2 b3 b4 b5 b6 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 |<<) res73 f b1 b2 b3 b4 b5 b6 b7 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 /*\ b7 |<<) res83 f b1 b2 b3 b4 b5 b6 b7 b8 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 /*\ b5 /*\ b8 |<<) res14 f b1 = (f /.\ b1 |<<<) res24 f b1 b2 = (f /.\ b1 /*\ b2 |<<<) res34 f b1 b2 b3 = (f /.\ b1 /*\ b2 /*\ b3 |<<<) res44 f b1 b2 b3 b4 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 |<<<) res54 f b1 b2 b3 b4 b5 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 |<<<) res64 f b1 b2 b3 b4 b5 b6 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 |<<<) res74 f b1 b2 b3 b4 b5 b6 b7 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 /*\ b7 |<<<) res84 f b1 b2 b3 b4 b5 b6 b7 b8 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 /*\ b7 /*\ b8 |<<<) -- | Prefix name for the prefix operator '/&\'. filter p = (/&\) p -- | Same as 'filter' but takes base (non-extended) values as -- input arguments. filter' p a = (/&\) (extend p) (extend a) -- | Prefix name for the degenerate operator '/!\'. degen a = (/!\) a -- | -- <<fig/eqs-exb-pattern-ignore.png>> -- -- The @ignoreXY@ pattern takes a function of @Y + X@ arguments, @Y@ -- basic inputs followed by @X@ behavior-extended inputs. The function -- is first lifted and applied on the @X@ behavior-extended arguments, -- and the result is then degenerated using the @Y@ non-extended -- arguments as fallback. The effect is similar to "ignoring" a the -- result of a function evaluation if \(\in b\). -- -- The main application of this pattern is as extended behavior -- wrapper for stateful processes which do not "understand" extended -- behavior semantics, i.e. it simply propagates the current state -- \((\in \alpha)\) if the inputs belongs to the set of extended -- values \((\in b)\). -- -- Constructors: @ignore[1-4][1-4]@. ignore22 :: ExB b => (a1 -> a2 -> a1' -> a2' -> (a1, a2)) -- ^ function of @Y + X@ arguments -> a1 -> a2 -> b a1' -> b a2' -> (a1, a2) ignore11 f a1 b1 = degen a1 $ res11 (f a1) b1 ignore21 f a1 b1 b2 = degen a1 $ res21 (f a1) b1 b2 ignore31 f a1 b1 b2 b3 = degen a1 $ res31 (f a1) b1 b2 b3 ignore41 f a1 b1 b2 b3 b4 = degen a1 $ res41 (f a1) b1 b2 b3 b4 ignore12 f a1 a2 b1 = degen (a1, a2) $ res11 (f a1 a2) b1 ignore22 f a1 a2 b1 b2 = degen (a1, a2) $ res21 (f a1 a2) b1 b2 ignore32 f a1 a2 b1 b2 b3 = degen (a1, a2) $ res31 (f a1 a2) b1 b2 b3 ignore42 f a1 a2 b1 b2 b3 b4 = degen (a1, a2) $ res41 (f a1 a2) b1 b2 b3 b4 ignore13 f a1 a2 a3 b1 = degen (a1, a2, a3) $ res11 (f a1 a2 a3) b1 ignore23 f a1 a2 a3 b1 b2 = degen (a1, a2, a3) $ res21 (f a1 a2 a3) b1 b2 ignore33 f a1 a2 a3 b1 b2 b3 = degen (a1, a2, a3) $ res31 (f a1 a2 a3) b1 b2 b3 ignore43 f a1 a2 a3 b1 b2 b3 b4 = degen (a1, a2, a3) $ res41 (f a1 a2 a3) b1 b2 b3 b4 ignore14 f a1 a2 a3 a4 b1 = degen (a1, a2, a3, a4) $ res11 (f a1 a2 a3 a4) b1 ignore24 f a1 a2 a3 a4 b1 b2 = degen (a1, a2, a3, a4) $ res21 (f a1 a2 a3 a4) b1 b2 ignore34 f a1 a2 a3 a4 b1 b2 b3 = degen (a1, a2, a3, a4) $ res31 (f a1 a2 a3 a4) b1 b2 b3 ignore44 f a1 a2 a3 a4 b1 b2 b3 b4 = degen (a1, a2, a3, a4) $ res41 (f a1 a2 a3 a4) b1 b2 b3 b4
forsyde/forsyde-atom
src/ForSyDe/Atom/ExB.hs
Haskell
bsd-3-clause
8,397
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} module Language.Granule.Syntax.FirstParameter where import GHC.Generics class FirstParameter a e | a -> e where getFirstParameter :: a -> e setFirstParameter :: e -> a -> a default getFirstParameter :: (Generic a, GFirstParameter (Rep a) e) => a -> e getFirstParameter a = getFirstParameter' . from $ a default setFirstParameter :: (Generic a, GFirstParameter (Rep a) e) => e -> a -> a setFirstParameter e a = to . setFirstParameter' e . from $ a class GFirstParameter f e where getFirstParameter' :: f a -> e setFirstParameter' :: e -> f a -> f a instance {-# OVERLAPPING #-} GFirstParameter (K1 i e) e where getFirstParameter' (K1 a) = a setFirstParameter' e (K1 _) = K1 e instance {-# OVERLAPPABLE #-} GFirstParameter (K1 i a) e where getFirstParameter' _ = undefined setFirstParameter' _ _ = undefined instance GFirstParameter a e => GFirstParameter (M1 i c a) e where getFirstParameter' (M1 a) = getFirstParameter' a setFirstParameter' e (M1 a) = M1 $ setFirstParameter' e a instance (GFirstParameter a e, GFirstParameter b e) => GFirstParameter (a :+: b) e where getFirstParameter' (L1 a) = getFirstParameter' a getFirstParameter' (R1 a) = getFirstParameter' a setFirstParameter' e (L1 a) = L1 $ setFirstParameter' e a setFirstParameter' e (R1 a) = R1 $ setFirstParameter' e a instance GFirstParameter a e => GFirstParameter (a :*: b) e where getFirstParameter' (a :*: _) = getFirstParameter' a setFirstParameter' e (a :*: b) = (setFirstParameter' e a :*: b) instance (GFirstParameter U1 String) where getFirstParameter' _ = "" setFirstParameter' _ e = e
dorchard/gram_lang
frontend/src/Language/Granule/Syntax/FirstParameter.hs
Haskell
bsd-3-clause
1,825
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DoAndIfThenElse #-} {-# LANGUAGE ScopedTypeVariables #-} import Common import Database.PostgreSQL.Simple.Copy import Database.PostgreSQL.Simple.FromField (FromField) import Database.PostgreSQL.Simple.HStore import Database.PostgreSQL.Simple.Internal (breakOnSingleQuestionMark) import Database.PostgreSQL.Simple.Types(Query(..),Values(..), PGArray(..)) import qualified Database.PostgreSQL.Simple.Transaction as ST import Control.Applicative import Control.Exception as E import Control.Monad import Data.Char import Data.List (concat, sort) import Data.IORef import Data.Monoid ((<>)) import Data.String (fromString) import Data.Typeable import GHC.Generics (Generic) import Data.Aeson import Data.ByteString (ByteString) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy.Char8 as BL import Data.CaseInsensitive (CI) import qualified Data.CaseInsensitive as CI import Data.Map (Map) import qualified Data.Map as Map import Data.Text(Text) import qualified Data.Text.Encoding as T import qualified Data.Vector as V import System.FilePath import System.Timeout(timeout) import Data.Time(getCurrentTime, diffUTCTime) import Test.Tasty import Test.Tasty.Golden import Notify import Serializable import Time tests :: TestEnv -> TestTree tests env = testGroup "tests" $ map ($ env) [ testBytea , testCase "ExecuteMany" . testExecuteMany , testCase "Fold" . testFold , testCase "Notify" . testNotify , testCase "Serializable" . testSerializable , testCase "Time" . testTime , testCase "Array" . testArray , testCase "Array of nullables" . testNullableArray , testCase "HStore" . testHStore , testCase "citext" . testCIText , testCase "JSON" . testJSON , testCase "Question mark escape" . testQM , testCase "Savepoint" . testSavepoint , testCase "Unicode" . testUnicode , testCase "Values" . testValues , testCase "Copy" . testCopy , testCopyFailures , testCase "Double" . testDouble , testCase "1-ary generic" . testGeneric1 , testCase "2-ary generic" . testGeneric2 , testCase "3-ary generic" . testGeneric3 , testCase "Timeout" . testTimeout ] testBytea :: TestEnv -> TestTree testBytea TestEnv{..} = testGroup "Bytea" [ testStr "empty" [] , testStr "\"hello\"" $ map (fromIntegral . fromEnum) ("hello" :: String) , testStr "ascending" [0..255] , testStr "descending" [255,254..0] , testStr "ascending, doubled up" $ doubleUp [0..255] , testStr "descending, doubled up" $ doubleUp [255,254..0] ] where testStr label bytes = testCase label $ do let bs = B.pack bytes [Only h] <- query conn "SELECT md5(?::bytea)" [Binary bs] assertBool "Haskell -> SQL conversion altered the string" $ md5 bs == h [Only (Binary r)] <- query conn "SELECT ?::bytea" [Binary bs] assertBool "SQL -> Haskell conversion altered the string" $ bs == r doubleUp = concatMap (\x -> [x, x]) testExecuteMany :: TestEnv -> Assertion testExecuteMany TestEnv{..} = do execute_ conn "CREATE TEMPORARY TABLE tmp_executeMany (i INT, t TEXT, b BYTEA)" let rows :: [(Int, String, Binary ByteString)] rows = [ (1, "hello", Binary "bye") , (2, "world", Binary "\0\r\t\n") , (3, "?", Binary "") ] count <- executeMany conn "INSERT INTO tmp_executeMany VALUES (?, ?, ?)" rows count @?= fromIntegral (length rows) rows' <- query_ conn "SELECT * FROM tmp_executeMany" rows' @?= rows return () testFold :: TestEnv -> Assertion testFold TestEnv{..} = do xs <- fold_ conn "SELECT generate_series(1,10000)" [] $ \xs (Only x) -> return (x:xs) reverse xs @?= ([1..10000] :: [Int]) ref <- newIORef [] forEach conn "SELECT * FROM generate_series(1,?) a, generate_series(1,?) b" (100 :: Int, 50 :: Int) $ \(a :: Int, b :: Int) -> do xs <- readIORef ref writeIORef ref $! (a,b):xs xs <- readIORef ref reverse xs @?= [(a,b) | a <- [1..100], b <- [1..50]] -- Make sure fold propagates our exception. ref <- newIORef [] True <- expectError (== TestException) $ forEach_ conn "SELECT generate_series(1,10)" $ \(Only a) -> if a == 5 then do -- Cause a SQL error to trip up CLOSE. True <- expectError isSyntaxError $ execute_ conn "asdf" True <- expectError ST.isFailedTransactionError $ (query_ conn "SELECT 1" :: IO [(Only Int)]) throwIO TestException else do xs <- readIORef ref writeIORef ref $! (a :: Int) : xs xs <- readIORef ref reverse xs @?= [1..4] withTransaction conn $ replicateM_ 2 $ do xs <- fold_ conn "VALUES (1), (2), (3), (4), (5)" [] $ \xs (Only x) -> return (x:xs) reverse xs @?= ([1..5] :: [Int]) ref <- newIORef [] forEach_ conn "SELECT generate_series(1,101)" $ \(Only a) -> forEach_ conn "SELECT generate_series(1,55)" $ \(Only b) -> do xs <- readIORef ref writeIORef ref $! (a :: Int, b :: Int) : xs xs <- readIORef ref reverse xs @?= [(a,b) | a <- [1..101], b <- [1..55]] xs <- fold_ conn "SELECT 1 WHERE FALSE" [] $ \xs (Only x) -> return (x:xs) xs @?= ([] :: [Int]) -- TODO: add more complete tests, e.g.: -- -- * Fold in a transaction -- -- * Fold in a transaction after a previous fold has been performed -- -- * Nested fold return () queryFailure :: forall a. (FromField a, Typeable a, Show a) => Connection -> Query -> a -> Assertion queryFailure conn q resultType = do x :: Either SomeException [Only a] <- E.try $ query_ conn q case x of Left _ -> return () Right val -> assertFailure ("Did not fail as expected: " ++ show q ++ " :: " ++ show (typeOf resultType) ++ " -> " ++ show val) testArray :: TestEnv -> Assertion testArray TestEnv{..} = do xs <- query_ conn "SELECT '{1,2,3,4}'::_int4" xs @?= [Only (V.fromList [1,2,3,4 :: Int])] xs <- query_ conn "SELECT '{{1,2},{3,4}}'::_int4" xs @?= [Only (V.fromList [V.fromList [1,2], V.fromList [3,4 :: Int]])] queryFailure conn "SELECT '{1,2,3,4}'::_int4" (undefined :: V.Vector Bool) queryFailure conn "SELECT '{{1,2},{3,4}}'::_int4" (undefined :: V.Vector Int) testNullableArray :: TestEnv -> Assertion testNullableArray TestEnv{..} = do xs <- query_ conn "SELECT '{sometext, \"NULL\"}'::_text" xs @?= [Only (V.fromList ["sometext", "NULL" :: Text])] xs <- query_ conn "SELECT '{sometext, NULL}'::_text" xs @?= [Only (V.fromList [Just "sometext", Nothing :: Maybe Text])] queryFailure conn "SELECT '{sometext, NULL}'::_text" (undefined :: V.Vector Text) testHStore :: TestEnv -> Assertion testHStore TestEnv{..} = do execute_ conn "CREATE EXTENSION IF NOT EXISTS hstore" roundTrip [] roundTrip [("foo","bar"),("bar","baz"),("baz","hello")] roundTrip [("fo\"o","bar"),("b\\ar","baz"),("baz","\"value\\with\"escapes")] where roundTrip :: [(Text,Text)] -> Assertion roundTrip xs = do let m = Only (HStoreMap (Map.fromList xs)) m' <- query conn "SELECT ?::hstore" m [m] @?= m' testCIText :: TestEnv -> Assertion testCIText TestEnv{..} = do execute_ conn "CREATE EXTENSION IF NOT EXISTS citext" roundTrip (CI.mk "") roundTrip (CI.mk "UPPERCASE") roundTrip (CI.mk "lowercase") where roundTrip :: (CI Text) -> Assertion roundTrip cit = do let toPostgres = Only cit fromPostgres <- query conn "SELECT ?::citext" toPostgres [toPostgres] @?= fromPostgres testJSON :: TestEnv -> Assertion testJSON TestEnv{..} = do roundTrip (Map.fromList [] :: Map Text Text) roundTrip (Map.fromList [("foo","bar"),("bar","baz"),("baz","hello")] :: Map Text Text) roundTrip (Map.fromList [("fo\"o","bar"),("b\\ar","baz"),("baz","\"value\\with\"escapes")] :: Map Text Text) roundTrip (V.fromList [1,2,3,4,5::Int]) roundTrip ("foo" :: Text) roundTrip (42 :: Int) where roundTrip :: ToJSON a => a -> Assertion roundTrip a = do let js = Only (toJSON a) js' <- query conn "SELECT ?::json" js [js] @?= js' testQM :: TestEnv -> Assertion testQM TestEnv{..} = do -- Just test on a single string let testQuery' b = "testing for ?" <> b <> " and making sure " testQueryDoubleQM = testQuery' "?" testQueryRest = "? is substituted" testQuery = fromString $ testQueryDoubleQM <> testQueryRest -- expect the entire first part with double QMs replaced with literal '?' expected = (fromString $ testQuery' "", fromString testQueryRest) tried = breakOnSingleQuestionMark testQuery errMsg = concat [ "Failed to break on single question mark exclusively:\n" , "expected: ", show expected , "result: ", show tried ] assertBool errMsg $ tried == expected -- Let's also test the question mark operators in action -- ? -> Does the string exist as a top-level key within the JSON value? positiveQuery "SELECT ?::jsonb ?? ?" (testObj, "foo" :: Text) negativeQuery "SELECT ?::jsonb ?? ?" (testObj, "baz" :: Text) negativeQuery "SELECT ?::jsonb ?? ?" (toJSON numArray, "1" :: Text) -- ?| -> Do any of these array strings exist as top-level keys? positiveQuery "SELECT ?::jsonb ??| ?" (testObj, PGArray ["nope","bar","6" :: Text]) negativeQuery "SELECT ?::jsonb ??| ?" (testObj, PGArray ["nope","6" :: Text]) negativeQuery "SELECT ?::jsonb ??| ?" (toJSON numArray, PGArray ["1","2","6" :: Text]) -- ?& -> Do all of these array strings exist as top-level keys? positiveQuery "SELECT ?::jsonb ??& ?" (testObj, PGArray ["foo","bar","quux" :: Text]) positiveQuery "SELECT ?::jsonb ??& ?" (testObj, PGArray ["foo","bar" :: Text]) negativeQuery "SELECT ?::jsonb ??& ?" (testObj, PGArray ["foo","bar","baz" :: Text]) negativeQuery "SELECT ?::jsonb ??& ?" (toJSON numArray, PGArray ["1","2","3","4","5" :: Text]) -- Format error for 2 question marks, not 4 True <- expectError (isFormatError 2) $ (query conn "SELECT ?::jsonb ?? ?" $ Only testObj :: IO [Only Bool]) return () where positiveQuery :: ToRow a => Query -> a -> Assertion positiveQuery = boolQuery True negativeQuery :: ToRow a => Query -> a -> Assertion negativeQuery = boolQuery False numArray :: [Int] numArray = [1,2,3,4,5] boolQuery :: ToRow a => Bool -> Query -> a -> Assertion boolQuery b t x = do a <- query conn t x [Only b] @?= a testObj = toJSON (Map.fromList [("foo",toJSON (1 :: Int)) ,("bar",String "baz") ,("quux",toJSON [1 :: Int,2,3,4,5])] :: Map Text Value ) testSavepoint :: TestEnv -> Assertion testSavepoint TestEnv{..} = do True <- expectError ST.isNoActiveTransactionError $ withSavepoint conn $ return () let getRows :: IO [Int] getRows = map fromOnly <$> query_ conn "SELECT a FROM tmp_savepoint ORDER BY a" withTransaction conn $ do execute_ conn "CREATE TEMPORARY TABLE tmp_savepoint (a INT UNIQUE)" execute_ conn "INSERT INTO tmp_savepoint VALUES (1)" [1] <- getRows withSavepoint conn $ do execute_ conn "INSERT INTO tmp_savepoint VALUES (2)" [1,2] <- getRows return () [1,2] <- getRows withSavepoint conn $ do execute_ conn "INSERT INTO tmp_savepoint VALUES (3)" [1,2,3] <- getRows True <- expectError isUniqueViolation $ execute_ conn "INSERT INTO tmp_savepoint VALUES (2)" True <- expectError ST.isFailedTransactionError getRows -- Body returning successfully after handling error, -- but 'withSavepoint' will roll back without complaining. return () -- Rolling back clears the error condition. [1,2] <- getRows -- 'withSavepoint' will roll back after an exception, even if the -- exception wasn't SQL-related. True <- expectError (== TestException) $ withSavepoint conn $ do execute_ conn "INSERT INTO tmp_savepoint VALUES (3)" [1,2,3] <- getRows throwIO TestException [1,2] <- getRows -- Nested savepoint can be rolled back while the -- outer effects are retained. withSavepoint conn $ do execute_ conn "INSERT INTO tmp_savepoint VALUES (3)" True <- expectError isUniqueViolation $ withSavepoint conn $ do execute_ conn "INSERT INTO tmp_savepoint VALUES (4)" [1,2,3,4] <- getRows execute_ conn "INSERT INTO tmp_savepoint VALUES (4)" [1,2,3] <- getRows return () [1,2,3] <- getRows return () -- Transaction committed successfully, even though there were errors -- (but we rolled them back). [1,2,3] <- getRows return () testUnicode :: TestEnv -> Assertion testUnicode TestEnv{..} = do let q = Query . T.encodeUtf8 -- Handle encoding ourselves to ensure -- the table gets created correctly. let messages = map Only ["привет","мир"] :: [Only Text] execute_ conn (q "CREATE TEMPORARY TABLE ру́сский (сообщение TEXT)") executeMany conn "INSERT INTO ру́сский (сообщение) VALUES (?)" messages messages' <- query_ conn "SELECT сообщение FROM ру́сский" sort messages @?= sort messages' testValues :: TestEnv -> Assertion testValues TestEnv{..} = do execute_ conn "CREATE TEMPORARY TABLE values_test (x int, y text)" test (Values ["int4","text"] []) test (Values ["int4","text"] [(1,"hello")]) test (Values ["int4","text"] [(1,"hello"),(2,"world")]) test (Values ["int4","text"] [(1,"hello"),(2,"world"),(3,"goodbye")]) test (Values [] [(1,"hello")]) test (Values [] [(1,"hello"),(2,"world")]) test (Values [] [(1,"hello"),(2,"world"),(3,"goodbye")]) where test :: Values (Int, Text) -> Assertion test table@(Values _ vals) = do execute conn "INSERT INTO values_test ?" (Only table) vals' <- query_ conn "DELETE FROM values_test RETURNING *" sort vals @?= sort vals' testCopy :: TestEnv -> Assertion testCopy TestEnv{..} = do execute_ conn "CREATE TEMPORARY TABLE copy_test (x int, y text)" copy_ conn "COPY copy_test FROM STDIN (FORMAT CSV)" mapM_ (putCopyData conn) copyRows putCopyEnd conn copy_ conn "COPY copy_test FROM STDIN (FORMAT CSV)" mapM_ (putCopyData conn) abortRows putCopyError conn "aborted" -- Hmm, does postgres always produce \n as an end-of-line here, or -- are there cases where it will use a \r\n as well? copy_ conn "COPY copy_test TO STDOUT (FORMAT CSV)" rows <- loop [] sort rows @?= sort copyRows -- Now, let's just verify that the connection state is back to ready, -- so that we can issue more queries: [Only (x::Int)] <- query_ conn "SELECT 2 + 2" x @?= 4 where copyRows = ["1,foo\n" ,"2,bar\n"] abortRows = ["3,baz\n"] loop rows = do mrow <- getCopyData conn case mrow of CopyOutDone _ -> return rows CopyOutRow row -> loop (row:rows) testCopyFailures :: TestEnv -> TestTree testCopyFailures env = testGroup "Copy failures" $ map ($ env) [ testCopyUniqueConstraintError , testCopyMalformedError ] goldenTest :: TestName -> IO BL.ByteString -> TestTree goldenTest testName = goldenVsString testName (resultsDir </> fileName<.>"expected") where resultsDir = "test" </> "results" fileName = map normalize testName normalize c | not (isAlpha c) = '-' | otherwise = c -- | Test that we provide a sensible error message on failure testCopyUniqueConstraintError :: TestEnv -> TestTree testCopyUniqueConstraintError TestEnv{..} = goldenTest "unique constraint violation" $ handle (\(SomeException exc) -> return $ BL.pack $ show exc) $ do execute_ conn "CREATE TEMPORARY TABLE copy_unique_constraint_error_test (x int PRIMARY KEY, y text)" copy_ conn "COPY copy_unique_constraint_error_test FROM STDIN (FORMAT CSV)" mapM_ (putCopyData conn) copyRows _n <- putCopyEnd conn return BL.empty where copyRows = ["1,foo\n" ,"2,bar\n" ,"1,baz\n"] testCopyMalformedError :: TestEnv -> TestTree testCopyMalformedError TestEnv{..} = goldenTest "malformed input" $ handle (\(SomeException exc) -> return $ BL.pack $ show exc) $ do execute_ conn "CREATE TEMPORARY TABLE copy_malformed_input_error_test (x int PRIMARY KEY, y text)" copy_ conn "COPY copy_unique_constraint_error_test FROM STDIN (FORMAT CSV)" mapM_ (putCopyData conn) copyRows _n <- putCopyEnd conn return BL.empty where copyRows = ["1,foo\n" ,"2,bar\n" ,"z,baz\n"] testTimeout :: TestEnv -> Assertion testTimeout TestEnv{..} = withConn $ \c -> do start_t <- getCurrentTime res <- timeout 200000 $ do withTransaction c $ do query_ c "SELECT pg_sleep(1)" :: IO [Only ()] end_t <- getCurrentTime assertBool "Timeout did not occur" (res == Nothing) #if !defined(mingw32_HOST_OS) -- At the moment, you cannot timely abandon queries with async exceptions on -- Windows. let d = end_t `diffUTCTime` start_t assertBool "Timeout didn't work in a timely fashion" (0.1 < d && d < 0.6) #endif testDouble :: TestEnv -> Assertion testDouble TestEnv{..} = do [Only (x :: Double)] <- query_ conn "SELECT 'NaN'::float8" assertBool "expected NaN" (isNaN x) [Only (x :: Double)] <- query_ conn "SELECT 'Infinity'::float8" x @?= (1 / 0) [Only (x :: Double)] <- query_ conn "SELECT '-Infinity'::float8" x @?= (-1 / 0) testGeneric1 :: TestEnv -> Assertion testGeneric1 TestEnv{..} = do roundTrip conn (Gen1 123) where roundTrip conn x0 = do r <- query conn "SELECT ?::int" (x0 :: Gen1) r @?= [x0] testGeneric2 :: TestEnv -> Assertion testGeneric2 TestEnv{..} = do roundTrip conn (Gen2 123 "asdf") where roundTrip conn x0 = do r <- query conn "SELECT ?::int, ?::text" x0 r @?= [x0] testGeneric3 :: TestEnv -> Assertion testGeneric3 TestEnv{..} = do roundTrip conn (Gen3 123 "asdf" True) where roundTrip conn x0 = do r <- query conn "SELECT ?::int, ?::text, ?::bool" x0 r @?= [x0] data Gen1 = Gen1 Int deriving (Show,Eq,Generic) instance FromRow Gen1 instance ToRow Gen1 data Gen2 = Gen2 Int Text deriving (Show,Eq,Generic) instance FromRow Gen2 instance ToRow Gen2 data Gen3 = Gen3 Int Text Bool deriving (Show,Eq,Generic) instance FromRow Gen3 instance ToRow Gen3 data TestException = TestException deriving (Eq, Show, Typeable) instance Exception TestException expectError :: Exception e => (e -> Bool) -> IO a -> IO Bool expectError p io = (io >> return False) `E.catch` \ex -> if p ex then return True else throwIO ex isUniqueViolation :: SqlError -> Bool isUniqueViolation SqlError{..} = sqlState == "23505" isSyntaxError :: SqlError -> Bool isSyntaxError SqlError{..} = sqlState == "42601" isFormatError :: Int -> FormatError -> Bool isFormatError i FormatError{..} | null fmtMessage = False | otherwise = fmtMessage == concat [ show i , " single '?' characters, but " , show (length fmtParams) , " parameters" ] ------------------------------------------------------------------------ -- | Action for connecting to the database that will be used for testing. -- -- Note that some tests, such as Notify, use multiple connections, and assume -- that 'testConnect' connects to the same database every time it is called. testConnect :: IO Connection testConnect = connectPostgreSQL "" withTestEnv :: (TestEnv -> IO a) -> IO a withTestEnv cb = withConn $ \conn -> cb TestEnv { conn = conn , withConn = withConn } where withConn = bracket testConnect close main :: IO () main = withTestEnv $ defaultMain . tests
tomjaguarpaw/postgresql-simple
test/Main.hs
Haskell
bsd-3-clause
21,271
{-# LANGUAGE Rank2Types #-} {-| 'Snap.Extension.ConnectionPool' exports the 'MonadConnectionPool' interface which allows you to use HDBC connections in your application. These connections are pooled and only created once. The interface's only operation is 'withConnection'. 'Snap.Extension.ConnectionPool.ConnectionPool' contains the only implementation of this interface and can be used to turn your application's monad into a 'MonadConnectionPool'. -} module Snap.Extension.ConnectionPool ( MonadConnectionPool(..) , IsConnectionPoolState(..)) where import Control.Monad.Trans import Database.HDBC import Snap.Types ------------------------------------------------------------------------------ -- | The 'MonadConnectionPool' type class. Minimal complete definition: -- 'withConnection'. class MonadIO m => MonadConnectionPool m where -- | Given an action, wait for an available connection from the pool and -- execute the action. Return the result. withConnection :: (forall c. IConnection c => c -> IO a) -> m a ------------------------------------------------------------------------------ class IsConnectionPoolState a where withConnectionFromPool :: MonadIO m => (forall c. IConnection c => c -> IO b) -> a -> m b
duairc/snap-extensions
src/Snap/Extension/ConnectionPool.hs
Haskell
bsd-3-clause
1,280
module Data.Iteratee.List.IO ( defaultBufferSize , enumHandleSize , enumHandle , enumFileSize , enumFile ) where ------------------------------------------------------------------------ -- Imports ------------------------------------------------------------------------ import Data.Iteratee.Base import Data.Iteratee.Exception import Data.Iteratee.IO (defaultBufferSize, enumHandleWithSize) import Data.Monoid (Monoid (..)) import Control.Exception import Control.Monad import Control.Monad.CatchIO (MonadCatchIO (..)) import qualified Control.Monad.CatchIO as CIO import Control.Monad.IO.Class import Foreign.C import Foreign.Ptr import Foreign.Storable import Foreign.Marshal.Alloc import Foreign.Marshal.Array import System.IO ------------------------------------------------------------------------ -- IO Enumerators ------------------------------------------------------------------------ enumHandleSize :: (Storable a) => Int -> Handle -> Enumerator [a] IO b enumHandleSize = enumHandleWithSize peekArray {-# INLINE enumHandleSize #-} {-# RULES "enumHandleSize/String" enumHandleSize = enumHandleSizeString #-} enumHandleSizeString :: Int -> Handle -> Enumerator String IO a enumHandleSizeString = enumHandleWithSize (flip (curry peekCAStringLen)) {-# INLINE enumHandleSizeString #-} enumHandle :: (Storable a) => Handle -> Enumerator [a] IO b enumHandle = enumHandleSize defaultBufferSize {-# INLINE enumHandle #-} enumFileSize :: (Storable a) => Int -> FilePath -> Enumerator [a] IO b enumFileSize size file iter = bracket (openFile file ReadMode) (hClose) (\hand -> enumHandleSize size hand iter) {-# INLINE enumFileSize #-} enumFile :: (Storable a) => FilePath -> Enumerator [a] IO b enumFile = enumFileSize defaultBufferSize {-# INLINE enumFile #-}
tanimoto/iteratee
src/Data/Iteratee/List/IO.hs
Haskell
bsd-3-clause
1,781
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} {-# LANGUAGE TupleSections #-} module Ivory.ModelCheck.Ivory2CVC4 -- ( modelCheckMod ) where import Prelude () import Prelude.Compat hiding (exp) import Control.Monad (forM, forM_, void, when) import Data.List (nub) import qualified Data.Map as M import Data.Maybe import qualified Ivory.Language.Array as I import qualified Ivory.Language.Cast as I import qualified Ivory.Language.Syntax as I import Ivory.Opts.BitShift (bitShiftFold) import Ivory.Opts.ConstFold (constFold) import Ivory.Opts.DivZero (divZeroFold) import Ivory.Opts.Index (ixFold) import Ivory.Opts.Overflow (overflowFold) import Ivory.ModelCheck.CVC4 import Ivory.ModelCheck.Monad -- XXX testing -- import Debug.Trace -------------------------------------------------------------------------------- modelCheckProc :: [I.Module] -> I.Proc -> ModelCheck () modelCheckProc mods p = do forM_ mods $ \m -> do mapM_ toStruct (getVisible $ I.modStructs m) mapM_ addStruct (getVisible $ I.modStructs m) mapM_ addImport (I.modImports m) mapM_ (addProc Defined) (getVisible $ I.modProcs m) mapM_ toArea (getVisible $ I.modAreas m) modelCheckProc' . overflowFold . divZeroFold . bitShiftFold . ixFold . constFold $ p where getVisible ps = I.public ps ++ I.private ps addImport e = addProc Imported I.Proc { I.procSym = I.importSym e , I.procRetTy = err "addImport" "tried to use return type" , I.procArgs = I.importArgs e , I.procBody = [] , I.procRequires = I.importRequires e , I.procEnsures = I.importEnsures e } -------------------------------------------------------------------------------- toArea :: I.Area -> ModelCheck () toArea I.Area { I.areaSym = sym , I.areaType = ty , I.areaInit = init } = void $ addEnvVar ty sym -------------------------------------------------------------------------------- modelCheckProc' :: I.Proc -> ModelCheck () modelCheckProc' I.Proc { I.procSym = sym , I.procRetTy = ret , I.procArgs = args , I.procBody = body , I.procRequires = requires , I.procEnsures = ensures } = do mapM_ toParam args mapM_ toRequire requires mapM_ (toBody ensures) body -------------------------------------------------------------------------------- toParam :: I.Typed I.Var -> ModelCheck () toParam (I.Typed t val) = do v <- addEnvVar t (toVar val) assertBoundedVar t (var v) -------------------------------------------------------------------------------- toRequire :: I.Require -> ModelCheck () toRequire (I.Require cond) = do e <- toAssertion id cond addInvariant e -------------------------------------------------------------------------------- toEnsure :: I.Ensure -> ModelCheck Expr toEnsure (I.Ensure cond) = toAssertion id cond -------------------------------------------------------------------------------- toAssertion :: (I.Expr -> I.Expr) -> I.Cond -> ModelCheck Expr toAssertion trans cond = case cond of I.CondBool exp -> toExpr I.TyBool (trans exp) I.CondDeref t exp var c -> do e <- toExpr t exp toAssertion (subst [(var, exp)] . trans) c -------------------------------------------------------------------------------- -- | Symbolically execute statements, carrying the return requirements forward -- to each location that there is a return statement. toBody :: [I.Ensure] -> I.Stmt -> ModelCheck () toBody ens stmt = case stmt of I.IfTE exp blk0 blk1 -> toIfTE ens exp blk0 blk1 I.Assume exp -> addInvariant =<< toExpr I.TyBool exp I.Assert exp -> addQuery =<< toExpr I.TyBool exp I.CompilerAssert exp -> addQuery =<< toExpr I.TyBool exp I.Return (I.Typed t e) -> snapshotRefs >> toReturn ens t e I.ReturnVoid -> snapshotRefs >> return () I.Deref t v ref -> toDeref t v ref I.Store t ptr exp -> toStore t ptr exp I.RefCopy t ptr exp -> toStore t ptr exp -- XXX is this correct? I.Assign t v exp -> toAssign t v exp I.Call t retV nm args -> toCall t retV nm args I.Local t v inits -> toLocal t v inits I.AllocRef t ref name -> toAlloc t ref name I.Loop m v exp inc blk -> toLoop ens m v exp inc blk I.Comment (I.SourcePos src) -> setSrcLoc src I.Comment _ -> return () I.Break -> err "toBody" (show stmt) I.Forever _ -> err "toBody" (show stmt) -- TODO: Need to interpret the zero initializer here I.RefZero t ptr -> err "refZero" (show stmt) toReturn :: [I.Ensure] -> I.Type -> I.Expr -> ModelCheck () toReturn ens t exp = do e <- toExpr t exp v <- addEnvVar t "retval" addInvariant (var v .== e) queryEnsures ens t exp toDeref :: I.Type -> I.Var -> I.Expr -> ModelCheck () toDeref t v ref = do v' <- addEnvVar t (toVar v) e <- toExpr t ref assertBoundedVar t (var v') addInvariant (var v' .== e) toAlloc :: I.Type -> I.Var -> I.Name -> ModelCheck () toAlloc t ref name = do v' <- addEnvVar t (toVar ref) n' <- lookupVar (toName name) addInvariant (var v' .== var n') toStore :: I.Type -> I.Expr -> I.Expr -> ModelCheck () toStore t e@(I.ExpIndex{}) exp = toSelectStore t e exp toStore t e@(I.ExpLabel{}) exp = toSelectStore t e exp toStore t ptr exp = do v' <- updateEnvRef t ptr e <- toExpr t exp addInvariant (var v' .== e) toSelectStore :: I.Type -> I.Expr -> I.Expr -> ModelCheck () toSelectStore t f exp = do f' <- toExpr t f v <- toStoreRef t f e <- toExpr t exp addInvariant (var v .== store f' e) toLocal :: I.Type -> I.Var -> I.Init -> ModelCheck () toLocal t v inits = do v' <- addEnvVar t (toVar v) is <- toInit t inits addInvariant (var v' .== is) toInit :: I.Type -> I.Init -> ModelCheck Expr toInit ty init = case init of I.InitZero -> case ty of I.TyArr _ _ -> fmap var $ incReservedVar =<< toType ty I.TyStruct _-> fmap var $ incReservedVar =<< toType ty I.TyBool -> return false _ -> return $ intLit 0 I.InitExpr t exp -> toExpr t exp I.InitArray is _ -> do let (I.TyArr k t) = ty tv <- fmap var $ incReservedVar =<< toType ty forM_ (zip [0..] is) $ \ (ix,i) -> do e <- toInit t i addInvariant (index (intLit ix) tv .== e) return tv I.InitStruct fs -> do tv <- fmap var $ incReservedVar =<< toType ty let (I.TyStruct s) = ty forM_ fs $ \ (f, i) -> do structs <- getStructs case M.lookup s structs >>= lookupField f of Just t -> do e <- toInit t i addInvariant (field (var f) tv .== e) Nothing -> error $ "I don't know how to initialize field " ++ f ++ " of struct " ++ s return tv where lookupField f (I.Struct _ tfs) = listToMaybe [ t | I.Typed t f' <- tfs, f == f' ] lookupField f (I.Abstract _ _) = Nothing toAssign :: I.Type -> I.Var -> I.Expr -> ModelCheck () toAssign t v exp = do e <- toExpr t exp v' <- addEnvVar t (toVar v) addInvariant (var v' .== e) toCall :: I.Type -> Maybe I.Var -> I.Name -> [I.Typed I.Expr] -> ModelCheck () toCall t retV nm args = do (d, p) <- lookupProc $ toName nm case d of Imported -> toCallContract t retV p args Defined -> do inline <- askInline if inline then toCallInline t retV p args else toCallContract t retV p args toCallInline :: I.Type -> Maybe I.Var -> I.Proc -> [I.Typed I.Expr] -> ModelCheck () toCallInline t retV (I.Proc {..}) args = do argEnv <- forM (zip procArgs args) $ \ (formal, actual) -> do e <- toExpr (I.tType actual) (I.tValue actual) v <- addEnvVar (I.tType formal) (toVar $ I.tValue formal) addInvariant (var v .== e) return (toVar (I.tValue formal), e) withLocalReturnRefs $ do mapM_ (toBody []) procBody snapshotRefs -- incase of implicit retVoid rs <- getReturnRefs forM_ (M.toList rs) $ \ ((t, r), bvs) -> do -- XXX: can we rely on Refs always being passed as a Var? case lookup r argEnv of Just (Var x) -> do r' <- addEnvVar t x -- x may point to any number of values upon returning from a call addInvariant $ foldr1 (.&&) [b .=> (var r' .== var v) | (b,v) <- bvs] _ -> return () case retV of Nothing -> return () Just v -> do r <- addEnvVar t (toVar v) rv <- lookupVar (toVar I.retval) addInvariant (var r .== var rv) toCallContract :: I.Type -> Maybe I.Var -> I.Proc -> [I.Typed I.Expr] -> ModelCheck () toCallContract t retV pc args = do let su = [ (v, e) | (I.Typed _ v, I.Typed _ e) <- zip (I.procArgs pc) args] checkRequires su $ I.procRequires pc case retV of Nothing -> return () Just v -> do r <- addEnvVar t (toVar v) assumeEnsures ((I.retval, I.ExpVar $ I.VarName r) : su) (I.procEnsures pc) return () where checkRequires su reqs = forM_ reqs $ \ (I.Require c) -> addQuery =<< toAssertion (subst su) c assumeEnsures su ens = forM_ ens $ \ (I.Ensure c) -> addInvariant =<< toAssertion (subst su) c -- XXX Abstraction (to implement): If there is load/stores in the block, the we -- don't care how many times it iterates. It's pure. toLoop :: [I.Ensure] -> Integer -> I.Var -> I.Expr -> I.LoopIncr -> [I.Stmt] -> ModelCheck () toLoop ens maxIx v start end blk = mapM_ go ixs where go :: Integer -> ModelCheck () go ix = do v' <- addEnvVar t (toVar v) addInvariant (var v' .== intLit ix) mapM_ (toBody ens) blk t = I.ixRep loopData = loopIterations maxIx start end ixs | loopOp loopData == Incr = takeWhile (<= endVal loopData) $ iterate (+ 1) (startVal loopData) | otherwise -- loopOp loopData == Decr = takeWhile (>= endVal loopData) $ iterate (flip (-) 1) (startVal loopData) toIfTE :: [I.Ensure] -> I.Expr -> [I.Stmt] -> [I.Stmt] -> ModelCheck () toIfTE ens cond blk0 blk1 = do b <- toExpr I.TyBool cond trs <- runBranch b blk0 frs <- runBranch (not' b) blk1 forM_ (M.toList (M.unionWith (++) trs frs)) $ \ ((t, r), nub -> vs) -> do when (length vs == 2) $ do r' <- addEnvVar t r let [tv,fv] = vs addInvariant $ (b .=> (var r' .== var tv)) .&& (not' b .=> (var r' .== var fv)) where runBranch b blk = withLocalRefs $ inBranch b $ do mapM_ (toBody ens) blk -- Body under the invariant symRefs <$> getState -------------------------------------------------------------------------------- toExpr :: I.Type -> I.Expr -> ModelCheck Expr toExpr t exp = case exp of I.ExpSym s -> return (var s) I.ExpVar v -> var <$> lookupVar (toVar v) I.ExpLit lit -> case lit of I.LitInteger i -> return $ intLit i I.LitFloat r -> return $ realLit $ realToFrac r I.LitDouble r -> return $ realLit r I.LitBool b -> return $ if b then T else F I.LitChar _ -> fmap var $ incReservedVar =<< toType t I.LitNull -> fmap var $ incReservedVar =<< toType t I.LitString _ -> fmap var $ incReservedVar =<< toType t I.ExpLabel t' e f -> do e' <- toExpr t' e return $ field (var f) e' I.ExpIndex ta a ti i -> do a' <- toExpr ta a i' <- toExpr ti i return $ index i' a' I.ExpToIx e i -> toExpr t e I.ExpSafeCast t' e -> do e' <- toExpr t' e assertBoundedVar t e' return e' I.ExpOp op args -> toExprOp t op args I.ExpAddrOfGlobal s -> var <$> lookupVar s I.ExpMaxMin True -> return $ intLit $ fromJust $ I.toMaxSize t I.ExpMaxMin False -> return $ intLit $ fromJust $ I.toMinSize t I.ExpSizeOf _ty -> error "Ivory.ModelCheck.Ivory2CVC4.toExpr: FIXME: handle sizeof expressions" I.ExpExtern _ -> error "Ivory.ModelCheck.Ivory2CVC4.toExpr: can't handle external symbols" -------------------------------------------------------------------------------- toExprOp :: I.Type -> I.ExpOp -> [I.Expr] -> ModelCheck Expr toExprOp t op args = case op of I.ExpEq t' -> go t' (mkEq t') I.ExpNeq t' -> toExpr t (I.ExpOp I.ExpNot [I.ExpOp (I.ExpEq t') args]) I.ExpCond -> toExpCond t arg0 arg1 arg2 I.ExpLt orEq t' -> case orEq of True -> go t' (.<=) False -> go t' (.<) I.ExpGt orEq t' -> case orEq of True -> go t' (.>=) False -> go t' (.>) I.ExpNot -> not' <$> toExpr I.TyBool arg0 I.ExpAnd -> go t (.&&) I.ExpOr -> go t (.||) I.ExpMod -> toMod t arg0 arg1 I.ExpAdd -> go t (.+) I.ExpSub -> go t (.-) I.ExpMul -> toMul t arg0 arg1 I.ExpDiv -> toDiv t arg0 arg1 I.ExpNegate -> let neg = I.ExpOp I.ExpSub [litOp t 0, arg0] in toExpr t neg I.ExpAbs -> do v <- fmap var $ incReservedVar =<< toType t addInvariant (v .>= intLit 0) return v _ -> fmap var $ incReservedVar =<< toType t where arg0 = args !! 0 arg1 = args !! 1 arg2 = args !! 2 mkEq I.TyBool = (.<=>) mkEq _ = (.==) go t' op = do e0 <- toExpr t' arg0 e1 <- toExpr t' arg1 return (e0 `op` e1) toExpCond :: I.Type -> I.Expr -> I.Expr -> I.Expr -> ModelCheck Expr toExpCond t b x y = do v <- incReservedVar =<< toType t b' <- toExpr I.TyBool b x' <- toExpr t x y' <- toExpr t y let v' = var v addInvariant ((b' .=> (v' .== x')) .&& (not' b' .=> (v' .== y'))) return v' -- Abstraction: a % b (C semantics) implies -- -- ( ((a => 0) && (a % b => 0) && (a % b < b) && (a % b <= a)) -- || ((a < 0) && (a % b <= 0) && (a % b > b) && (a % b => a))) -- -- make a fresh variable v == a % b -- and assert the above for v then returning it. toMod :: I.Type -> I.Expr -> I.Expr -> ModelCheck Expr toMod t e0 e1 = do v <- incReservedVar =<< toType t let v' = var v a <- toExpr t e0 case e1 of I.ExpLit (I.LitInteger i) -> addInvariant (v' .== (a .% i)) _ -> do b <- toExpr t e1 addInvariant (v' .== call modAbs [a, b] .&& modExp v' a b) return v' toMul :: I.Type -> I.Expr -> I.Expr -> ModelCheck Expr toMul t e0 e1 = do v <- incReservedVar =<< toType t a <- toExpr t e0 b <- toExpr t e1 let v' = var v addInvariant (v' .== call mulAbs [a, b] .&& mulExp v' a b) return v' toDiv :: I.Type -> I.Expr -> I.Expr -> ModelCheck Expr toDiv t e0 e1 = do v <- incReservedVar =<< toType t a <- toExpr t e0 b <- toExpr t e1 let v' = var v addInvariant (v' .== call divAbs [a, b] .&& divExp v' a b) return v' -------------------------------------------------------------------------------- -- Helpers toName :: I.Name -> Var toName name = case name of I.NameSym s -> s I.NameVar v -> toVar v toVar :: I.Var -> Var toVar v = case v of I.VarName n -> n I.VarInternal n -> n I.VarLitName n -> n baseType :: I.Type -> Bool baseType t = case t of I.TyBool -> True (I.TyWord _) -> True (I.TyInt _) -> True I.TyFloat -> True I.TyDouble -> True _ -> False -- Abstraction: collapse references. toType :: I.Type -> ModelCheck Type toType t = case t of I.TyVoid -> return Void (I.TyWord _) -> return Integer (I.TyInt _) -> return Integer (I.TyIndex n) -> return Integer I.TyBool -> return Bool I.TyChar -> return Char I.TyFloat -> return Real I.TyDouble -> return Real I.TyProc _ _ -> return Opaque -- I.TyProc t' ts -> err "toType" "<< proc >>" I.TyRef t' -> toType t' I.TyConstRef t' -> toType t' I.TyPtr t' -> toType t' I.TyConstPtr t' -> toType t' I.TyArr i t' -> Array <$> toType t' I.TyCArray t' -> Array <$> toType t' I.TyOpaque -> return Opaque I.TyStruct name -> return $ Struct name updateEnvRef :: I.Type -> I.Expr -> ModelCheck Var updateEnvRef t ref = case ref of I.ExpVar v -> addEnvVar t (toVar v) I.ExpAddrOfGlobal v -> addEnvVar t v _ -> err "updateEnvRef" (show ref) toStoreRef :: I.Type -> I.Expr -> ModelCheck Var toStoreRef t ref = case ref of I.ExpIndex t' e _ _ -> toStoreRef t' e I.ExpLabel t' e _ -> toStoreRef t' e I.ExpVar v -> updateEnvRef t ref I.ExpAddrOfGlobal v -> updateEnvRef t ref _ -> err "toStoreRef" (show ref) data LoopOp = Incr | Decr deriving (Show, Read, Eq) data Loop = Loop { startVal :: Integer , endVal :: Integer , loopOp :: LoopOp } deriving (Show, Read, Eq) -- Compute the number of iterations in a loop. Assume the constant folder has -- run. loopIterations :: Integer -> I.Expr -> I.LoopIncr -> Loop loopIterations maxIx start end = case end of I.IncrTo e -> Loop { startVal = getLit 0 start , endVal = getLit maxIx e , loopOp = Incr } I.DecrTo e -> Loop { startVal = getLit maxIx start , endVal = getLit 0 e , loopOp = Decr } where getLit d e = case e of I.ExpLit l -> case l of I.LitInteger i -> i _ -> err "loopIterations.ExpLit" (show e) _ -> d -------------------------------------------------------------------------------- -- Language construction helpers binOp :: I.ExpOp -> I.Expr -> I.Expr -> I.Expr binOp op e0 e1 = I.ExpOp op [e0, e1] -- orOp, andOp :: I.Expr -> I.Expr -> I.Expr -- orOp = binOp I.ExpOr -- andOp = binOp I.ExpAnd -- leOp, leqOp, geOp, geqOp :: I.Type -> I.Expr -> I.Expr -> I.Expr -- leOp t = binOp (I.ExpLt False t) -- leqOp t = binOp (I.ExpLt True t) -- geOp t = binOp (I.ExpGt False t) -- geqOp t = binOp (I.ExpGt True t) -- negOp :: I.Expr -> I.Expr -- negOp e = I.ExpOp I.ExpNot [e] -- addOp :: I.Expr -> I.Expr -> I.Expr -- addOp e0 e1 = binOp I.ExpAdd e0 e1 -- subOp :: I.Expr -> I.Expr -> I.Expr -- subOp e0 e1 = binOp I.ExpSub e0 e1 -- incrOp :: I.Type -> I.Expr -> I.Expr -- incrOp t e = addOp e (litOp t 1) -- decrOp :: I.Type -> I.Expr -> I.Expr -- decrOp t e = subOp e (litOp t 1) litOp :: I.Type -> Integer -> I.Expr litOp t n = I.ExpLit e where e = case t of I.TyWord _ -> I.LitInteger n I.TyInt _ -> I.LitInteger n I.TyFloat -> I.LitFloat (fromIntegral n) I.TyDouble -> I.LitDouble (fromIntegral n) _ -> err "litOp" (show t) varOp :: Var -> I.Expr varOp = I.ExpVar . I.VarName -------------------------------------------------------------------------------- addEnvVar :: I.Type -> Var -> ModelCheck Var addEnvVar t v = do t' <- toType t v' <- declUpdateEnv t' v updateStRef t v v' return v' where isRef = case t of I.TyRef _ -> True _ -> False -- Call the appropriate cvc4lib functions. assertBoundedVar :: I.Type -> Expr -> ModelCheck () assertBoundedVar t e = getBounds t where getBounds t' = case t' of I.TyWord w -> case w of I.Word8 -> c word8 I.Word16 -> c word16 I.Word32 -> c word32 I.Word64 -> c word64 I.TyInt i -> case i of I.Int8 -> c int8 I.Int16 -> c int16 I.Int32 -> c int32 I.Int64 -> c int64 I.TyIndex n -> addInvariant $ (intLit 0 .<= e) .&& (e .<= (intLit n .- intLit 1)) _ -> return () c f = addInvariant (call f [e]) subst :: [(I.Var, I.Expr)] -> I.Expr -> I.Expr subst su = loop where loop e = case e of I.ExpSym{} -> e I.ExpVar v -> case lookup v su of Nothing -> e Just e' -> e' I.ExpLit{} -> e I.ExpOp op args -> I.ExpOp op (map loop args) I.ExpLabel t e0 s -> I.ExpLabel t (loop e0) s I.ExpIndex t e0 t1 e1 -> I.ExpIndex t (loop e0) t1 (loop e1) I.ExpSafeCast t e0 -> I.ExpSafeCast t (loop e0) I.ExpToIx e0 maxSz -> I.ExpToIx (loop e0) maxSz I.ExpAddrOfGlobal{} -> e I.ExpMaxMin{} -> e I.ExpSizeOf{} -> e I.ExpExtern{} -> e queryEnsures :: [I.Ensure] -> I.Type -> I.Expr -> ModelCheck () queryEnsures ens t retE = forM_ ens $ \e -> addQuery =<< toEnsure e toStruct :: I.Struct -> ModelCheck () toStruct (I.Abstract name _) = addType name [] toStruct (I.Struct name fields) = do fs <- forM fields $ \ (I.Typed t f) -> (f,) <$> toType t addType name fs err :: String -> String -> a err f msg = error $ "in ivory-model-check. Unexpected: " ++ msg ++ " in function " ++ f --------------------------------------------------------------------------------
GaloisInc/ivory
ivory-model-check/src/Ivory/ModelCheck/Ivory2CVC4.hs
Haskell
bsd-3-clause
21,486
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} -- FIXME module B.Shake.Core.Rule.Internal ( ShakeValue , Rule(..) , RuleKey(..) , RuleExecutor(..) ) where import Control.Applicative import Control.Monad (join, void) import Data.Maybe (maybeToList) import qualified Control.Exception as Ex import B.Question import B.Shake.Classes import B.Shake.Core.Action.Internal (Action(..)) import qualified B.Rule as B type ShakeValue a = (Show a, Typeable a, Eq a, Hashable a, Binary a, NFData a) class (ShakeValue key, ShakeValue value) => Rule key value where storedValue :: key -> IO (Maybe value) -- | What Shake calls 'Rule' we call 'Question'. 'RuleKey' -- wraps a Shake 'Rule's key so it can be an instance of -- 'Question'. newtype RuleKey key value = RuleKey key deriving (Show, Typeable, Eq, Hashable, Binary, NFData) data NoValue = NoValue deriving (Show, Typeable) instance Ex.Exception NoValue instance (Rule key value) => Question (RuleKey key value) where type Answer (RuleKey key value) = value type AnswerMonad (RuleKey key value) = IO answer (RuleKey key) = fmap join . Ex.try $ do mValue <- storedValue key return $ maybe (Left (Ex.toException NoValue)) Right mValue -- | Shake does not have a class or type corresponding to -- b's 'Rule'. Instead, it uses 'key -> Maybe (Action -- value)' inline. newtype RuleExecutor key value = RuleExecutor (key -> Maybe (Action value)) deriving (Typeable) instance (Rule key value) => B.Rule (RuleKey key value) (RuleExecutor key value) where queryRule (RuleKey key) (RuleExecutor f) = maybeToList $ (void . toBuildRule) <$> f key
strager/b-shake
B/Shake/Core/Rule/Internal.hs
Haskell
bsd-3-clause
1,833
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Ordinal.IT.Rules ( rules ) where import qualified Data.Text as Text import Prelude import Data.String import Duckling.Dimensions.Types import Duckling.Numeral.Helpers (parseInt) import Duckling.Ordinal.Helpers import Duckling.Regex.Types import Duckling.Types ruleOrdinalsPrimo :: Rule ruleOrdinalsPrimo = Rule { name = "ordinals (primo..10)" , pattern = [ regex "((prim|second|terz|quart|quint|sest|settim|ottav|non|decim)(o|a|i|e))" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of "primi" -> Just $ ordinal 1 "prima" -> Just $ ordinal 1 "primo" -> Just $ ordinal 1 "prime" -> Just $ ordinal 1 "seconda" -> Just $ ordinal 2 "secondi" -> Just $ ordinal 2 "seconde" -> Just $ ordinal 2 "secondo" -> Just $ ordinal 2 "terze" -> Just $ ordinal 3 "terzi" -> Just $ ordinal 3 "terzo" -> Just $ ordinal 3 "terza" -> Just $ ordinal 3 "quarte" -> Just $ ordinal 4 "quarto" -> Just $ ordinal 4 "quarta" -> Just $ ordinal 4 "quarti" -> Just $ ordinal 4 "quinto" -> Just $ ordinal 5 "quinta" -> Just $ ordinal 5 "quinti" -> Just $ ordinal 5 "quinte" -> Just $ ordinal 5 "sesti" -> Just $ ordinal 6 "seste" -> Just $ ordinal 6 "sesta" -> Just $ ordinal 6 "sesto" -> Just $ ordinal 6 "settimi" -> Just $ ordinal 7 "settima" -> Just $ ordinal 7 "settimo" -> Just $ ordinal 7 "settime" -> Just $ ordinal 7 "ottavo" -> Just $ ordinal 8 "ottava" -> Just $ ordinal 8 "ottavi" -> Just $ ordinal 8 "ottave" -> Just $ ordinal 8 "none" -> Just $ ordinal 9 "noni" -> Just $ ordinal 9 "nona" -> Just $ ordinal 9 "nono" -> Just $ ordinal 9 "decimo" -> Just $ ordinal 10 "decima" -> Just $ ordinal 10 "decime" -> Just $ ordinal 10 "decimi" -> Just $ ordinal 10 _ -> Nothing _ -> Nothing } ruleOrdinalDigits :: Rule ruleOrdinalDigits = Rule { name = "ordinal (digits)" , pattern = [ regex "0*(\\d+) ?(\x00aa|\x00b0|\x00b0)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> ordinal <$> parseInt match _ -> Nothing } rules :: [Rule] rules = [ ruleOrdinalDigits , ruleOrdinalsPrimo ]
rfranek/duckling
Duckling/Ordinal/IT/Rules.hs
Haskell
bsd-3-clause
2,827
module ProjectEuler.Problem011 (solution011) where import Util takeWhilePN :: Int -> (a -> Bool) -> [a] -> [a] takeWhilePN _ _ [] = [] takeWhilePN n p (x:xs) | p x = x : takeWhilePN n p xs | otherwise = take n (x:xs) triangles :: [Int] triangles = 1 : map pairSum (zip triangles [2..]) firstWithN n = first (zip triangles (takeWhilePN 1 (\xs -> length xs <= n) (map factors triangles))))
ThermalSpan/haskell-euler
src/ProjectEuler/Problem011.hs
Haskell
bsd-3-clause
421
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveDataTypeable #-} module Example.Engine where import Data.DEVS import Data.Binary import Data.Typeable (Typeable) import Data.Set (Set) import qualified Data.Set as Set import qualified Prelude as P import Numeric.Units.Dimensional.Prelude import Numeric.NumType (Zero, Pos3, Neg1) data Engine = Engine deriving (Typeable, Ord, Eq, Show) instance PDEVS Engine where type Y Engine = Int type X Engine = Int instance AtomicModel Engine instance ProcessorModel Simulator Engine pm_engine = procModel Engine ref_engine = selfRef Engine
alios/lambda-devs
Example/Example/Engine.hs
Haskell
bsd-3-clause
634
{-# LANGUAGE CPP #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE ForeignFunctionInterface #-} -- | -- Module : Data.Binary.Serialise.CBOR.ByteOrder -- Copyright : (c) Duncan Coutts 2015 -- License : BSD3-style (see LICENSE.txt) -- -- Maintainer : duncan@community.haskell.org -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Lorem ipsum... -- module Data.Binary.Serialise.CBOR.ByteOrder where #include "MachDeps.h" #if __GLASHOW_HASKELL >= 710 #define HAVE_BYTESWAP_PRIMOPS #endif #if i386_HOST_ARCH || x86_64_HOST_ARCH #define MEM_UNALIGNED_OPS #endif #if WORD_SIZE_IN_BITS == 64 #define ARCH_64bit #elif WORD_SIZE_IN_BITS == 32 #else #error expected WORD_SIZE_IN_BITS to be 32 or 64 #endif import GHC.Exts import GHC.Word import Foreign.C.Types import Foreign.Ptr import GHC.ForeignPtr #if !defined(HAVE_BYTESWAP_PRIMOPS) || !defined(MEM_UNALIGNED_OPS) import Data.Bits ((.|.), shiftL) #endif #if !defined(ARCH_64bit) import GHC.IntWord64 (wordToWord64#) #endif import Data.ByteString (ByteString) import qualified Data.ByteString.Internal as BS {-# INLINE grabWord8 #-} grabWord8 :: Ptr () -> Word grabWord8 (Ptr ip#) = W# (indexWord8OffAddr# ip# 0#) #if defined(HAVE_BYTESWAP_PRIMOPS) && \ defined(MEM_UNALIGNED_OPS) && \ !defined(WORDS_BIGENDIAN) {-# INLINE grabWord16 #-} grabWord16 :: Ptr () -> Word grabWord16 (Ptr ip#) = W# (byteSwap16# (indexWord16OffAddr# ip# 0#)) {-# INLINE grabWord32 #-} grabWord32 :: Ptr () -> Word grabWord32 (Ptr ip#) = W# (byteSwap32# (indexWord32OffAddr# ip# 0#)) {-# INLINE grabWord64 #-} grabWord64 :: Ptr () -> Word64 grabWord64 (Ptr ip#) = W64# (byteSwap64# (indexWord64OffAddr# ip# 0#)) #elif defined(MEM_UNALIGNED_OPS) && \ defined(WORDS_BIGENDIAN) {-# INLINE grabWord16 #-} grabWord16 :: Ptr () -> Word grabWord16 (Ptr ip#) = W# (indexWord16OffAddr# ip# 0#) {-# INLINE grabWord32 #-} grabWord32 :: Ptr () -> Word grabWord32 (Ptr ip#) = W# (indexWord32OffAddr# ip# 0#) {-# INLINE grabWord64 #-} grabWord64 :: Ptr () -> Word64 grabWord64 (Ptr ip#) = W64# (indexWord64OffAddr# ip# 0#) #else -- fallback version: {-# INLINE grabWord16 #-} grabWord16 :: Ptr () -> Word grabWord16 (Ptr ip#) = case indexWord8OffAddr# ip# 0# of w0# -> case indexWord8OffAddr# ip# 1# of w1# -> W# w0# `shiftL` 8 .|. W# w1# {-# INLINE grabWord32 #-} grabWord32 :: Ptr () -> Word grabWord32 (Ptr ip#) = case indexWord8OffAddr# ip# 0# of w0# -> case indexWord8OffAddr# ip# 1# of w1# -> case indexWord8OffAddr# ip# 2# of w2# -> case indexWord8OffAddr# ip# 3# of w3# -> W# w0# `shiftL` 24 .|. W# w1# `shiftL` 16 .|. W# w2# `shiftL` 8 .|. W# w3# {-# INLINE grabWord64 #-} grabWord64 :: Ptr () -> Word64 grabWord64 (Ptr ip#) = case indexWord8OffAddr# ip# 0# of w0# -> case indexWord8OffAddr# ip# 1# of w1# -> case indexWord8OffAddr# ip# 2# of w2# -> case indexWord8OffAddr# ip# 3# of w3# -> case indexWord8OffAddr# ip# 4# of w4# -> case indexWord8OffAddr# ip# 5# of w5# -> case indexWord8OffAddr# ip# 6# of w6# -> case indexWord8OffAddr# ip# 7# of w7# -> w w0# `shiftL` 56 .|. w w1# `shiftL` 48 .|. w w2# `shiftL` 40 .|. w w3# `shiftL` 32 .|. w w4# `shiftL` 24 .|. w w5# `shiftL` 16 .|. w w6# `shiftL` 8 .|. w w7# where #ifdef ARCH_64bit w w# = W64# w# #else w w# = W64# (wordToWord64# w#) #endif #endif {-# INLINE withBsPtr #-} withBsPtr :: (Ptr b -> a) -> ByteString -> a withBsPtr f (BS.PS (ForeignPtr addr# _fpc) off _len) = f (Ptr addr# `plusPtr` off) {-# INLINE unsafeHead #-} unsafeHead :: ByteString -> Word8 unsafeHead (BS.PS (ForeignPtr addr# _fpc) (I# off#) _len) = W8# (indexWord8OffAddr# addr# off#) -- -- Half floats -- {-# INLINE wordToFloat16 #-} wordToFloat16 :: Word -> Float wordToFloat16 = halfToFloat . fromIntegral {-# INLINE floatToWord16 #-} floatToWord16 :: Float -> Word16 floatToWord16 = fromIntegral . floatToHalf foreign import ccall unsafe "hs_binary_halfToFloat" halfToFloat :: CUShort -> Float foreign import ccall unsafe "hs_binary_floatToHalf" floatToHalf :: Float -> CUShort -- -- Casting words to floats -- -- We have to go via a word rather than reading directly from memory because of -- endian issues. A little endian machine cannot read a big-endian float direct -- from memory, so we read a word, bswap it and then convert to float. -- Currently there are no primops for casting word <-> float, see -- https://ghc.haskell.org/trac/ghc/ticket/4092 -- In this implementation, we're avoiding doing the extra indirection (and -- closure allocation) of the runSTRep stuff, but we have to be very careful -- here, we cannot allow the "constsant" newByteArray# 8# realWorld# to be -- floated out and shared and aliased across multiple concurrent calls. So we -- do manual worker/wrapper with the worker not being inlined. {-# INLINE wordToFloat32 #-} wordToFloat32 :: Word -> Float wordToFloat32 (W# w#) = F# (wordToFloat32# w#) {-# NOINLINE wordToFloat32# #-} wordToFloat32# :: Word# -> Float# wordToFloat32# w# = case newByteArray# 4# realWorld# of (# s', mba# #) -> case writeWord32Array# mba# 0# w# s' of s'' -> case readFloatArray# mba# 0# s'' of (# _, f# #) -> f# {-# INLINE wordToFloat64 #-} wordToFloat64 :: Word64 -> Double wordToFloat64 (W64# w#) = D# (wordToFloat64# w#) {-# NOINLINE wordToFloat64# #-} #ifdef ARCH_64bit wordToFloat64# :: Word# -> Double# #else wordToFloat64# :: Word64# -> Double# #endif wordToFloat64# w# = case newByteArray# 8# realWorld# of (# s', mba# #) -> case writeWord64Array# mba# 0# w# s' of s'' -> case readDoubleArray# mba# 0# s'' of (# _, f# #) -> f# -- Alternative impl that goes via the FFI {- {-# INLINE wordToFloat32 #-} wordToFloat32 :: Word -> Float wordToFloat32 = toFloat {-# INLINE wordToFloat64 #-} wordToFloat64 :: Word64 -> Double wordToFloat64 = toFloat {-# INLINE toFloat #-} toFloat :: (Storable word, Storable float) => word -> float toFloat w = unsafeDupablePerformIO $ alloca $ \buf -> do poke (castPtr buf) w peek buf -}
thoughtpolice/binary-serialise-cbor
Data/Binary/Serialise/CBOR/ByteOrder.hs
Haskell
bsd-3-clause
6,724
module PasswordGenerator (newPasswordBox) where import Graphics.UI.Gtk import Crypto.Threefish.Random import Data.IORef import System.IO.Unsafe import Graphics.Rendering.Pango.Font import Himitsu.PasswordUtils import PasswordDialogs (passwordBox) {-# NOINLINE prng #-} prng :: IORef SkeinGen prng = unsafePerformIO $ newSkeinGen >>= newIORef -- | Returns a HBox containing everything needed to add or modify an account, -- along with references to entry boxes containing the account's service -- name, account name and password respectively. newPasswordBox :: Dialog -> IO (HBox, Entry, Entry, Entry) newPasswordBox dlg = do box <- hBoxNew False 10 (pass, passframe, passent) <- generatorBox dlg (account, serviceent, userent) <- accountBox passframe dlg containerAdd box account containerAdd box pass return (box, serviceent, userent, passent) -- | Returns a VBox containing inputs for entering account details, an entry -- box which will contain a service name, and an entry box which will contain -- an account name for that service. accountBox :: Frame -> Dialog -> IO (VBox, Entry, Entry) accountBox passframe dlg = do vbox <- vBoxNew False 10 containerSetBorderWidth vbox 5 accountframe <- frameNew frameSetLabel accountframe "Account Details" accountbox <- vBoxNew False 5 containerSetBorderWidth accountbox 5 containerAdd accountframe accountbox containerAdd vbox accountframe -- Service name servicelabel <- labelNew (Just "Name of service/website") serviceent <- entryNew _ <- serviceent `on` entryActivate $ dialogResponse dlg ResponseAccept servicelblalign <- alignmentNew 0 0 0 0 containerAdd servicelblalign servicelabel containerAdd accountbox servicelblalign containerAdd accountbox serviceent -- Username for service userlabel <- labelNew (Just "Your username") userent <- entryNew _ <- userent `on` entryActivate $ dialogResponse dlg ResponseAccept userlblalign <- alignmentNew 0 0 0 0 containerAdd userlblalign userlabel containerAdd accountbox userlblalign containerAdd accountbox userent containerAdd vbox passframe set vbox [boxChildPacking passframe := PackNatural, boxChildPacking accountframe := PackNatural] return (vbox, serviceent, userent) -- | Returns a framed box containing settings for password generation, a framed -- box containing a password entry field with a "generate" button, and the -- password entry field itself. generatorBox :: Dialog -> IO (Frame, Frame, Entry) generatorBox dlg = do frame <- frameNew containerSetBorderWidth frame 5 frameSetLabel frame "Generator Settings" box <- vBoxNew False 10 containerSetBorderWidth box 5 containerAdd frame box -- What chars should go in the password? includeframe <- frameNew frameSetLabel includeframe "Password Characters" includebox <- vBoxNew False 5 containerSetBorderWidth includebox 5 lower <- checkButtonNewWithLabel "Include lowercase letters" upper <- checkButtonNewWithLabel "Include uppercase letters" numbers <- checkButtonNewWithLabel "Include numbers" special <- checkButtonNewWithLabel "Include symbols" mapM_ (flip toggleButtonSetActive True) [lower, upper, numbers, special] mapM_ (containerAdd includebox) [lower, upper, numbers, special] containerAdd includeframe includebox containerAdd box includeframe -- How long should it be? lenframe <- frameNew frameSetLabel lenframe "Password Length" numcharsbox <- hBoxNew False 5 containerSetBorderWidth numcharsbox 5 numchars <- spinButtonNewWithRange 4 100 1 spinButtonSetValue numchars 20 containerAdd numcharsbox numchars numcharslbl <- labelNew (Just "characters") containerAdd numcharsbox numcharslbl containerAdd lenframe numcharsbox set numcharsbox [boxChildPacking numcharslbl := PackNatural, boxChildPacking numchars := PackNatural] containerAdd box lenframe -- What does it look like? passframe <- frameNew frameSetLabel passframe "Your Password" passbox <- vBoxNew False 5 containerSetBorderWidth passbox 5 containerAdd passframe passbox -- Text box containing password. passent <- passwordBox dlg fd <- fontDescriptionNew fontDescriptionSetFamily fd "monospace" widgetModifyFont passent (Just fd) entrySetWidthChars passent 30 entrySetVisibility passent False containerAdd passbox passent -- Show the password? visible <- checkButtonNewWithLabel "Show password" containerAdd passbox visible _ <- visible `on` toggled $ do toggleButtonGetActive visible >>= entrySetVisibility passent -- Asessing password strength strbox <- hBoxNew False 5 containerSetBorderWidth strbox 5 ratinglbl <- labelNew (Just "Password strength:") containerAdd strbox ratinglbl rating <- labelNew (Just "N/A") containerAdd strbox rating set strbox [boxChildPacking ratinglbl := PackNatural, boxChildPacking rating := PackNatural] containerAdd passbox strbox -- Set up password ratings let fillPW = fillNewPassword rating passent numchars lower upper numbers special fillPR = entryGetText passent >>= fillPasswordRating rating mapM_ (\x -> x `on` buttonActivated $ fillPW) [lower,upper,numbers,special] _ <- onValueSpinned numchars fillPW widgetGrabFocus passent _ <- passent `on` editableChanged $ fillPR btn <- buttonNewWithLabel "Generate" _ <- btn `on` buttonActivated $ do fillNewPassword rating passent numchars lower upper numbers special containerAdd passbox btn set box [boxChildPacking includeframe := PackNatural, boxChildPacking lenframe := PackNatural] return (frame, passframe, passent) where fillNewPassword r ent chars bLower bUpper bNum bSym = do lower <- toggleButtonGetActive bLower upper <- toggleButtonGetActive bUpper num <- toggleButtonGetActive bNum sym <- toggleButtonGetActive bSym len <- spinButtonGetValue chars let ps = specify (floor len) lower upper num sym pass <- atomicModifyIORef' prng (generate ps) entrySetText ent pass fillPasswordRating r pass fillPasswordRating r pass = do let strength = judge $ analyze pass labelSetText r (show strength)
valderman/himitsu
src/PasswordGenerator.hs
Haskell
bsd-3-clause
6,212
{-# LANGUAGE DeriveDataTypeable , NoImplicitPrelude , PackageImports , UnicodeSyntax #-} module Data.LList ( LList , fromList , toList , cons , (++) , head , safeHead , last , safeLast , tail , safeTail , init , null , length , map , reverse , intersperse , intercalate , concat , take , drop , splitAt ) where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- import qualified "base" Data.List as L ( head, last, init, length , reverse, intersperse , foldr, foldl, foldr1, foldl1, map , genericTake, genericDrop ) import "base" Control.Applicative ( Applicative, pure, (<*>) , Alternative, empty, (<|>) ) import "base" Control.Monad ( Monad, return, (>>=), (>>), fail, ap ) import "base" Data.Bool ( Bool(False, True), otherwise ) import "base" Data.Eq ( Eq, (==), (/=) ) import "base" Data.Foldable ( Foldable, foldr, foldl, foldr1, foldl1 ) import "base" Data.Function ( ($) ) import "base" Data.Functor ( Functor, fmap ) import "base" Data.Maybe ( Maybe(Nothing, Just) ) import "base" Data.Monoid ( Monoid, mempty, mappend ) import "base" Data.Ord ( Ord, compare, (<), min, max ) import "base" Data.Typeable ( Typeable ) import "base" Prelude ( Num, (+), (-), fromIntegral, error ) import "base" Text.Show ( Show ) import "base-unicode-symbols" Data.Eq.Unicode ( (≡), (≢) ) import "base-unicode-symbols" Data.Function.Unicode ( (∘) ) import "base-unicode-symbols" Prelude.Unicode ( ℤ, (⋅) ) import "deepseq" Control.DeepSeq ( NFData, rnf ) -------------------------------------------------------------------------------- -- LList, a list with a known length -------------------------------------------------------------------------------- data LList α = LList !ℤ [α] deriving (Show, Typeable) -------------------------------------------------------------------------------- -- Basic list functions -------------------------------------------------------------------------------- fromList ∷ [α] → LList α fromList xs = LList (fromIntegral $ L.length xs) xs {-# INLINE fromList #-} toList ∷ LList α → [α] toList (LList _ xs) = xs {-# INLINE toList #-} cons ∷ α → LList α → LList α cons x (LList n xs) = LList (n + 1) (x : xs) (++) ∷ LList α → LList α → LList α (++) = mappend {-# INLINE (++) #-} head ∷ LList α → α head = L.head ∘ toList {-# INLINE head #-} safeHead ∷ LList α → Maybe α safeHead l | null l = Nothing | otherwise = Just (head l) last ∷ LList α → α last = L.last ∘ toList {-# INLINE last #-} safeLast ∷ LList α → Maybe α safeLast l | null l = Nothing | otherwise = Just (last l) tail ∷ LList α → LList α tail (LList n (_:xs)) = LList (n - 1) xs tail _ = error "Data.LList.tail: empty list" safeTail ∷ LList α → Maybe (LList α) safeTail l | null l = Nothing | otherwise = Just $ tail l init ∷ LList α → LList α init (LList n xs) = LList (n - 1) (L.init xs) null ∷ LList α → Bool null (LList n _) = n ≡ 0 {-# INLINE null #-} length ∷ LList α → ℤ length (LList n _) = n {-# INLINE length #-} map ∷ (α → β) → LList α → LList β map f (LList n xs) = LList n (L.map f xs) {-# INLINE map #-} reverse ∷ LList α → LList α reverse (LList n xs) = LList n (L.reverse xs) {-# INLINE reverse #-} intersperse ∷ α → LList α → LList α intersperse e (LList n xs) = LList (if n < 2 then n else 2⋅n - 1) (L.intersperse e xs) intercalate ∷ LList α → LList (LList α) → LList α intercalate xs xss = concat (intersperse xs xss) {-# INLINE intercalate #-} concat ∷ LList (LList α) → LList α concat = foldr mappend mempty {-# INLINE concat #-} take ∷ ℤ → LList α → LList α take i (LList n xs) = LList (min i n) (L.genericTake i xs) drop ∷ ℤ → LList α → LList α drop i (LList n xs) = LList (max 0 (n-i)) (L.genericDrop i xs) splitAt ∷ ℤ → LList α → (LList α, LList α) splitAt n l = (take n l, drop n l) {-# INLINE splitAt #-} -------------------------------------------------------------------------------- -- Instances -------------------------------------------------------------------------------- instance (NFData α) ⇒ NFData (LList α) where rnf (LList _ xs) = rnf xs -- Note that the length is already evaluated -- since it has a strictness flag. instance Foldable LList where foldr f z = L.foldr f z ∘ toList foldl f z = L.foldl f z ∘ toList foldr1 f = L.foldr1 f ∘ toList foldl1 f = L.foldl1 f ∘ toList instance (Eq α) ⇒ Eq (LList α) where (LList nx xs) == (LList ny ys) | nx ≢ ny = False | otherwise = xs ≡ ys (LList nx xs) /= (LList ny ys) | nx ≢ ny = True | otherwise = xs ≢ ys instance (Ord α) ⇒ Ord (LList α) where compare (LList _ xs) (LList _ ys) = compare xs ys instance Monoid (LList α) where mempty = fromList [] mappend (LList nx xs) (LList ny ys) = LList (nx + ny) (xs `mappend` ys) instance Functor LList where fmap = map instance Applicative LList where pure = return (<*>) = ap instance Alternative LList where empty = mempty (<|>) = mappend instance Monad LList where m >>= k = foldr (mappend ∘ k) mempty m m >> k = foldr (mappend ∘ (\_ → k)) mempty m return = fromList ∘ (: []) fail _ = mempty
roelvandijk/length-list
src/Data/LList.hs
Haskell
bsd-3-clause
5,867
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="si-LK"> <title>TLS Debug | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/tlsdebug/src/main/javahelp/org/zaproxy/zap/extension/tlsdebug/resources/help_si_LK/helpset_si_LK.hs
Haskell
apache-2.0
971
module TimeMaster (timeMaster) where import ServerMonad import Control.Concurrent.MVar import Data.Time.LocalTime import System.Posix.Env timeMaster :: TimeMasterVar -> IO () timeMaster tmvar = do (timezone, mv) <- takeMVar tmvar lt <- getLocalTimeInTimezone timezone putMVar mv lt timeMaster tmvar getLocalTimeInTimezone :: String -> IO LocalTime getLocalTimeInTimezone tz = do setEnv "TZ" tz True tzset t <- getZonedTime return $ zonedTimeToLocalTime t foreign import ccall "time.h tzset" tzset :: IO ()
haskell/ghc-builder
server/TimeMaster.hs
Haskell
bsd-3-clause
625
{-# LANGUAGE CPP #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} #ifndef MIN_VERSION_mtl #define MIN_VERSION_mtl(x,y,z) 0 #endif ----------------------------------------------------------------------------- -- | -- Module : Data.Machine.Plan -- Copyright : (C) 2012 Edward Kmett, Rúnar Bjarnason -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : provisional -- Portability : Rank-N Types, MPTCs -- ---------------------------------------------------------------------------- module Data.Machine.Plan ( -- * Plans Plan , runPlan , PlanT(..) , yield , maybeYield , await , stop , awaits , exhaust ) where import Control.Applicative import Control.Category import Control.Monad (MonadPlus(..)) import Control.Monad.Trans.Class import Control.Monad.IO.Class import Control.Monad.State.Class import Control.Monad.Reader.Class import Control.Monad.Error.Class import Control.Monad.Writer.Class import Data.Functor.Identity import Prelude hiding ((.),id) ------------------------------------------------------------------------------- -- Plans ------------------------------------------------------------------------------- -- | You can 'construct' a 'Plan' (or 'PlanT'), turning it into a -- 'Data.Machine.Type.Machine' (or 'Data.Machine.Type.MachineT'). -- newtype PlanT k o m a = PlanT { runPlanT :: forall r. (a -> m r) -> -- Done a (o -> m r -> m r) -> -- Yield o (Plan k o a) (forall z. (z -> m r) -> k z -> m r -> m r) -> -- forall z. Await (z -> Plan k o a) (k z) (Plan k o a) m r -> -- Fail m r } -- | A @'Plan' k o a@ is a specification for a pure 'Machine', that reads inputs selected by @k@ -- with types based on @i@, writes values of type @o@, and has intermediate results of type @a@. -- -- A @'Plan' k o a@ can be used as a @'PlanT' k o m a@ for any @'Monad' m@. -- -- It is perhaps easier to think of 'Plan' in its un-cps'ed form, which would -- look like: -- -- @ -- data 'Plan' k o a -- = Done a -- | Yield o (Plan k o a) -- | forall z. Await (z -> Plan k o a) (k z) (Plan k o a) -- | Fail -- @ type Plan k o a = forall m. PlanT k o m a -- | Deconstruct a 'Plan' without reference to a 'Monad'. runPlan :: PlanT k o Identity a -> (a -> r) -> (o -> r -> r) -> (forall z. (z -> r) -> k z -> r -> r) -> r -> r runPlan m kp ke kr kf = runIdentity $ runPlanT m (Identity . kp) (\o (Identity r) -> Identity (ke o r)) (\f k (Identity r) -> Identity (kr (runIdentity . f) k r)) (Identity kf) {-# INLINE runPlan #-} instance Functor (PlanT k o m) where fmap f (PlanT m) = PlanT $ \k -> m (k . f) {-# INLINE fmap #-} instance Applicative (PlanT k o m) where pure a = PlanT (\kp _ _ _ -> kp a) {-# INLINE pure #-} m <*> n = PlanT $ \kp ke kr kf -> runPlanT m (\f -> runPlanT n (\a -> kp (f a)) ke kr kf) ke kr kf {-# INLINE (<*>) #-} m *> n = PlanT $ \kp ke kr kf -> runPlanT m (\_ -> runPlanT n kp ke kr kf) ke kr kf {-# INLINE (*>) #-} m <* n = PlanT $ \kp ke kr kf -> runPlanT m (\a -> runPlanT n (\_ -> kp a) ke kr kf) ke kr kf {-# INLINE (<*) #-} instance Alternative (PlanT k o m) where empty = PlanT $ \_ _ _ kf -> kf {-# INLINE empty #-} PlanT m <|> PlanT n = PlanT $ \kp ke kr kf -> m kp ke kr (n kp ke kr kf) {-# INLINE (<|>) #-} instance Monad (PlanT k o m) where return = pure {-# INLINE return #-} PlanT m >>= f = PlanT (\kp ke kr kf -> m (\a -> runPlanT (f a) kp ke kr kf) ke kr kf) (>>) = (*>) {-# INLINE (>>) #-} fail _ = PlanT (\_ _ _ kf -> kf) {-# INLINE (>>=) #-} instance MonadPlus (PlanT k o m) where mzero = empty {-# INLINE mzero #-} mplus = (<|>) {-# INLINE mplus #-} instance MonadTrans (PlanT k o) where lift m = PlanT (\kp _ _ _ -> m >>= kp) {-# INLINE lift #-} instance MonadIO m => MonadIO (PlanT k o m) where liftIO m = PlanT (\kp _ _ _ -> liftIO m >>= kp) {-# INLINE liftIO #-} instance MonadState s m => MonadState s (PlanT k o m) where get = lift get {-# INLINE get #-} put = lift . put {-# INLINE put #-} #if MIN_VERSION_mtl(2,1,0) state f = PlanT $ \kp _ _ _ -> state f >>= kp {-# INLINE state #-} #endif instance MonadReader e m => MonadReader e (PlanT k o m) where ask = lift ask #if MIN_VERSION_mtl(2,1,0) reader = lift . reader #endif local f m = PlanT $ \kp ke kr kf -> local f (runPlanT m kp ke kr kf) instance MonadWriter w m => MonadWriter w (PlanT k o m) where #if MIN_VERSION_mtl(2,1,0) writer = lift . writer #endif tell = lift . tell listen m = PlanT $ \kp ke kr kf -> runPlanT m ((kp =<<) . listen . return) ke kr kf pass m = PlanT $ \kp ke kr kf -> runPlanT m ((kp =<<) . pass . return) ke kr kf instance MonadError e m => MonadError e (PlanT k o m) where throwError = lift . throwError catchError m k = PlanT $ \kp ke kr kf -> runPlanT m kp ke kr kf `catchError` \e -> runPlanT (k e) kp ke kr kf -- | Output a result. yield :: o -> Plan k o () yield o = PlanT (\kp ke _ _ -> ke o (kp ())) -- | Like yield, except stops if there is no value to yield. maybeYield :: Maybe o -> Plan k o () maybeYield = maybe stop yield -- | Wait for input. -- -- @'await' = 'awaits' 'id'@ await :: Category k => Plan (k i) o i await = PlanT (\kp _ kr kf -> kr kp id kf) -- | Wait for a particular input. -- -- @ -- awaits 'L' :: 'Plan' ('T' a b) o a -- awaits 'R' :: 'Plan' ('T' a b) o b -- awaits 'id' :: 'Plan' ('Data.Machine.Is.Is' i) o i -- @ awaits :: k i -> Plan k o i awaits h = PlanT $ \kp _ kr -> kr kp h -- | @'stop' = 'empty'@ stop :: Plan k o a stop = empty -- | Run a monadic action repeatedly yielding its results, until it returns Nothing. exhaust :: Monad m => m (Maybe a) -> PlanT k a m () exhaust f = do (lift f >>= maybeYield); exhaust f
bitemyapp/machines
src/Data/Machine/Plan.hs
Haskell
bsd-3-clause
6,013
{-# LANGUAGE RecordWildCards #-} module GHCJS.DOM.JSFFI.PositionError ( module Generated , PositionErrorCode(..) , PositionException(..) , throwPositionException ) where import Control.Exception (Exception, throwIO) import Control.Monad.IO.Class (MonadIO(..)) import GHCJS.DOM.JSFFI.Generated.PositionError as Generated data PositionErrorCode = PositionPermissionDenied | PositionUnavailable | PositionTimeout deriving (Show, Eq, Enum) data PositionException = PositionException { positionErrorCode :: PositionErrorCode, positionErrorMessage :: String } deriving (Show, Eq) instance Exception PositionException throwPositionException :: MonadIO m => PositionError -> m a throwPositionException error = do positionErrorCode <- (toEnum . subtract 1 . fromIntegral) <$> getCode error positionErrorMessage <- getMessage error liftIO $ throwIO (PositionException{..})
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/PositionError.hs
Haskell
mit
913
module X (foo) where foo = 10
itchyny/vim-haskell-indent
test/module/export.out.hs
Haskell
mit
30
{-# OPTIONS_JHC -fno-prelude -fm4 #-} module Jhc.Inst.Read() where import Prelude.Text import Jhc.Basics import Jhc.Float import Prelude.Float import Jhc.Num import Numeric(showSigned, showInt, readSigned, readDec, showFloat, readFloat, lexDigits) -- Reading at the Integer type avoids -- possible difficulty with minInt m4_define(READINST,{{ instance Read $1 where readsPrec p r = [(fromInteger i, t) | (i,t) <- readsPrec p r] }}) READINST(Int8) READINST(Int16) READINST(Int32) READINST(Int64) READINST(IntMax) READINST(IntPtr) m4_define(READWORD,{{ instance Read $1 where readsPrec _ r = readDec r }}) READWORD(Word) READWORD(Word8) READWORD(Word16) READWORD(Word32) READWORD(Word64) READWORD(WordMax) READWORD(WordPtr) instance Read () where readsPrec p = readParen False (\r -> [((),t) | ("(",s) <- lex r, (")",t) <- lex s ] ) instance Read Double where readsPrec p = readSigned readDouble instance Read Float where readsPrec p s = [ (doubleToFloat x,y) | (x,y) <- readSigned readDouble s]
m-alvarez/jhc
lib/jhc/Jhc/Inst/Read.hs
Haskell
mit
1,136
module Layout.Default where default (Float,Integer,Double) foo = 5
RefactoringTools/HaRe
test/testdata/Layout/Default.hs
Haskell
bsd-3-clause
70
{-# LANGUAGE Safe #-} ----------------------------------------------------------------------------- -- | -- Module : Data.STRef.Lazy -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable (uses Control.Monad.ST.Lazy) -- -- Mutable references in the lazy ST monad. -- ----------------------------------------------------------------------------- module Data.STRef.Lazy ( -- * STRefs ST.STRef, -- abstract newSTRef, readSTRef, writeSTRef, modifySTRef ) where import Control.Monad.ST.Lazy.Safe import qualified Data.STRef as ST import Prelude newSTRef :: a -> ST s (ST.STRef s a) readSTRef :: ST.STRef s a -> ST s a writeSTRef :: ST.STRef s a -> a -> ST s () modifySTRef :: ST.STRef s a -> (a -> a) -> ST s () newSTRef = strictToLazyST . ST.newSTRef readSTRef = strictToLazyST . ST.readSTRef writeSTRef r a = strictToLazyST (ST.writeSTRef r a) modifySTRef r f = strictToLazyST (ST.modifySTRef r f)
frantisekfarka/ghc-dsi
libraries/base/Data/STRef/Lazy.hs
Haskell
bsd-3-clause
1,152
-- | This module contains functions that act on factions. module Game.Cosanostra.Faction ( factionMembers , effectsFaction , winners ) where import Game.Cosanostra.Effect import Game.Cosanostra.Lenses import Game.Cosanostra.Types import Control.Lens import Data.Maybe import qualified Data.Set as S -- | Get all members of a action. factionMembers :: Players -> Turn -> Phase -> Faction -> S.Set Player factionMembers players turn phase faction = S.fromList $ filter (\player -> player ^. to (playerFaction players turn phase) == faction) (playerKeys players) effectsFaction :: [Effect] -> Faction effectsFaction = (^?! to effectsRecruited . effectType . effectTypeRecruitedFaction) -- | Get the faction for a player. -- -- Note this function is non-total, that is, will cause an error if the player -- does not have a faction. playerFaction :: Players -> Turn -> Phase -> Player -> Faction playerFaction players turn phase player = player ^?! to (playerEffects players player turn phase) . to effectsRecruited . effectType . effectTypeRecruitedFaction factionsPrimaryWinners :: Players -> Turn -> Phase -> Factions -> S.Set Faction factionsPrimaryWinners players turn phase factions = S.fromList [faction | player <- playerKeys players , isNothing (player ^. to (playerEffects players player turn phase) . to effectsCauseOfDeath) , let faction = player ^. to (playerFaction players turn phase) , factions ^?! ix faction . factionTraitsIsPrimary ] winners :: Players -> Turn -> Phase -> Factions -> Maybe [Player] winners players turn phase factions | S.size winningFactions > 1 = Nothing | otherwise = Just [player | player <- playerKeys players , let recruit = player ^?! to (playerEffects players player turn phase) . to effectsRecruited . effectType , let faction = recruit ^?! effectTypeRecruitedFaction , let factionTraits = factions ^?! ix faction , not (factionTraits ^. factionTraitsIsPrimary) || faction `S.member` winningFactions , checkConstraint players player turn phase (recruit ^?! effectTypeAgenda) ] where winningFactions = factionsPrimaryWinners players turn phase factions
rfw/cosanostra
src/Game/Cosanostra/Faction.hs
Haskell
mit
2,675
{- Copyright (C) 2015 Braden Walters This file is licensed under the MIT Expat License. See LICENSE.txt. -} {-# LANGUAGE QuasiQuotes #-} module Output.CPP (outputCpp) where import Data.List (intersperse, sortBy) import FollowTable import Rules import StartEndTable import StateTable import Text.RawString.QQ outputCpp :: FilePath -> [Rule] -> IO () outputCpp baseName rules = do outputHeader (baseName ++ ".hpp") rules outputSource (baseName ++ ".cpp") (baseName ++ ".hpp") rules outputSource :: FilePath -> FilePath -> [Rule] -> IO () outputSource fileName headerPath rules = let include = includeHeader headerPath tokenDefinitions = defineTokens [name | (Token name _) <- rules] transTables = rulesToCpp rules 1 tokenRulesList = rulesList "tokens" [x | x@(Token _ _) <- rules] ignoreRulesList = rulesList "ignores" [x | x@(Ignore _) <- rules] in writeFile fileName (include ++ sourceClasses ++ tokenDefinitions ++ transTables ++ tokenRulesList ++ ignoreRulesList ++ lexicalAnalyserCpp) outputHeader :: FilePath -> [Rule] -> IO () outputHeader fileName rules = let tokenNames = [name | (Token name _) <- rules] in writeFile fileName $ lexicalAnalyserHpp tokenNames includeHeader :: FilePath -> String includeHeader headerPath = [r| #include <cstdio> #include <stdexcept> #include "|] ++ headerPath ++ [r|" |] sourceClasses :: String sourceClasses = [r| const int END = -1; struct CharOrRange { bool end; bool is_range; char c1, c2; CharOrRange() : end(true) { } CharOrRange(char c1) : end(false), is_range(false), c1(c1) { } CharOrRange(char c1, char c2) : end(false), is_range(true), c1(c1), c2(c2) { } }; enum TransitionType { NONE, CHARACTER, CHARCLASS, ANYCHAR, }; struct StateTransition { TransitionType type; char character; CharOrRange* charclass; int goto_state; StateTransition(char c, int goto_state) : type(CHARACTER), character(c), charclass(0), goto_state(goto_state) { } StateTransition(CharOrRange* c, int goto_state) : type(CHARCLASS), character(0), charclass(c), goto_state(goto_state) { } StateTransition(int goto_state) : type(ANYCHAR), goto_state(goto_state) { } StateTransition() : type(NONE) { } }; struct Rule { bool end; Token token; StateTransition* transition_table; int num_transitions; int* accepting_states; Rule(StateTransition* transition_table, int num_transitions, int* accepting_states) : end(false), transition_table(transition_table), num_transitions(num_transitions), accepting_states(accepting_states) { } Rule(Token token, StateTransition* transition_table, int num_transitions, int* accepting_states) : end(false), token(token), transition_table(transition_table), num_transitions(num_transitions), accepting_states(accepting_states) { } Rule() : end(true) { } }; |] defineTokens :: [Name] -> String defineTokens rules = let defineToken name num = [r|Token |] ++ name ++ [r| = |] ++ show num ++ [r|;|] in concat (intersperse "\n" $ zipWith defineToken rules [1..]) rulesToCpp :: [Rule] -> Integer -> String rulesToCpp ((Class name charsAndRanges):rest) i = [r| CharOrRange charclass_|] ++ name ++ [r|[] = {|] ++ concat (intersperse ", " (map charOrRangeToCpp charsAndRanges)) ++ [r|, CharOrRange()}; |] ++ rulesToCpp rest i rulesToCpp ((Token name regex):rest) i = let seTable = buildStartEndTable regex followTable = buildFollowTable seTable stateTable = buildStateTable (head $ seTableEntries seTable) followTable in transitionTable name stateTable ++ acceptingStates name stateTable ++ rulesToCpp rest i rulesToCpp ((Ignore regex):rest) i = let seTable = buildStartEndTable regex followTable = buildFollowTable seTable stateTable = buildStateTable (head $ seTableEntries seTable) followTable in transitionTable (show i) stateTable ++ acceptingStates (show i) stateTable ++ rulesToCpp rest (i + 1) rulesToCpp [] _ = [] charOrRangeToCpp :: CharacterOrRange -> String charOrRangeToCpp (Character c) = [r|CharOrRange('|] ++ [c] ++ [r|')|] charOrRangeToCpp (Range c1 c2) = [r|CharOrRange('|] ++ [c1] ++ [r|', '|] ++ [c2] ++ [r|')|] transitionTable :: Name -> StateTable -> String transitionTable name stateTable = let rowLength = maxStateTransitions stateTable getTransitions (StateTableEntry _ _ transitions) = transitions transRows = map transAnyLast (map getTransitions $ stateTableEntries stateTable) in [r| StateTransition trans_|] ++ name ++ [r|[][|] ++ show rowLength ++ [r|] = { { |] ++ concat (intersperse "}, {" $ map (transitionRow rowLength) transRows) ++ [r| } }; int num_trans_|] ++ name ++ [r| = |] ++ show rowLength ++ [r|; |] transAnyLast :: [StateTransition] -> [StateTransition] transAnyLast transitions = let anyLast (RxAnyChar _) (RxAnyChar _) = EQ anyLast (RxAnyChar _) _ = GT anyLast _ (RxAnyChar _) = LT anyLast _ _ = EQ anyLastTransition (StateTransition rx1 _) (StateTransition rx2 _) = anyLast rx1 rx2 in sortBy anyLastTransition transitions transitionRow :: Integer -> [StateTransition] -> String transitionRow rowLength ((StateTransition (RxChar c _) num):rest) = [r| StateTransition('|] ++ toEscapeSequence c ++ [r|', |] ++ show num ++ [r|), |] ++ transitionRow (rowLength - 1) rest transitionRow rowLength ((StateTransition (RxClass name _) num):rest) = [r| StateTransition(charclass_|] ++ name ++ [r|, |] ++ show num ++ [r|), |] ++ transitionRow (rowLength - 1) rest transitionRow rowLength ((StateTransition (RxAnyChar _) num):rest) = [r| StateTransition(|] ++ show num ++ [r|), |] ++ transitionRow (rowLength - 1) rest transitionRow rowLength (item:rest) = transitionRow (rowLength - 1) rest transitionRow rowLength [] | rowLength > 0 = [r|StateTransition(),|] ++ transitionRow (rowLength - 1) [] | otherwise = [] acceptingStates :: Name -> StateTable -> String acceptingStates name stateTable = let accepting = filter isAcceptingState $ stateTableEntries stateTable toStateNum (StateTableEntry num _ _) = show num in [r|int accepting_|] ++ name ++ [r|[] = {|] ++ concat (intersperse ", " (map toStateNum accepting)) ++ [r|, END}; |] rulesList :: Name -> [Rule] -> String rulesList name rules = let toRule (Token name _) _ = [r|Rule(|] ++ name ++ [r|, &trans_|] ++ name ++ [r|[0][0], num_trans_|] ++ name ++ [r|, accepting_|] ++ name ++ [r|)|] toRule (Ignore _) id = [r|Rule(&trans_|] ++ show id ++ [r|[0][0], num_trans_|] ++ show id ++ [r|, accepting_|] ++ show id ++ [r|)|] toRule _ _ = "" ruleStrings = filter (not . null) $ zipWith toRule rules [1..] in [r| Rule rules_|] ++ name ++ [r|[] = { |] ++ concat (intersperse ", " ruleStrings) ++ [r|, Rule() }; |] lexicalAnalyserCpp :: String lexicalAnalyserCpp = [r| bool isAccepting(int accepting[], int current_state) { for (int i = 0; accepting[i] != END; ++i) { if (accepting[i] == current_state) return true; } return false; } enum DFAMatchResult { MATCHED, FAILED, REACHED_EOF, }; DFAMatchResult dfaMatch(Rule& rule, istream& input, string& lexeme) { streampos start_pos = input.tellg(); int current_state = 0; char current_char = (char) input.get(); string found_chars; bool made_transition = true; while (made_transition && current_char != EOF) { made_transition = false; for (int i = 0; i < rule.num_transitions && !made_transition; ++i) { StateTransition& cur_transition = rule.transition_table[(current_state * rule.num_transitions) + i]; switch (cur_transition.type) { case CHARACTER: { if (current_char == cur_transition.character) { current_state = cur_transition.goto_state; made_transition = true; } break; } case CHARCLASS: { bool success = false; for (int j = 0; !cur_transition.charclass[j].end; ++j) { CharOrRange& cur_char_or_range = cur_transition.charclass[j]; if (cur_char_or_range.is_range) { if (current_char >= cur_char_or_range.c1 && current_char <= cur_char_or_range.c2) success = true; } else { if (current_char == cur_char_or_range.c1) success = true; } } if (success) { current_state = cur_transition.goto_state; made_transition = true; } break; } case ANYCHAR: { current_state = cur_transition.goto_state; made_transition = true; break; } case NONE: break; } } if (made_transition) found_chars += current_char; current_char = (char) input.get(); } input.seekg(start_pos, input.beg); if (isAccepting(rule.accepting_states, current_state)) { lexeme = found_chars; return MATCHED; } else if (current_char == EOF) return REACHED_EOF; else { return FAILED; } } LexicalAnalyzer::LexicalAnalyzer(istream& input) : input(input) {} void LexicalAnalyzer::start() { input.seekg(0, input.beg); } bool LexicalAnalyzer::next(Token& t, string& lexeme) { string current_lexeme; bool reached_eof = false; do { lexeme = ""; for (int i = 0; !rules_ignores[i].end; ++i) { switch (dfaMatch(rules_ignores[i], input, current_lexeme)) { case MATCHED: if (current_lexeme.length() > lexeme.length()) lexeme = current_lexeme; break; case FAILED: break; case REACHED_EOF: reached_eof = true; } current_lexeme = ""; } if (lexeme.length() > 0) input.seekg(streamoff(lexeme.length()), input.cur); else if (reached_eof) return false; reached_eof = false; } while (lexeme.length() > 0); for (int i = 0; !rules_tokens[i].end; ++i) { switch (dfaMatch(rules_tokens[i], input, current_lexeme)) { case MATCHED: if (current_lexeme.length() > lexeme.length()) { t = rules_tokens[i].token; lexeme = current_lexeme; } case FAILED: break; case REACHED_EOF: reached_eof = true; } } if (lexeme.length() > 0) { input.seekg(streamoff(lexeme.length()), input.cur); return true; } else { if (reached_eof) return false; throw invalid_argument("Could not match a token in stream."); } } |] lexicalAnalyserHpp :: [Name] -> String lexicalAnalyserHpp tokenNames = let declareToken name = [r|extern Token |] ++ name ++ [r|;|] in [r| #ifndef LEXICAL_ANALYZER_HPP #define LEXICAL_ANALYZER_HPP #include <iostream> using namespace std; typedef int Token; |] ++ concat (intersperse "\n" $ map declareToken tokenNames) ++ [r| class LexicalAnalyzer { public: LexicalAnalyzer(istream& input = cin); void start(); bool next(Token& t, string& lexeme); private: istream& input; }; #endif |] maxStateTransitions :: StateTable -> Integer maxStateTransitions stateTable = let getTransitions (StateTableEntry _ _ transitions) = transitions transLists = map getTransitions $ stateTableEntries stateTable in maximum $ map (fromIntegral . length) transLists
meoblast001/lexical-analyser-generator
src/Output/CPP.hs
Haskell
mit
11,472
{-# LANGUAGE TupleSections, OverloadedStrings #-} module Handler.Home where import Import import App.Pieces import App.UTCTimeP import Data.Text as T -- This is a handler function for the GET request method on the HomeR -- resource pattern. All of your resource patterns are defined in -- config/routes -- -- The majority of the code you will write in Yesod lives in these handler -- functions. You can spread them across multiple files if you are so -- inclined, or create a single monolithic file. getHomeR :: Handler Html getHomeR = do (formWidget, formEnctype) <- generateFormPost sampleForm let submission = Nothing :: Maybe (FileInfo, Text) handlerName = "getHomeR" :: Text defaultLayout $ do aDomId <- newIdent setTitleI MsgMainPageTitle $(widgetFile "homepage") postHomeR :: Handler Html postHomeR = do ((result, formWidget), formEnctype) <- runFormPost sampleForm let handlerName = "postHomeR" :: Text submission = case result of FormSuccess res -> Just res _ -> Nothing defaultLayout $ do aDomId <- newIdent setTitle "Welcome To Yesod!" $(widgetFile "homepage") sampleForm :: Form (FileInfo, Text) sampleForm = renderDivs $ (,) <$> fileAFormReq "Choose a file" <*> areq textField "What's on the file?" Nothing
TimeAttack/time-attack-server
Handler/Home.hs
Haskell
mit
1,346
{-# LANGUAGE Arrows #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TemplateHaskell #-} module Db.PlaceCategory ( PlaceCategory'(PlaceCategory) , NewPlaceCategory , PlaceCategory , placeCategoryQuery , getPlaceCategory , insertPlaceCategory , placeCategoryId , placeCategoryName ) where import BasePrelude hiding (optional) import Control.Lens import Data.Profunctor.Product.TH (makeAdaptorAndInstance) import Data.Text (Text) import Opaleye import Db.Internal data PlaceCategory' a b = PlaceCategory { _placeCategoryId :: a , _placeCategoryName :: b } deriving (Eq,Show) makeLenses ''PlaceCategory' type PlaceCategory = PlaceCategory' Int Text type PlaceCategoryColumn = PlaceCategory' (Column PGInt4) (Column PGText) makeAdaptorAndInstance "pPlaceCategory" ''PlaceCategory' type NewPlaceCategory = PlaceCategory' (Maybe Int) Text type NewPlaceCategoryColumn = PlaceCategory' (Maybe (Column PGInt4)) (Column PGText) placeCategoryTable :: Table NewPlaceCategoryColumn PlaceCategoryColumn placeCategoryTable = Table "place_category" $ pPlaceCategory PlaceCategory { _placeCategoryId = optional "id" , _placeCategoryName = required "name" } placeCategoryQuery :: Query PlaceCategoryColumn placeCategoryQuery = queryTable placeCategoryTable insertPlaceCategory :: CanDb c e m => NewPlaceCategory -> m Int insertPlaceCategory = liftInsertReturningFirst placeCategoryTable (view placeCategoryId) . packNew getPlaceCategory :: CanDb c e m => Int -> m (Maybe PlaceCategory) getPlaceCategory i = liftQueryFirst $ proc () -> do p <- placeCategoryQuery -< () restrict -< p^.placeCategoryId .== pgInt4 i returnA -< p packNew :: NewPlaceCategory -> NewPlaceCategoryColumn packNew = pPlaceCategory PlaceCategory { _placeCategoryId = fmap pgInt4 , _placeCategoryName = pgStrictText }
benkolera/talk-stacking-your-monads
code-classy/src/Db/PlaceCategory.hs
Haskell
mit
2,004
module Parse ( totalCents, purchaseDate, maybeToEither ) where import Text.Read as R import Data.List as DL import Data.Char (isDigit) import Data.Time.Calendar import Data.Time.Format as DF import Data.Time.Clock totalCents :: String -> Either String Int totalCents "" = Left "empty input" totalCents s = case elemIndex ',' s of Nothing -> Left "Input contained no ','" Just p -> do let (integer_s, fractional_s) = splitAt p s let euros = digits integer_s let cents = digits $ if take 3 fractional_s == ",--" then "00" else fractional_s let unsigned = (+) <$> fmap (* 100) euros <*> cents if head s == '-' then negate <$> unsigned else unsigned -- todo: Figure out why an Either in parseTimeM will throw instead of filling in the left. purchaseDate :: String -> Either String Day purchaseDate s = do let utcTime = DF.parseTimeM True DF.defaultTimeLocale "%e %b, %Y" s :: Maybe Day maybeToEither ("Unable to parse '" ++ s ++ "' as date" ) utcTime digits :: String -> Either String Int digits "" = Left "Empty input" digits s = annotateLeft ("For input '" ++ s ++ "': ") (R.readEither (filter isDigit s) :: Either String Int) -- Prepends a string to the Left value of an Either String _ annotateLeft :: String -> Either String a -> Either String a annotateLeft _ (Right a) = Right a annotateLeft s (Left v) = Left(s ++ v) maybeToEither :: l -> Maybe a -> Either l a maybeToEither _ (Just a) = Right a maybeToEither l Nothing = Left l
fsvehla/steam-analytics
src/Parse.hs
Haskell
mit
1,544
module Main ( main ) where -- doctest import qualified Test.DocTest as DocTest main :: IO () main = DocTest.doctest [ "-isrc" , "src/AParser.hs" ]
mauriciofierrom/cis194-homework
homework10/test/examples/Main.hs
Haskell
mit
170
{-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedLabels #-} module Examples.Rpc.CalculatorClient (main) where import qualified Capnp.New as C import Capnp.Rpc (ConnConfig(..), fromClient, handleConn, socketTransport) import Control.Monad (when) import Data.Function ((&)) import Data.Functor ((<&>)) import qualified Data.Vector as V import Network.Simple.TCP (connect) import Capnp.Gen.Calculator.New main :: IO () main = connect "localhost" "4000" $ \(sock, _addr) -> handleConn (socketTransport sock C.defaultLimit) C.def { debugMode = True , withBootstrap = Just $ \_sup client -> do let calc :: C.Client Calculator calc = fromClient client value <- calc & C.callP #evaluate C.def { expression = Expression $ Expression'literal 123 } <&> C.pipe #value >>= C.callR #read C.def >>= C.waitPipeline >>= C.evalLimitT C.defaultLimit . C.parseField #value assertEq value 123 let getOp op = calc & C.callP #getOperator C.def { op } <&> C.pipe #func >>= C.asClient add <- getOp Operator'add subtract <- getOp Operator'subtract value <- calc & C.callP #evaluate C.def { expression = Expression $ Expression'call Expression'call' { function = subtract , params = V.fromList [ Expression $ Expression'call Expression'call' { function = add , params = V.fromList [ Expression $ Expression'literal 123 , Expression $ Expression'literal 45 ] } , Expression $ Expression'literal 67 ] } } <&> C.pipe #value >>= C.callR #read C.def >>= C.waitPipeline >>= C.evalLimitT C.defaultLimit . C.parseField #value assertEq value 101 putStrLn "PASS" } assertEq :: (Show a, Eq a) => a -> a -> IO () assertEq got want = when (got /= want) $ error $ "Got " ++ show got ++ " but wanted " ++ show want
zenhack/haskell-capnp
examples/lib/Examples/Rpc/CalculatorClient.hs
Haskell
mit
2,681
module Tree.Lists where import Tree.Types import Tree.BTree import Tree.Balanced (insert) -- IN-order traversal. -- 1. traverse left. 2. visit root. 3. traverse right. inOrdList :: BTree a -> [a] inOrdList = foldTree (\v lRes rRes -> lRes ++ v : rRes) [] -- POST-order traversal. -- 1. traverse left. 2. traverse right. 3. visit root. postOrdList :: BTree a -> [a] postOrdList = foldTree (\v lRes rRes -> rRes ++ v : lRes) [] -- PRE-order traversal. -- 1. visit root. 2. traverse left. 3. traverse right. -- Not ordered. aka 'flatten' preOrdList :: BTree a -> [a] preOrdList = foldTree (\v lRes rRes -> v : lRes ++ rRes) [] -- From >>pre<< OrdList, that is. fromPreList :: Ord a => [a] -> BTree a fromPreList [] = Empty fromPreList (x:xs) = Node x (fromPreList lefts) (fromPreList rights) where lefts = takeWhile (<= x) xs rights = dropWhile (<= x) xs -- This list doesn't need to be in any particular order at all. -- Creates a balanced tree. -- -- Not too efficient; with each folded-over `a`, -- it starts at the root of the tree and moves down to insert. fromList :: Ord a => [a] -> BTree a fromList = foldl (flip insert) Empty
marklar/elm-fun
BTree/Tree/Lists.hs
Haskell
mit
1,169
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DataKinds, ConstraintKinds, PolyKinds #-} {-# LANGUAGE FlexibleInstances, FlexibleContexts, UndecidableInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} module GrammarGen where import Generics.SOP import Random class Gen a where gen :: MonadDiscrete w m => m a instance (SListI l, All Gen l) => Gen (NP I l) where gen = case (sList :: SList l) of SNil -> return Nil SCons -> (:*) <$> (I <$> gen) <*> gen instance {-# OVERLAPPABLE #-} (Generic a, All2 Gen (Code a)) => Gen a where gen = uniform sums >>= fmap (to . SOP) sums :: forall w l m. (MonadDiscrete w m, All2 Gen l) => [m (NS (NP I) l)] sums = case (sList :: SList l) of SNil -> [] SCons -> (Z <$> gen) : map (fmap S) sums
vladfi1/hs-misc
GrammarGen.hs
Haskell
mit
780
module Util where import qualified System.Random.MWC as MWC import Data.ByteVector (fromByteVector) import System.IO.Temp (withSystemTempFile) import Data.ByteString.Lazy.Internal (defaultChunkSize) import System.IO (hClose) import Conduit import Control.Monad.Catch (MonadMask) import Data.Time (getCurrentTime, diffUTCTime) withRandomFile :: (MonadIO m, MonadMask m) => (FilePath -> m a) -> m a withRandomFile f = withSystemTempFile "random-file.bin" $ \fp h -> do liftIO $ do gen <- MWC.createSystemRandom replicateMC (4000000 `div` defaultChunkSize) (MWC.uniformVector gen defaultChunkSize) $$ mapC fromByteVector =$ sinkHandle h hClose h f fp timed :: MonadIO m => m a -> m a timed f = do start <- liftIO $ do start <- getCurrentTime putStrLn $ "Start: " ++ show start return start res <- f liftIO $ do end <- getCurrentTime putStrLn $ "End : " ++ show end print $ diffUTCTime end start return res
snoyberg/bytevector
bench/Util.hs
Haskell
mit
1,050
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Graphics.Tracy.Color ( -- * Colors Color (..) , from256 , Alpha , blending -- * Literals , white , gray , black , red , green , blue , cyan , magenta , yellow -- * Modifiers , Modifier , bright , dark ) where import Data.Default import Data.Monoid import Graphics.Tracy.V3 newtype Color = Color { clr :: V3 } deriving (Show, Read, Num) instance Default Color where def = gray -- | Mix two colors. instance Monoid Color where mempty = gray mappend (Color a) (Color b) = Color (avg a b) type Alpha = Double -- | Linear interpolation. blending :: Alpha -> Color -> Color -> Color blending alpha (Color a) (Color b) = Color ((alpha .* a) + ((1 - alpha) .* b)) {-# INLINE blending #-} -- | Build color from an RGB components. from256 :: Double -> Double -> Double -> Color from256 x y z = Color (V3 (x / 255) (y / 255) (z / 255)) white, gray, black :: Color white = from256 255 255 255 gray = from256 128 128 128 black = from256 0 0 0 red, green, blue :: Color red = from256 255 0 0 green = from256 0 255 0 blue = from256 0 0 255 cyan, magenta, yellow :: Color cyan = from256 0 255 255 magenta = from256 255 0 255 yellow = from256 0 255 255 type Modifier a = a -> a bright :: Modifier Color bright = (white <>) dark :: Modifier Color dark = (black <>)
pxqr/tracy
src/Graphics/Tracy/Color.hs
Haskell
mit
1,504
{-# LANGUAGE ScopedTypeVariables #-} module CodeGen where import Prelude import Data.List import qualified Data.Map as HashMap import qualified LLIR import LLIR hiding (blockName) import Text.Printf data CGContext = CGContext { -- label, constant string constStrs :: HashMap.Map String String, nextConstStrId :: Int, -- global arrays with sizes globalArrays :: [(String, Int)] } deriving(Eq, Show); newCGContext :: CGContext newCGContext = CGContext (HashMap.empty) 0 [] getConstStrId :: FxContext -> String -> (FxContext, String) getConstStrId fcx str = let gcx = global fcx strs = constStrs gcx in case HashMap.lookup str strs of Just name -> (fcx, name) Nothing -> let next = (nextConstStrId gcx) id = ".const_str" ++ (show next) gcx2 = gcx{ constStrs= HashMap.insert str id strs, nextConstStrId = next + 1 } in (fcx{global=gcx2}, id) addGlobals (CGContext constStrs nextConstStrId globalArrays) globals = -- only collects sizes of global arrays so the beginning of main function can set the lengths. let arrays = filter (\(_, (_, size)) -> case size of Just _ -> True Nothing -> False) (HashMap.toList globals) l = map (\(name, (_, Just size)) -> (".global_" ++ name, size)) arrays in CGContext constStrs nextConstStrId l data InstLoc = Register String | Memory String Int | Immediate Int deriving(Eq, Show); data FxContext = FxContext { name :: String, global :: CGContext, function :: LLIR.VFunction, blockName :: String, -- variables maps registers to a label/reg + offset variables :: HashMap.Map String InstLoc, offset :: Int, instrs :: [String], errors :: [String] } deriving(Eq, Show); newFxContext :: String -> CGContext -> LLIR.VFunction -> FxContext newFxContext name global func = FxContext name global func "entry" HashMap.empty 0 [] [] updateOffsetBy :: FxContext -> Int -> FxContext updateOffsetBy fcx size = fcx{offset=(offset fcx) + size} updateOffset :: FxContext -> FxContext updateOffset fcx = updateOffsetBy fcx 8 locStr :: InstLoc -> String locStr (Memory place offset) = (show offset) ++ "(" ++ place ++ ")" locStr (Register place) = place locStr (Immediate place) = "$" ++ (show place) getVar :: FxContext -> String -> InstLoc getVar fxc var = hml (variables fxc) var "getVar" lookupVariable :: FxContext -> String -> String lookupVariable fxc var = let table = (variables fxc) in case head var of '$' -> var _ -> locStr $ hml table var "lookupVariable" setVariableLoc :: FxContext -> String -> InstLoc -> FxContext setVariableLoc fcx var loc = fcx{variables=HashMap.alter update var (variables fcx)} where update _ = Just loc getHeader :: String getHeader = ".section .text\n" ++ ".globl main\n" -- args: [(Name, size)] getPreCall :: [(String, Int)] -> String getPreCall args = let argRegs = ["%rdi", "%rsi", "%rdx", "%rcx", "%r8", "%r9"] remainingArgs = drop (length argRegs) args argsInRegisters = (foldl (\acc (arg, reg) -> acc ++ " movq " ++ (fst arg) ++ ", " ++ reg ++ "\n") "" (zip args argRegs)) pushedArgs = (foldl (\acc arg -> acc ++ " pushq " ++ (fst arg) ++ "\n") "" (reverse remainingArgs)) in " #precall\n" ++ pusha ++ argsInRegisters ++ pushedArgs ++ " #/precall\n" getPostCall :: Int -> String getPostCall numArguments = " #postcall\n" ++ (intercalate "" $ replicate (numArguments - 6) " pop %rax\n") ++ popa ++ " #/postcall\n" getProlog :: FxContext -> Int -> Int -> String getProlog cx argsLength localsSize = let argRegs = ["%rdi", "%rsi", "%rdx", "%rcx", "%r8", "%r9"] argz = ( argRegs ++ (map (\i -> (show $ (i - (length argRegs) + 1) * 8) ++ "(%rbp)") (drop 6 [1..argsLength]) ) ) in " #prolog\n" ++ " push %rbp\n" ++ " movq %rsp, %rbp\n" ++ " subq $" ++ (show localsSize) ++ ", %rsp\n" ++ -- put register arguments to stack ( arrayToLine $ concat $ map (\(x, y) -> let fm = x to = getRef cx $ ArgRef (y-1) (name cx) in if fm == to then [] else move x to ) $ zip argz [1..argsLength] ) ++ " #/prolog\n" getEpilog :: String getEpilog = " \n" ++ " #epilog\n" ++ " movq %rbp, %rsp\n" ++ " pop %rbp\n" ++ " ret\n" ++ " #/epilog\n" genGlobals :: HashMap.Map String (VType, Maybe Int) -> String genGlobals globals = ".bss\n" ++ (intercalate "" $ map genGlobal $ HashMap.toList globals) ++ "\n" genGlobal :: (String, (VType, Maybe Int)) -> String genGlobal (name, (_, Nothing)) = ".global_" ++ name ++ ":\n .zero 8\n" -- Need to adjust for arrays genGlobal (name, (_, Just size)) = -- an extra 8-byte word for storing the length ".global_" ++ name ++ ":\n .zero " ++ show (8 * (1 + size)) ++ "\n" genCallouts :: HashMap.Map String String -> String genCallouts callouts = "" -- Not sure how to declare global strings closestMultipleOf16 num = ((num + 15) `div` 16) * 16 localSize instr = case instr of VStore _ _ _ -> 0 VArrayStore _ _ _ _ -> 0 VReturn _ _ -> 0 VCondBranch _ _ _ _ -> 0 VUncondBranch _ _ -> 0 VUnreachable _ -> 0 VAllocation _ _ (Just x) -> (x + 1) * 8 VAllocation _ _ Nothing -> 8 _ -> 8 calculateLocalsSize instrs = foldl (+) 0 (map localSize instrs) genFunction :: CGContext -> LLIR.VFunction -> (CGContext, String) genFunction cx f = let argsLength = length $ LLIR.arguments f instrs = concat $ map (\x -> snd $ getBlockInstrs f $ hml (LLIR.blocks f) x "getblocks" ) (LLIR.blockOrder f) nzInst = (filter (\x -> 0 /= (localSize x)) instrs) localsSize = (8*argsLength) + (calculateLocalsSize nzInst) ncx0 = foldl (\cx (idx, arg) -> let sz = 8 in if idx <= 6 then updateOffsetBy ( setVariableLoc cx (LLIR.functionName f ++ "@" ++ show (idx - 1)) (Memory "%rbp" $ ( -((offset cx) + sz) ) ) ) sz else setVariableLoc cx (LLIR.functionName f ++ "@" ++ show (idx - 1)) (Memory "%rbp" $ ( (idx - 6) + 2 ) * 6 ) ) (newFxContext (LLIR.functionName f) cx f) (zip [1..argsLength] $ LLIR.arguments f) ncx1 = foldl (\cx arg -> let sz = localSize arg in updateOffsetBy ( setVariableLoc cx (LLIR.getName arg) (Memory "%rbp" $ ( -((offset cx) + sz) ) ) ) sz ) ncx0 nzInst (ncx2, blocksStr) = foldl (\(cx, s) name -> let block = hml (LLIR.blocks f) name "getFunc-Block" (ncx, str) = genBlock cx{blockName=name} block name f in (ncx, s ++ str)) (ncx1, "") $ LLIR.blockOrder f prolog = getProlog ncx2 argsLength (closestMultipleOf16 localsSize) strRes = "\n" ++ LLIR.functionName f ++ ":\n" ++ prolog ++ blocksStr ++ getEpilog in --if (LLIR.getName f) /= "sum" then (global ncx2, strRes) --else --error ( printf "localsSize:%s\n\nncx0:%s\n\nncx1:%s\n\nncx2:%s\n\n%s" (show localsSize) (show ncx0) (show ncx1) (show ncx2) (show (map (\y -> getRef ncx2 $ ArgRef (y-1) (name ncx2) ) [1..argsLength] ) ) ) getBlockInstrs :: LLIR.VFunction -> LLIR.VBlock -> (Bool,[LLIR.VInstruction]) getBlockInstrs f block = let instructions :: [String] = LLIR.blockInstructions block term = last instructions termI = instCastU f $ InstRef term instructions2 :: [String] = case termI of VCondBranch _ _ _ _ -> filter (\x -> case do inst <- instCast f $ InstRef x _ <- case inst of VBinOp _ op _ _ -> if elem op ["<","<=",">",">=","u<","u<=","u>","u>=","==","!="] then Just True else Nothing _ -> Nothing uses <- return $ getUses inst f _ <- if 1 == length uses then Just True else Nothing if ( getName $ getUseInstr2 f (uses !! 0) ) == term then Just True else Nothing of Just _ -> False _ -> True ) instructions _ -> instructions instrs = map (\x -> instCastU f $ InstRef x) instructions2 in ( (length instructions)/=(length instructions2), instrs ) makeOneReg :: String -> String -> String -> (String,String,[String]) makeOneReg a b c = if (isMemoryS a) && (isMemoryS b) then (c,b,move a c) else (a,b,[]) swapBinop :: String -> String swapBinop a | a == "==" = "==" | a == "!=" = "!=" | a == ">" = "<" | a == ">=" = "<=" | a == "<" = ">" | a == "<=" = ">=" | a == "u>" = "u<" | a == "u>=" = "<u=" | a == "u<" = "u>" | a == "u<=" = "u>=" genBlock :: FxContext -> LLIR.VBlock -> String -> LLIR.VFunction -> (FxContext, String) genBlock cx block name f = let instructions = LLIR.blockInstructions block term = last instructions (fastTerm, instructions2) = getBlockInstrs f block instructions3 = if fastTerm then take ((length instructions2)-1) instructions2 else instructions2 (ncx, s) = foldl (\(cx, acc) instruction -> let (ncx, str) = genInstruction cx instruction in (ncx, acc ++ ( "# " ++ (show instruction) ++ "\n" ) ++ str)) (cx, "") instructions3 blockName = LLIR.blockFunctionName block ++ "_" ++ LLIR.blockName block setupGlobals = if blockName /= "main_entry" then "" else genSetupGlobals (global cx) fastEnd = if not fastTerm then "" else let termI = instCastU f $ InstRef term (_,cond,tB, fB) = case termI of VCondBranch a c t f -> (a, c, t, f) _ -> error "badcond" cmpI = instCastU f $ cond (_,op0,a1,a2) = case cmpI of VBinOp a b c d -> (a,b,c,d) _ -> error "badbin" r1 :: String = getRef cx a1 r2 :: String = getRef cx a2 phis = (LLIR.getPHIs (function cx) tB) ++ (LLIR.getPHIs (function cx) fB) cors = concat $ map (\(VPHINode pname hm) -> let var = locStr $ getVar cx pname str :: String = CodeGen.blockName cx val = getRef cx (hml hm str "genBlock") in move val var ) phis (x1,x2,mvs) = makeOneReg r1 r2 "%rax" (y1,y2,op) = if isImmediateS x1 then (x2, x1, swapBinop op0) else (x1, x2, op0) mp = HashMap.fromList [("==","je"),("!=","jne"),("u<","jb"),("u<=","jbe"),("u>","ja"),("u>","jae"),("<","jl"),("<=","jle"),(">","jg"),(">=","jge")] insts = ["# " ++ (show cmpI), "# "++ (show termI), printf "cmpq %s, %s" y2 y1, printf "%s %s_%s" (hml mp op "reverse cmp") (CodeGen.name cx) tB, printf "jmp %s_%s" (CodeGen.name cx) fB] in arrayToLine $ cors ++ mvs ++ insts in (ncx, blockName ++ ":\n" ++ setupGlobals ++ s ++ fastEnd) genSetupGlobals cx = concat $ map (\(name, size) -> arrayToLine $ move ("$" ++ (show size)) name ) $ globalArrays cx arrayToLine :: [String] -> String arrayToLine ar = concat $ map (\x -> " " ++ x ++ "\n") ar genUOp :: String -> String -> String genUOp op reg = case op of "-" -> printf "negq %s" reg "!" -> printf "xorq $1, %s" reg isMemory :: InstLoc -> Bool isMemory (Memory _ _ ) = True isMemory _ = False isMemoryS :: String -> Bool isMemoryS s = ( (last s) == ')' ) || ( (take (length ".global") s) == ".global" ) isRegisterS :: String -> Bool isRegisterS s = (head s) == '%' isImmediateS :: String -> Bool isImmediateS s = (head s) == '$' move :: String -> String -> [String] move loc1 loc2 = if loc1 == loc2 then [] else if (isMemoryS loc1) && (isMemoryS loc2) then [printf "movq %s, %s" loc1 "%rax", printf "movq %s, %s" "%rax" loc2 ] else [printf "movq %s, %s" loc1 loc2] makeReg :: String -> String -> (String,[String]) makeReg reg tmp = if isRegisterS reg then (reg, []) else (tmp, move reg tmp) genInstruction cx (VAllocation result tp size) = let s = case size of Just i -> i Nothing -> 0 -- reserve first 8-byte number to store the length of the array var = getVar cx result -- in case of an array, skip first byte stackOffset = case var of Memory loc off -> off _ -> error "badd var for allocation" destination = (show stackOffset) ++ "(%rbp)" ncx :: FxContext = case size of -- if array, store location of its length lookup at the head Just i -> let cx2 = setVariableLoc cx (result) (Memory "%rbp" $ stackOffset + 8) cx3 = setVariableLoc cx2 (result ++ "@len" ) (Memory "%rbp" $ stackOffset) in cx3 Nothing -> cx ncx2 = ncx zeroingCode = case size of Just sz -> " # bzero\n" ++ " cld\n" ++ " leaq " ++ (locStr $ getVar ncx2 result ) ++ ", %rdi\n" ++ " movq $" ++ (show sz) ++ ", %rcx\n" ++ " movq $0, %rax\n" ++ " rep stosq\n" ++ " # /bzero\n" Nothing -> "" in (ncx2, (if s > 0 then arrayToLine ( move ("$" ++ (show s)) destination ) else "") ++ zeroingCode ) genInstruction cx (VUnOp result op val) = let loc = getRef cx val var = getVar cx result vloc = locStr var oploc = case var of Register _ -> vloc _ -> "%rax" insts = move loc oploc ++ [ genUOp op oploc ] ++ move oploc vloc in (cx, arrayToLine insts) genInstruction cx (VPHINode _ _) = (cx, "") genInstruction cx (VBinOp result op val1 val2) = let loc1 = getRef cx val1 loc2 = getRef cx val2 var = getVar cx result vloc = locStr var oploc = case var of Register _ -> vloc _ -> "%rax" cp = move oploc vloc in (cx, ( if ((op == "/") || (op == "%")) then -- in A/B require A in rax, rdx empty let (nreg, inst0) = if isImmediateS loc2 then makeReg loc2 "%rbx" else (loc2,[]) (instA, out) :: ([String], String) = genOpB op loc1 nreg in (arrayToLine ( inst0 ++ instA ++ (move out vloc) ) ) else (arrayToLine $ move loc1 oploc) ++ ( arrayToLine $ genOp op loc2 oploc ) ++ ( arrayToLine cp ) ) ) genInstruction cx (VMethodCall name isCallout fname args) = -- push arguments let (ncx, nargs) = foldl (\(cx, acc) arg -> let (ncx, narg) = genArg cx arg in (ncx, acc ++ [narg])) (cx, []) args precall = getPreCall nargs cleanRax = " movq $0, %rax\n" postcall = getPostCall $ length args destination = locStr $ getVar cx name (ncx2, exitMessage) = if fname == "exit" && isCallout then genExitMessage cx (args !! 0) else (ncx, "") in (ncx2, exitMessage ++ precall ++ cleanRax ++ " callq " ++ fname ++ "\n movq %rax, " ++ destination ++ "\n" ++ postcall) genInstruction cx (VStore _ val var) = let loc1 = getRef cx val loc2 = getRef cx var in (cx, arrayToLine $ move loc1 loc2) genInstruction cx (VLookup result val) = let loc = getRef cx val destination = locStr $ getVar cx result in (cx, arrayToLine $ move loc destination) genInstruction cx (VArrayStore _ val arrayRef idxRef) = let arr = case arrayRef of InstRef s -> lookupVariable cx s GlobalRef s -> ".global_" ++ s _ -> "bad array store " ++ (show arrayRef) isGlobal = case arrayRef of GlobalRef _ -> True _ -> False idx = getRef cx idxRef loc = getRef cx val in (cx, " leaq " ++ arr ++ ", %rax\n" ++ " movq " ++ idx ++ ", %rbx\n" ++ (if isGlobal then " addq $1, %rbx\n" else "") ++ " leaq (%rax, %rbx, 8), %rbx\n" ++ " movq " ++ loc ++ ", %rax\n" ++ " movq %rax, (%rbx)\n") genInstruction cx (VArrayLookup result arrayRef idxRef) = let arr = case arrayRef of InstRef s -> lookupVariable cx s GlobalRef s -> ".global_" ++ s _ -> "bad array lookup " ++ (show arrayRef) isGlobal = case arrayRef of GlobalRef _ -> True _ -> False idx = getRef cx idxRef destination = locStr $ getVar cx result in (cx, " leaq " ++ arr ++ ", %rax\n" ++ " movq " ++ idx ++ ", %rbx\n" ++ (if isGlobal then " addq $1, %rbx\n" else "") ++ " movq (%rax, %rbx, 8), %rbx\n" ++ " movq %rbx, " ++ destination ++ "\n") genInstruction cx (VArrayLen result ref) = let access = case ref of InstRef s -> lookupVariable cx (s ++ "@len") GlobalRef s -> ".global_" ++ s _ -> "bad VArrayLen of " ++ (show ref) destination = locStr $ getVar cx result in (cx, " movq " ++ access ++ ", %rax\n" ++ " movq %rax, " ++ destination ++ "\n") genInstruction cx (VReturn _ maybeRef) = case maybeRef of Just ref -> (cx, " movq " ++ (snd (genAccess cx ref)) ++ ", %rax\n" ++ " movq %rbp, %rsp\n pop %rbp\n ret\n" ) Nothing -> if name cx == "main" then (cx, " movq %rbp, %rsp\n xorq %rax, %rax\n pop %rbp\n ret\n" ) else (cx, " movq %rbp, %rsp\n pop %rbp\n ret\n" ) -- TODO MOVE CMP / etc genInstruction cx (VCondBranch result cond true false) = let loc :: String = getRef cx cond phis = (LLIR.getPHIs (function cx) true) ++ (LLIR.getPHIs (function cx) false) cors = concat $ map (\(VPHINode pname hm) -> let var = locStr $ getVar cx pname val = getRef cx (hml hm (blockName cx) "condBr" ) in move val var ) phis (reg, inst1) :: (String, [String]) = makeReg loc "%rax" insts = inst1 ++ [printf "testq %s, %s" reg reg, printf "jnz %s_%s" (name cx) true, printf "jz %s_%s" (name cx) false] in ( cx, arrayToLine $ cors ++ insts ) genInstruction cx (VUnreachable _) = (cx, " # unreachable instruction\n") genInstruction cx (VUncondBranch result dest) = let phis = LLIR.getPHIs (function cx) dest cors :: [String] = concat $ map (\(VPHINode pname hm) -> let var = locStr $ getVar cx pname val = getRef cx (hml hm (blockName cx) "uncondBr") in move val var ) phis in (cx, arrayToLine $ cors ++ [printf "jmp %s_%s" (name cx) dest ]) genExitMessage :: FxContext -> ValueRef -> (FxContext, String) genExitMessage cx val = (ncx, " xorq %rax, %rax\n movq $" ++ message ++ ", %rdi\n" ++ " call printf\n") where (ncx, message) = case val of LLIR.ConstInt (-1) -> getConstStrId cx ("\"*** RUNTIME ERROR ***: Array out of Bounds access in method \\\"" ++ name cx ++ "\\\"\\n\"") LLIR.ConstInt (-2) -> getConstStrId cx ("\"*** RUNTIME ERROR ***: Method \\\"" ++ name cx ++ "\\\" didn't return\\n\"") quadRegToByteReg :: String -> String quadRegToByteReg a | a == "%rax" = "%al" | a == "%rbx" = "%bl" | a == "%rcx" = "%cl" | a == "%rdx" = "%dl" | a == "%r8" = "%r8b" | a == "%r9" = "%r9b" | a == "%r10" = "%r10b" | a == "%r11" = "%r11b" | a == "%r12" = "%r12b" | a == "%r13" = "%r13b" | a == "%r14" = "%r14b" | a == "%r15" = "%r15b" | a == "%rsp" = "%spl" | a == "%rbp" = "%bpl" | a == "%rsi" = "%sil" | a == "%rsd" = "%dil" quadRegToWordReg :: String -> String quadRegToWordReg a | a == "%rax" = "%eax" | a == "%rbx" = "%ebx" | a == "%rcx" = "%ecx" | a == "%rdx" = "%edx" | a == "%r8" = "%r8b" | a == "%r9" = "%r9b" | a == "%r10" = "%r10d" | a == "%r11" = "%r11d" | a == "%r12" = "%r12d" | a == "%r13" = "%r13d" | a == "%r14" = "%r14d" | a == "%r15" = "%r15d" | a == "%rsp" = "%esp" | a == "%rbp" = "%ebp" | a == "%rsi" = "%esi" | a == "%rsd" = "%ed" zero :: String -> String zero reg = printf "xorl %s, %s" reg -- arg2 must be register, arg1 may be memory -- OP -> arg1 -> arg2 / output -> insts genOp :: String -> String -> String -> [String] -- out is RHS and must be reg/mem, loc is LHS could be immediate/etc genOp "+" loc out = [printf "addq %s, %s" loc out] genOp "-" loc out = [printf "subq %s, %s" loc out] genOp "*" loc out = [printf "imulq %s, %s" loc out] genOp "==" loc out = [printf "cmpq %s, %s" loc out, printf "sete %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp "!=" loc out = [printf "cmpq %s, %s" loc out, printf "setne %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp "<" loc out = [printf "cmpq %s, %s" loc out, printf "setl %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp "<=" loc out = [printf "cmpq %s, %s" loc out, printf "setle %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp ">" loc out = [printf "cmpq %s, %s" loc out, printf "setg %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp ">=" loc out = [printf "cmpq %s, %s" loc out, printf "setge %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp "u<" loc out = [printf "cmpq %s, %s" loc out, printf "setb %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp "u<=" loc out = [printf "cmpq %s, %s" loc out, printf "setbe %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp "u>" loc out = [printf "cmpq %s, %s" loc out, printf "seta %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp "u>=" loc out = [printf "cmpq %s, %s" loc out, printf "setae %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp "|" loc out = [printf "orq %s, %s" loc out] -- ++ ", %rax\n cmp %rax, $0\n movq $0, %rax\n setnz %al\n" genOp "&" loc out = [printf "andq %s, %s" loc out]-- ++ ", %rax\n cmp %rax, $0\n movq $0, %rax\n setnz %al\n" -- requires RAX, RDX, and divisor -- In A/B %rax must contain A, arg2 contains B -- returns instructions, output -- op arg2 genOpB :: String -> String -> String -> ([String], String) genOpB "/" arg1 arg2 = ((move arg1 "%rax") ++ ["cqto", printf "idivq %s" arg2], "%rax") genOpB "%" arg1 arg2 = ((move arg1 "%rax") ++ ["cqto", printf "idivq %s" arg2], "%rdx") genArg :: FxContext -> ValueRef -> (FxContext, (String, Int)) genArg cx x = let (ncx, asm) = genAccess cx x in (ncx, (asm, 8)) getRef :: FxContext -> ValueRef -> String getRef cx (InstRef ref) = lookupVariable cx ref getRef cx (ConstInt i) = "$" ++ (show i) getRef cx (ConstString s) = let (ncx, id) = getConstStrId cx s in "$" ++ id getRef cx (ConstBool b) = "$" ++ (if b then "1" else "0") getRef cx (ArgRef i funcName) = if i < 6 then lookupVariable cx $ funcName ++ "@" ++ (show i) else (show $ 16 + 8 * (i - 6)) ++ "(%rbp)" getRef cx (GlobalRef name) = ".global_" ++ name genAccess :: FxContext -> ValueRef -> (FxContext, String) genAccess cx (InstRef ref) = (cx, lookupVariable cx ref) genAccess cx (FunctionRef i) = (cx, "$" ++ i) genAccess cx (ConstInt i) = (cx, "$" ++ (show i)) genAccess cx (ConstString s) = let (ncx, id) = getConstStrId cx s in (ncx, "$" ++ id) genAccess cx (ConstBool b) = (cx, "$" ++ (if b then "1" else "0")) genAccess cx (ArgRef i funcName) = (cx, if i < 6 then lookupVariable cx $ funcName ++ "@" ++ (show i) else (show $ 16 + 8 * (i - 6)) ++ "(%rbp)") genAccess cx (GlobalRef name) = (cx, ".global_" ++ name) genConstants cx = ".section .rodata\n" ++ HashMap.foldWithKey (\cnst label str-> str ++ "\n" ++ label ++ ":\n .string " ++ cnst) "" (constStrs cx) gen :: LLIR.PModule -> String gen mod = let globals = LLIR.globals mod callouts = LLIR.callouts mod fxs = HashMap.elems $ LLIR.functions mod cx = newCGContext cx2 = addGlobals cx globals (cx3, fns) = foldl (\(cx, asm) fn -> let (ncx, str) = genFunction cx fn in (ncx, asm ++ str)) (cx2, "") fxs in (genGlobals globals) ++ getHeader ++ (genCallouts callouts) ++ fns ++ "\n\n" ++ (genConstants cx3) ++ "\n" pusha = " push %rax\n" ++ " push %rbx\n" ++ " push %rcx\n" ++ " push %rdx\n" ++ " push %rsi\n" ++ " push %rdi\n" ++ " push %r8\n" ++ " push %r9\n" ++ " push %r10\n" ++ " push %r11\n" ++ " push %r12\n" ++ " push %r13\n" ++ " push %r14\n" ++ " push %r15\n" popa = " pop %r15\n" ++ " pop %r14\n" ++ " pop %r13\n" ++ " pop %r12\n" ++ " pop %r11\n" ++ " pop %r10\n" ++ " pop %r9\n" ++ " pop %r8\n" ++ " pop %rdi\n" ++ " pop %rsi\n" ++ " pop %rdx\n" ++ " pop %rcx\n" ++ " pop %rbx\n" ++ " pop %rax\n"
Slava/6.035-decaf-compiler
src/CodeGen.hs
Haskell
mit
25,071
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-} module Pitch.Players.Network where import Control.Applicative import Control.Concurrent import Control.Monad import Control.Monad.Writer import Data.Aeson (ToJSON, toJSON, FromJSON, fromJSON, encode, decode, Value (..), object, (.:), (.=), parseJSON, (.:?)) import Data.ByteString.Lazy.Char8 (pack) import qualified Data.Text as T import GHC.Generics import Pitch.Game import Pitch.Card import Pitch.Network import Pitch.Network.JSON import System.Random data NetworkConfig = NetworkConfig {readChannel :: Chan String ,writeChannel :: Chan (Status, GameState) ,state :: MVar (Writer [String] (GameState, ActionRequired, Int)) ,authentication :: MVar (Bool, String) ,thread :: ThreadId } data ActionRequired = Wait | BidAction | PlayAction deriving (Show, Generic) instance ToJSON ActionRequired where toJSON action = String . T.pack $ case action of Wait -> "Wait" BidAction -> "Bid" PlayAction -> "Play" instance FromJSON ActionRequired where parseJSON (String v) = case T.unpack v of "Wait" -> return Wait "Bid" -> return BidAction "Play" -> return PlayAction _ -> mzero parseJSON _ = mzero data NetStatus = NetStatus {messages :: [String], gamestate :: (GameState, ActionRequired, Int)} deriving (Show, Generic) instance ToJSON NetStatus instance FromJSON NetStatus data Status = Success String | Failure String instance ToJSON Status where toJSON (Success m) = object ["code" .= toJSON (20 :: Int), "message" .= toJSON m] toJSON (Failure m) = object ["code" .= toJSON (50 :: Int), "message" .= toJSON m] instance FromJSON Status where parseJSON (Object v) = mkStatus <$> v .: "code" <*> v .: "message" parseJSON _ = mzero mkStatus :: Int -> String -> Status mkStatus 20 = Success mkStatus 50 = Failure mkNetworkConfig :: StdGen -> IO (NetworkConfig, StdGen) mkNetworkConfig g = do rchannel <- newChan wchannel <- newChan state <- newEmptyMVar authentication <- newMVar (False, token) threadId <- forkIO $ runServer (rchannel, wchannel, state, authentication) return (NetworkConfig {readChannel = rchannel ,writeChannel = wchannel ,state = state ,thread = threadId ,authentication = authentication } ,g' ) where (token, g') = iterate (\(xs, g) -> let (x, g') = randomR ('A', 'Z') g in (x:xs, g')) ([], g) !! 20 setAction :: MVar (Writer [String] (GameState, ActionRequired, Int)) -> ActionRequired -> IO () setAction mvar ar = modifyMVar_ mvar $ \w -> return (do (a, _, c) <- w return (a, ar, c)) setGameState :: MVar (Writer [String] (GameState, ActionRequired, Int)) -> GameState -> IO () setGameState mvar gs = modifyMVar_ mvar $ \w -> return (do (_, b, c) <- w return (gs, b, c)) putMessage :: MVar (Writer [String] a) -> String -> IO () putMessage mvar message = modifyMVar_ mvar $ \w -> return (do v <- w tell [message] return v) updateMVAR :: Monoid a => MVar (Writer a b) -> b -> IO () updateMVAR mvar v = do mw <- tryTakeMVar mvar case mw of Nothing -> putMVar mvar (writer (v, mempty)) Just x -> putMVar mvar (do x return v) mkNetworkPlayerFromConfig :: NetworkConfig -> String -> Player mkNetworkPlayerFromConfig netc@NetworkConfig {readChannel=rchannel ,writeChannel=wchannel ,state=state ,authentication=authentication ,thread=threadId } name = player where player = defaultPlayer { initGameState = \pid gs -> updateMVAR state (gs, Wait, pid) , mkBid = \pid gs -> do setAction state BidAction setGameState state gs string <- readChan rchannel let maybeBid = decode (pack string) :: Maybe (Int, Maybe Suit) bid <- case maybeBid of Just x -> return x Nothing -> do writeChan wchannel (Failure "Parser error", gs) (mkBid player) pid gs validatedBid <- case validateBid pid gs bid of Nothing -> return bid Just errorMessage -> do writeChan wchannel (Failure errorMessage, gs) (mkBid player) pid gs writeChan wchannel (Success "Bid accepted", gs) setAction state Wait return validatedBid , mkPlay = \pid gs -> do setAction state PlayAction setGameState state gs string <- readChan rchannel let maybeCard = decode (pack string) :: Maybe Card card <- case maybeCard of Just x -> return x Nothing -> do writeChan wchannel (Failure "Parser error", gs) (mkPlay player) pid gs validatedCard <- case validateCard pid gs card of Nothing -> return card Just errorMessage -> do writeChan wchannel (Failure errorMessage, gs) (mkPlay player) pid gs writeChan wchannel (Success "Card accepted", gs) setAction state Wait return validatedCard , -- postBidHook :: (p, Int) -> Bid -> GameState -> IO () postBidHook = \pid Bid {amount=amount,bidSuit=suit,bidderIdx=bidderIdx} gs@(Game scores players rounds hand) -> do let bidMessage = case amount of 0 -> players !! bidderIdx ++ " passed" x -> players !! bidderIdx ++ " bid " ++ show x putMessage state bidMessage setGameState state gs , -- postPlayHook :: (p, Int) -> Play -> GameState -> [Card] -> IO () postPlayHook = \pid Play {card=card,playerIdx=playerIdx} gs@(Game scores players rounds hand) -> do let playMessage = players !! playerIdx ++ " played " ++ show card putMessage state playMessage setGameState state gs , acknowledgeTrump = \pid Bid {amount=amount,bidSuit=Just suit,bidderIdx=bidderIdx} _ -> putMessage state $ "Trump is " ++ show suit , name = name } mkNetworkPlayer :: StdGen -> String -> IO (Player, StdGen) mkNetworkPlayer g name = do (conf, g) <- mkNetworkConfig g let p = mkNetworkPlayerFromConfig conf name return (p, g)
benweitzman/Pitch
src/Pitch/Players/Network.hs
Haskell
mit
8,028
{-# LANGUAGE FlexibleInstances #-} module Model where import ClassyPrelude.Yesod import Database.Persist.Quasi import ModelTypes import Yesod.Auth.HashDB (HashDBUser(..)) -- You can define all of your database entities in the entities file. -- You can find more information on persistent and how to declare entities -- at: -- http://www.yesodweb.com/book/persistent/ share [mkPersist sqlSettings, mkMigrate "migrateAll"] $(persistFileWith lowerCaseSettings "config/models") instance HashDBUser User where userPasswordHash = userPassword setPasswordHash h p = p { userPassword = Just h }
ahushh/Monaba
monaba/src/Model.hs
Haskell
mit
603
-- Multiples of Ten in a Sequence Which Values Climb Up -- http://www.codewars.com/kata/561d54055e399e2f62000045/ module Codewars.Kata.ClimbUp where import Control.Arrow ((&&&)) findMult10SF :: Int -> Integer findMult10SF = uncurry (+) . ((*3) . (2^) &&& (*9) . (6^)) . (+ (-3)) . (*4)
gafiatulin/codewars
src/Beta/ClimbUp.hs
Haskell
mit
289
{- Model of explosion of buried curved charge. Proposed by L. M. Kotlyar in 1970's Makes possible the calculations of blast edges given set parameters. Explosion is modelled as potential flow of ideal liquid. Encoded by Saphronov Mark a. k. a. hijarian 2011.09 Public Domain -} module Model.Functions ( dzdu, dzdu', coeffCalculationHelper ) where import Data.Complex import Data.Complex.Integrate -- We need theta-functions here, -- see http://mathworld.wolfram.com/JacobiThetaFunctions.html import Numeric.Functions.Theta -- We import the data type named "ModelParams" from there import Model.Params type AuxiliaryDomainComplexValue = Complex Double type OriginDomainComplexValue = Complex Double ----------------------------------------------------------------------- -- DZDU FUNCTIONS BEGIN ----------------------------------------------------------------------- -- dz/du -- That is, differential of the mapping from auxiliary domain U to origin domain Z dzdu :: ModelParams -> AuxiliaryDomainComplexValue -> OriginDomainComplexValue dzdu p u = dwdu p u * exp (chi p u) -- dz/du -- Provided here for testing and comparing purposes -- It's a mathematically simplified equivalent of original `dzdu` dzdu' :: ModelParams -> AuxiliaryDomainComplexValue -> OriginDomainComplexValue dzdu' p u = (dzdu_simple p u) * (exp $ f_corr p u) -- Calculates simplified version of the area. It needs correcting function f_corr dzdu_simple :: ModelParams -> Complex Double -> Complex Double dzdu_simple p u = nval' * eval' * divident' / divisor'' where nval' = (mfunc p) * ((toComplex.negate) $ (phi_0 p) / pi / (v_0 p)) eval' = exp ( 0 :+ ((1 - alpha p) * pi)) divident' = t1m4t p u * t1p4t p u * t2m4t p u * t2p4t p u divisor'' = (t1m4 p u * t4m4 p u) ** ((1 - alpha p) :+ 0) * (t1p4 p u * t4p4 p u) ** ((1 + alpha p) :+ 0) ----------------------------------------------------------------------- -- DZDU FUNCTIONS END ----------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Helper which will be passed to the method which renews coefficients -- It's a function which uses `chi` method, so, we cannot really use this helper -- right in the module which needs it. coeffCalculationHelper :: ModelParams -> Double -> Double coeffCalculationHelper param e = curvature param (t e) where t e = imagPart $ chi param (0 :+ e) -- Curvature. -- Parametrized by the length of the curve, so, has a single argument -- which is a point at the curve. -- Returns the curvature at this point -- TODO: Maybe should convert this function to Complex valued? curvature :: ModelParams -> Double -> Double curvature param x = ((1 - epssin) ** (3/2)) / p where epssin = (epsilon * (sin x)) ^ 2 -- Here we see with our own eyes that RAD_B MUST BE GREATER THAN RAD_A! epsilon = ( sqrt ( b'*b' - a'*a' ) ) / b' p = (a'*a') / (b'*b') a' = rad_a param b' = rad_b param -------------------------------------------------------------------------------- ----------------------------------------------------------------------- -- CORE FUNCTIONS BEGIN ----------------------------------------------------------------------- -- The mapping between points in auxillary -- domain `u` and source domain `z` is defined as: -- dzdu param u = ((dwdu param u)) * exp ( negate $ chi param u ) -- and `chi` is `chi_0 - f_corr` -- So, we need to provide functions dwdu, chi_0 and f_corr -- Derivative of the complex potential dwdu dwdu :: ModelParams -> Complex Double -> Complex Double dwdu p u = npar * (mfunc p) * divident / divisor where npar = toComplex.negate $ phi_0' / pi divident = (t1m4t p u) * (t1p4t p u) * (t2m4t p u) * (t2p4t p u) divisor = (t1m4 p u) * (t1p4 p u) * (t4m4 p u) * (t4p4 p u) phi_0' = phi_0 p -- Small helper for dwdu function mfunc :: ModelParams -> Complex Double mfunc param = (* 2) . (** 2) . (/ divisor) $ divident where divisor = (t2z param) * (t3z param) * (t4z param) divident = (** 2) . abs $ t14p4t param -- Zhukovsky function chi chi :: ModelParams -> Complex Double -> Complex Double chi param u = (chi_0 param u) - (f_corr param u) -- Zhukovsky function chi_0 for simplified problem chi_0 :: ModelParams -> Complex Double -> Complex Double chi_0 p u = (+ cpar).(* (toComplex g)).log $ divident / divisor where cpar = toImaginary $ (pi * (g - 1)) g = alpha p divident = (t1p4 p u) * (t4p4 p u) divisor = (t1m4 p u) * (t4m4 p u) -- Correcting function f(u) -- For it to work, in the ModelParams object there should be already calculated values -- of the coefficients `cN` in field `cn` f_corr :: ModelParams -> Complex Double -> Complex Double f_corr p u = const_part + (foldl (+) c0 (f_arg u clist)) where const_part = ((4 * (1 - (gamma/2)) * negate(1/tau') ) :+ 0) * u gamma = alpha p c0 = 0 :+ 0 -- :) f_arg u clist = map (\ (n, cn) -> ((cn * (1 - rho n)) :+ 0) * exp' n) clist clist = zip [1..(n_cn p)] (c_n p) exp' n = exp $ (4 * u - pi * (fromInteger n)) / (tau' :+ 0) rho n = exp $ (negate (2 * pi * fromInteger n)) / tau' tau' = tau p ----------------------------------------------------------------------- -- CORE FUNCTIONS END ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- HELPER FUNCTIONS BEGIN ----------------------------------------------------------------------- -- Semantically converting to complex toComplex :: (RealFloat a) => a -> Complex a toComplex = (:+ 0) -- Semantically converting to pure imaginary number -- Equals to multiplying the real number by i toImaginary :: (RealFloat a) => a -> Complex a toImaginary = ((:+) 0) -- We will use theta-functions with parameters from object -- typed ModelParams, so let's write a helper so we will be able -- to write just thetaN' <p> <u> theta1' param = theta1 (n_theta param) (qpar (tau param)) theta2' param = theta2 (n_theta param) (qpar (tau param)) theta3' param = theta3 (n_theta param) (qpar (tau param)) theta4' param = theta4 (n_theta param) (qpar (tau param)) --pi4 :: (RealFloat a) => a pi4 = pi / 4 --pi4t :: ModelParams -> Complex Double pi4t p = toImaginary . (* pi4) $ (tau p) -- This is a set of helper functions to quickly calculate -- some often encountered theta function invocations t1m4t, t1p4t, t1m4, t1p4 :: ModelParams -> Complex Double -> Complex Double t1m4t p u = theta1' p (u - ( pi4t p )) t1p4t p u = theta1' p (u + ( pi4t p )) t1m4 p u = theta1' p (u - (toComplex pi4)) t1p4 p u = theta1' p (u + (toComplex pi4)) t1z :: ModelParams -> Complex Double t1z p = theta1' p (0 :+ 0) t14p4t :: ModelParams -> Complex Double t14p4t p = theta1' p ((toComplex pi4) + ( pi4t p )) t2m4t, t2p4t, t2m4, t2p4 :: ModelParams -> Complex Double -> Complex Double t2m4t p u = theta2' p (u - ( pi4t p )) t2p4t p u = theta2' p (u + ( pi4t p )) t2m4 p u = theta2' p (u - (toComplex pi4)) t2p4 p u = theta2' p (u + (toComplex pi4)) t2z :: ModelParams -> Complex Double t2z p = theta2' p (0 :+ 0) t3m4t, t3p4t, t3m4, t3p4 :: ModelParams -> Complex Double -> Complex Double t3m4t p u = theta3' p (u - ( pi4t p )) t3p4t p u = theta3' p (u + ( pi4t p )) t3m4 p u = theta3' p (u - (toComplex pi4)) t3p4 p u = theta3' p (u + (toComplex pi4)) t3z :: ModelParams -> Complex Double t3z p = theta3' p (0 :+ 0) t4m4t, t4p4t, t4m4, t4p4 :: ModelParams -> Complex Double -> Complex Double t4m4t p u = theta4' p (u - ( pi4t p )) t4p4t p u = theta4' p (u + ( pi4t p )) t4m4 p u = theta4' p (u - (toComplex pi4)) t4p4 p u = theta4' p (u + (toComplex pi4)) t4z :: ModelParams -> Complex Double t4z p = theta4' p (0 :+ 0) ----------------------------------------------------------------------- -- HELPER FUNCTIONS END -----------------------------------------------------------------------
hijarian/AFCALC
program/src/Model/Functions.hs
Haskell
cc0-1.0
8,074
{-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE MultiParamTypeClasses #-} -- The generic implementation for the protocol that converts to -- and from SQL cells. -- Going through JSON is not recommended because of precision loss -- for the numbers, and other issues related to numbers. module Spark.Core.Internal.RowGenerics( ToSQL, valueToCell, ) where import GHC.Generics import qualified Data.Vector as V import Data.Text(pack, Text) import Spark.Core.Internal.RowStructures import Spark.Core.Internal.Utilities -- We need to differentiate between the list built for the -- constructor and an inner object. data CurrentBuffer = ConsData ![Cell] | BuiltCell !Cell deriving (Show) _cellOrError :: CurrentBuffer -> Cell _cellOrError (BuiltCell cell) = cell _cellOrError x = let msg = "Expected built cell, received " ++ show x in failure (pack msg) -- All the types that can be converted to a SQL value. class ToSQL a where _valueToCell :: a -> Cell default _valueToCell :: (Generic a, GToSQL (Rep a)) => a -> Cell _valueToCell !x = _g2cell (from x) valueToCell :: (ToSQL a) => a -> Cell valueToCell = _valueToCell -- class FromSQL a where -- _cellToValue :: Cell -> Try a instance ToSQL a => ToSQL (Maybe a) where _valueToCell (Just x) = _valueToCell x _valueToCell Nothing = Empty instance (ToSQL a, ToSQL b) => ToSQL (a, b) where _valueToCell (x, y) = RowArray (V.fromList [valueToCell x, valueToCell y]) instance ToSQL Int where _valueToCell = IntElement instance ToSQL Double where _valueToCell = DoubleElement instance ToSQL Text where _valueToCell = StringElement class GToSQL r where _g2buffer :: r a -> CurrentBuffer _g2cell :: r a -> Cell _g2cell = _cellOrError . _g2buffer instance GToSQL U1 where _g2buffer U1 = failure $ pack "GToSQL UI called" -- | Constants, additional parameters and recursion of kind * instance (GToSQL a, GToSQL b) => GToSQL (a :*: b) where _g2buffer (a :*: b) = case (_g2buffer a, _g2buffer b) of (ConsData l1, ConsData l2) -> ConsData (l1 ++ l2) (y1, y2) -> failure $ pack $ "GToSQL (a :*: b): Expected buffers, received " ++ show y1 ++ " and " ++ show y2 instance (GToSQL a, GToSQL b) => GToSQL (a :+: b) where _g2buffer (L1 x) = _g2buffer x _g2buffer (R1 x) = let !y = _g2buffer x in y -- -- | Sums: encode choice between constructors -- instance (GToSQL a) => GToSQL (M1 i c a) where -- _g2cell !(M1 x) = let !y = _g2cell x in -- trace ("GToSQL M1: y = " ++ show y) y instance (GToSQL a) => GToSQL (M1 C c a) where _g2buffer (M1 x) = let !y = _g2buffer x in y instance (GToSQL a) => GToSQL (M1 S c a) where _g2buffer (M1 x) = let !y = ConsData [_g2cell x] in y instance (GToSQL a) => GToSQL (M1 D c a) where _g2buffer (M1 x) = case _g2buffer x of ConsData cs -> BuiltCell $ RowArray (V.fromList cs) BuiltCell cell -> BuiltCell cell -- | Products: encode multiple arguments to constructors instance (ToSQL a) => GToSQL (K1 i a) where _g2buffer (K1 x) = let !y = _valueToCell x in BuiltCell y
krapsh/kraps-haskell
src/Spark/Core/Internal/RowGenerics.hs
Haskell
apache-2.0
3,263
{-# LANGUAGE TypeFamilies, OverloadedLists, FlexibleInstances, FunctionalDependencies, ViewPatterns, MultiParamTypeClasses, UnicodeSyntax, GeneralizedNewtypeDeriving #-} module Fuzzy.Bool where import Prelude.Unicode import Control.Applicative import Data.Monoid import GHC.Exts class Adjunct f u | f → u where forget ∷ f → u construct ∷ u → f newtype PolygonicNumber = Poly { unPoly ∷ [Double] } instance Show PolygonicNumber where show (forget → [a,b,c]) = "Poly $ " <> show a <> " ← " <> show b <> " → " <> show c instance Adjunct PolygonicNumber [Double] where forget (Poly xs) = xs construct = Poly instance IsList PolygonicNumber where type Item PolygonicNumber = Double fromList = Poly toList (Poly xs) = xs instance Eq PolygonicNumber where (==) (forget → [al,bl,cl]) (forget → [ar, br, cr]) | ar ≡ al ∧ br ≡ ar ∧ cr ≡ cl = True | otherwise = False instance Ord PolygonicNumber where (<=) (forget → [al, bl, cl]) (forget → [ar, br, cr]) | bl ≡ br ∧ cl ≤ cr ∧ al ≤ ar = True | otherwise = False class PolyNumbers β where μ ∷ β → Double → Double spreadleft ∷ β → Double spreadright :: β → Double instance PolyNumbers PolygonicNumber where μ β@(forget → [a,b,c]) x | a ≤ x ∧ x ≤ b = (x - a) / spreadleft β | b ≤ x ∧ x ≤ c = (c - x) / spreadright β | otherwise = 0 spreadleft (forget → [a,b,c]) = b - a spreadright (forget → [a,b,c]) = c - b instance Fractional PolygonicNumber where fromRational a = Poly $ let b = fromRational a in [b,b,b] (/) (forget → xs) (forget → ys) = construct $ zipWith (/) xs ys member ∷ PolyNumbers a ⇒ a → Double → Double member = μ -- | These types of fuzzy logics are all monoidal in nature class FuzzyLogic α where -- | Laws -- -- for τ-norm ∷ α → α → α -- with tunit ∷ α -- α ⊕ β = β ⊕ α -- α ⊕ β ≤ γ ⊕ δ if α ≤ γ and β ≤ δ -- α ⊕ (β ⊕ γ) = (α ⊕ β) ⊕ γ -- tunit ⊕ α = α -- α ⊕ tunit = α tnorm :: α -> α -> α tunit ∷ α -- | Forget the algebraic structure instance Num PolygonicNumber where -- Creates a spike with exactly spread 0 fromInteger x = construct $ fromInteger <$> [x,x,x] (forget → xs) + (forget → ys) = construct $ zipWith (+) xs ys (forget → xs) * (forget → ys) = construct $ zipWith (*) xs ys abs (forget → xs) = construct $ abs <$> xs negate (forget → xs) = construct $ reverse $ negate <$> xs signum (forget → xs) = construct $ signum <$> xs fib ∷ (Eq a, Fractional a, Num a) ⇒ a → a fib a | a ≡ 0 = 0 fib n = fib (n - 1) + fib (n - 2)
edgarklerks/document-indexer
Fuzzy/Bool.hs
Haskell
bsd-2-clause
2,977
{-# LANGUAGE RankNTypes #-} module Graphics.GL.Low.Framebuffer ( -- | By default, rendering commands output graphics to the default framebuffer. -- This includes the color buffer, the depth buffer, and the stencil buffer. It -- is possible to render to a texture instead. This is important for many -- techniques. Rendering to a texture (either color, depth, or depth/stencil) -- is accomplished by using a framebuffer object (FBO). -- -- The following ritual sets up an FBO with a blank 256x256 color texture for -- off-screen rendering: -- -- @ -- do -- fbo <- newFBO -- tex <- newEmptyTexture2D 256 256 :: IO (Tex2D RGB) -- bindFramebuffer fbo -- attachTex2D tex -- bindFramebuffer DefaultFramebuffer -- return (fbo, tex) -- @ -- -- After binding an FBO to the framebuffer binding target, rendering commands -- will output to its color attachment and possible depth/stencil attachment -- if present. An FBO must have a color attachment before rendering. If only -- the depth results are needed, then you can attach a color RBO instead of -- a texture to the color attachment point. newFBO, bindFramebuffer, deleteFBO, attachTex2D, attachCubeMap, attachRBO, newRBO, deleteRBO, FBO, DefaultFramebuffer(..), RBO -- * Example -- $example ) where import Foreign.Ptr import Foreign.Marshal import Foreign.Storable import Control.Monad.IO.Class import Data.Default import Graphics.GL import Graphics.GL.Low.Internal.Types import Graphics.GL.Low.Classes import Graphics.GL.Low.Common import Graphics.GL.Low.Cube import Graphics.GL.Low.Texture -- | The default framebuffer. data DefaultFramebuffer = DefaultFramebuffer deriving Show instance Default DefaultFramebuffer where def = DefaultFramebuffer instance Framebuffer DefaultFramebuffer where framebufferName _ = 0 -- | Binds an FBO or the default framebuffer to the framebuffer binding target. -- Replaces the framebuffer already bound there. bindFramebuffer :: (MonadIO m, Framebuffer a) => a -> m () bindFramebuffer x = glBindFramebuffer GL_FRAMEBUFFER (framebufferName x) -- | Create a new framebuffer object. Before the framebuffer can be used for -- rendering it must have a color image attachment. newFBO :: (MonadIO m) => m FBO newFBO = liftIO . fmap FBO $ alloca (\ptr -> glGenFramebuffers 1 ptr >> peek ptr) -- | Delete an FBO. deleteFBO :: (MonadIO m) => FBO -> m () deleteFBO (FBO n) = liftIO $ withArray [n] (\ptr -> glDeleteFramebuffers 1 ptr) -- | Attach a 2D texture to the FBO currently bound to the -- framebuffer binding target. attachTex2D :: (MonadIO m, Attachable a) => Tex2D a -> m () attachTex2D tex = glFramebufferTexture2D GL_FRAMEBUFFER (attachPoint tex) GL_TEXTURE_2D (glObjectName tex) 0 -- | Attach one of the sides of a cubemap texture to the FBO currently bound -- to the framebuffer binding target. attachCubeMap :: (MonadIO m, Attachable a) => CubeMap a -> Side -> m () attachCubeMap cm side = glFramebufferTexture2D GL_FRAMEBUFFER (attachPoint cm) (side cubeSideCodes) (glObjectName cm) 0 -- | Attach an RBO to the FBO currently bound to the framebuffer binding -- target. attachRBO :: (MonadIO m, Attachable a) => RBO a -> m () attachRBO rbo = glFramebufferRenderbuffer GL_FRAMEBUFFER (attachPoint rbo) GL_RENDERBUFFER (unRBO rbo) -- | Create a new renderbuffer with the specified dimensions. newRBO :: (MonadIO m, InternalFormat a) => Int -> Int -> m (RBO a) newRBO w h = do n <- liftIO $ alloca (\ptr -> glGenRenderbuffers 1 ptr >> peek ptr) rbo <- return (RBO n) glBindRenderbuffer GL_RENDERBUFFER n glRenderbufferStorage GL_RENDERBUFFER (internalFormat rbo) (fromIntegral w) (fromIntegral h) return rbo -- | Delete an RBO. deleteRBO :: (MonadIO m) => RBO a -> m () deleteRBO (RBO n) = liftIO $ withArray [n] (\ptr -> glDeleteRenderbuffers 1 ptr) -- $example -- -- <<framebuffer.gif Animated screenshot showing post-processing effect>> -- -- This example program renders an animating object to an off-screen -- framebuffer. The resulting texture is then shown on a full-screen quad -- with an effect. -- -- @ -- module Main where -- -- import Control.Monad.Loops (whileM_) -- import Data.Functor ((\<$\>)) -- import qualified Data.Vector.Storable as V -- import Data.Maybe (fromJust) -- import Data.Default -- import Data.Word -- -- import qualified Graphics.UI.GLFW as GLFW -- import Linear -- import Graphics.GL.Low -- -- main = do -- GLFW.init -- GLFW.windowHint (GLFW.WindowHint'ContextVersionMajor 3) -- GLFW.windowHint (GLFW.WindowHint'ContextVersionMinor 2) -- GLFW.windowHint (GLFW.WindowHint'OpenGLForwardCompat True) -- GLFW.windowHint (GLFW.WindowHint'OpenGLProfile GLFW.OpenGLProfile'Core) -- mwin <- GLFW.createWindow 640 480 \"Framebuffer\" Nothing Nothing -- case mwin of -- Nothing -> putStrLn "createWindow failed" -- Just win -> do -- GLFW.makeContextCurrent (Just win) -- GLFW.swapInterval 1 -- (vao1, vao2, prog1, prog2, fbo, texture) <- setup -- whileM_ (not <$> GLFW.windowShouldClose win) $ do -- GLFW.pollEvents -- t <- (realToFrac . fromJust) \<$\> GLFW.getTime -- draw vao1 vao2 prog1 prog2 fbo texture t -- GLFW.swapBuffers win -- -- setup = do -- -- primary subject -- vao1 <- newVAO -- bindVAO vao1 -- let blob = V.fromList -- [ -0.5, -0.5, 0, 0 -- , 0, 0.5, 0, 1 -- , 0.5, -0.5, 1, 1] :: V.Vector Float -- vbo <- newVBO blob StaticDraw -- bindVBO vbo -- vsource <- readFile "framebuffer.vert" -- fsource1 <- readFile "framebuffer1.frag" -- prog1 <- newProgram vsource fsource1 -- useProgram prog1 -- setVertexLayout -- [ Attrib "position" 2 GLFloat -- , Attrib "texcoord" 2 GLFloat ] -- -- -- full-screen quad to show the post-processed scene -- vao2 <- newVAO -- bindVAO vao2 -- let blob = V.fromList -- [ -1, -1, 0, 0 -- , -1, 1, 0, 1 -- , 1, -1, 1, 0 -- , 1, 1, 1, 1] :: V.Vector Float -- vbo <- newVBO blob StaticDraw -- bindVBO vbo -- indices <- newElementArray (V.fromList [0,1,2,3,2,1] :: V.Vector Word8) StaticDraw -- bindElementArray indices -- fsource2 <- readFile "framebuffer2.frag" -- prog2 <- newProgram vsource fsource2 -- useProgram prog2 -- setVertexLayout -- [ Attrib "position" 2 GLFloat -- , Attrib "texcoord" 2 GLFloat ] -- -- -- create an FBO to render the primary scene on -- fbo <- newFBO -- bindFramebuffer fbo -- texture <- newEmptyTexture2D 640 480 :: IO (Tex2D RGB) -- bindTexture2D texture -- setTex2DFiltering Linear -- attachTex2D texture -- return (vao1, vao2, prog1, prog2, fbo, texture) -- -- draw :: VAO -> VAO -> Program -> Program -> FBO -> Tex2D RGB -> Float -> IO () -- draw vao1 vao2 prog1 prog2 fbo texture t = do -- -- render primary scene to fbo -- bindVAO vao1 -- bindFramebuffer fbo -- useProgram prog1 -- clearColorBuffer (0,0,0) -- setUniform1f "time" [t] -- drawTriangles 3 -- -- -- render results to quad on main screen -- bindVAO vao2 -- bindFramebuffer DefaultFramebuffer -- useProgram prog2 -- bindTexture2D texture -- clearColorBuffer (0,0,0) -- setUniform1f "time" [t] -- drawIndexedTriangles 6 UByteIndices -- @ -- -- The vertex shader for this program is -- -- @ -- #version 150 -- in vec2 position; -- in vec2 texcoord; -- out vec2 Texcoord; -- void main() -- { -- gl_Position = vec4(position, 0.0, 1.0); -- Texcoord = texcoord; -- } -- @ -- -- The two fragment shaders, one for the object, one for the effect, are -- -- @ -- #version 150 -- uniform float time; -- in vec2 Texcoord; -- out vec4 outColor; -- void main() -- { -- float t = time; -- outColor = vec4( -- fract(Texcoord.x*5) < 0.5 ? sin(t*0.145) : cos(t*0.567), -- fract(Texcoord.y*5) < 0.5 ? cos(t*0.534) : sin(t*0.321), -- 0.0, 1.0 -- ); -- } -- @ -- -- @ -- #version 150 -- uniform float time; -- uniform sampler2D tex; -- in vec2 Texcoord; -- out vec4 outColor; -- -- void main() -- { -- float d = pow(10,(abs(cos(time))+1.5)); -- outColor c = texture(tex, floor(Texcoord*d)/d); -- } -- @
sgraf812/lowgl
Graphics/GL/Low/Framebuffer.hs
Haskell
bsd-2-clause
8,157
module Data.CRF.Chain2.Tiers.DP ( table , flexible2 , flexible3 ) where import qualified Data.Array as A import Data.Array ((!)) import Data.Ix (range) table :: A.Ix i => (i, i) -> ((i -> e) -> i -> e) -> A.Array i e table bounds f = table' where table' = A.listArray bounds $ map (f (table' !)) $ range bounds down1 :: A.Ix i => (i, i) -> (i -> e) -> i -> e down1 bounds f = (!) down' where down' = A.listArray bounds $ map f $ range bounds down2 :: (A.Ix i, A.Ix j) => (j, j) -> (j -> (i, i)) -> (j -> i -> e) -> j -> i -> e down2 bounds1 bounds2 f = (!) down' where down' = A.listArray bounds1 [ down1 (bounds2 i) (f i) | i <- range bounds1 ] flexible2 :: (A.Ix i, A.Ix j) => (j, j) -> (j -> (i, i)) -> ((j -> i -> e) -> j -> i -> e) -> j -> i -> e flexible2 bounds1 bounds2 f = (!) flex where flex = A.listArray bounds1 [ down1 (bounds2 i) (f (flex !) i) | i <- range bounds1 ] flexible3 :: (A.Ix j, A.Ix i, A.Ix k) => (k, k) -> (k -> (j, j)) -> (k -> j -> (i, i)) -> ((k -> j -> i -> e) -> k -> j -> i -> e) -> k -> j -> i -> e flexible3 bounds1 bounds2 bounds3 f = (!) flex where flex = A.listArray bounds1 [ down2 (bounds2 i) (bounds3 i) (f (flex !) i) | i <- range bounds1 ]
kawu/crf-chain2-tiers
src/Data/CRF/Chain2/Tiers/DP.hs
Haskell
bsd-2-clause
1,339
{-| Module : Database.Relational.FieldType Description : Definition of FieldType and friends. Copyright : (c) Alexander Vieth, 2015 Licence : BSD3 Maintainer : aovieth@gmail.com Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE AutoDeriveTypeable #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeOperators #-} module Database.Relational.FieldType ( WriteOrRead(..) , FieldType , FieldTypes , FieldTypeWrite , FieldTypeRead ) where import GHC.TypeLits (Symbol) import Database.Relational.Schema import Database.Relational.Column import Database.Relational.Default data WriteOrRead where WRITE :: WriteOrRead READ :: WriteOrRead -- | The *field type* is distinct from the *column* type, and they coincide -- precisely when that column cannot be null. Thus, the field type depends -- upon the column *and* the schema in which it lives. -- We have two notions of *field type*: write field type, and read field -- type. The former is the type which must be given when writing data to -- this field, and the latter is the type which will be obtained when -- reading. They differ when the relevant column has a default, in which case -- Default may be given. type family FieldType (wor :: WriteOrRead) schema (column :: (Symbol, *)) :: * where FieldType READ schema column = FieldTypeRead column (IsNullable column schema) FieldType WRITE schema column = FieldTypeWrite column (IsNullable column schema) (IsDefault column schema) type family FieldTypes (wor :: WriteOrRead) schema (columns :: [(Symbol, *)]) :: [*] where FieldTypes wor schema '[] = '[] FieldTypes wor schema (c ': cs) = FieldType wor schema c ': FieldTypes wor schema cs type family FieldTypeRead (column :: (Symbol, *)) isNullable :: * where FieldTypeRead column True = Maybe (ColumnType column) FieldTypeRead column False = ColumnType column type family FieldTypeWrite (column :: (Symbol, *)) isNullable isDefault :: * where FieldTypeWrite column nullable True = Default (FieldTypeRead column nullable) FieldTypeWrite column nullable False = FieldTypeRead column nullable
avieth/Relational
Database/Relational/FieldType.hs
Haskell
bsd-3-clause
2,284
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE TemplateHaskell #-} -- | This module contains operations related to symbolic stack. module Toy.X86.SymStack ( regSymStack , atSymStack , SymStackSpace , SymStackHolder , runSymStackHolder , symStackSize , allocSymStackOp , popSymStackOp , peekSymStackOp , occupiedRegs , accountHardMem ) where import Control.Lens (ix, makeLenses, (%=), (<-=), (<<+=)) import Control.Monad.Fix import Control.Monad.State (StateT, runStateT) import Control.Monad.Writer (MonadWriter) import Data.Default (Default (..)) import qualified Data.Vector as V import Universum import Toy.X86.Data (Operand (..)) regSymStack :: V.Vector Operand regSymStack = Reg <$> ["ecx", "ebx", "esi", "edi"] atSymStack :: Int -> Operand atSymStack k = case regSymStack ^? ix k of Just x -> x Nothing -> Stack (k - V.length regSymStack) data SymStackState = SymStackState { _symSize :: Int , _symMaxSize :: Int } makeLenses ''SymStackState instance Default SymStackState where def = SymStackState 0 0 newtype SymStackHolder m a = SymStackHolder (StateT SymStackState m a) deriving (Functor, Applicative, Monad, MonadWriter __, MonadFix) -- | How much space sym stack requires on real stack. newtype SymStackSpace = SymStackSpace Int deriving (Show, Eq, Ord, Enum, Num, Real, Integral) runSymStackHolder :: Monad m => SymStackHolder m a -> m ((SymStackSpace, Int), a) runSymStackHolder (SymStackHolder a) = do (res, SymStackState k totalSize) <- runStateT a def let space = max 0 $ totalSize - V.length regSymStack return ((SymStackSpace space, k), res) updateSymMaxSize :: Monad m => Int -> SymStackHolder m () updateSymMaxSize k = SymStackHolder $ symMaxSize %= max k symStackSize :: Monad m => SymStackHolder m Int symStackSize = SymStackHolder $ use symSize allocSymStackOp :: Monad m => SymStackHolder m Operand allocSymStackOp = do pos <- SymStackHolder $ symSize <<+= 1 updateSymMaxSize (pos + 1) return $ atSymStack pos popSymStackOp :: Monad m => SymStackHolder m Operand popSymStackOp = SymStackHolder $ (symSize <-= 1) <&> atSymStack peekSymStackOp :: Monad m => SymStackHolder m Operand peekSymStackOp = SymStackHolder $ use symSize <&> atSymStack . pred occupiedRegs :: Monad m => SymStackHolder m [Operand] occupiedRegs = symStackSize <&> flip take (V.toList regSymStack) -- | @HardMem@s occupy same space as sym stack accountHardMem :: Monad m => Int -> SymStackHolder m () accountHardMem = updateSymMaxSize . (+ V.length regSymStack) -- TODO: dirty hack
Martoon-00/toy-compiler
src/Toy/X86/SymStack.hs
Haskell
bsd-3-clause
2,788
{-# LANGUAGE TemplateHaskell #-} module Test.ScopeLookup where import Language.Haskell.TH import NotCPP.ScopeLookup scopeLookupTest = $(do Just t <- scopeLookup' "True" return t)
bmillwood/notcpp
Test/ScopeLookup.hs
Haskell
bsd-3-clause
186
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Distributed.Process.Registry -- Copyright : (c) Tim Watson 2012 - 2013 -- License : BSD3 (see the file LICENSE) -- -- Maintainer : Tim Watson <watson.timothy@gmail.com> -- Stability : experimental -- Portability : non-portable (requires concurrency) -- -- The module provides an extended process registry, offering slightly altered -- semantics to the built in @register@ and @unregister@ primitives and a richer -- set of features: -- -- * Associate (unique) keys with a process /or/ (unique key per-process) values -- * Use any 'Keyable' algebraic data type as keys -- * Query for process with matching keys / values / properties -- * Atomically /give away/ names -- * Forceibly re-allocate names to/from a third party -- -- [Subscribing To Registry Events] -- -- It is possible to monitor a registry for changes and be informed whenever -- changes take place. All subscriptions are /key based/, which means that -- you can subscribe to name or property changes for any process, so that any -- property changes matching the key you've subscribed to will trigger a -- notification (i.e., regardless of the process to which the property belongs). -- -- The different types of event are defined by the 'KeyUpdateEvent' type. -- -- Processes subscribe to registry events using @monitorName@ or its counterpart -- @monitorProperty@. If the operation succeeds, this will evaluate to an -- opaque /reference/ that can be used when subsequently handling incoming -- notifications, which will be delivered to the subscriber's mailbox as -- @RegistryKeyMonitorNotification keyIdentity opaqueRef event@, where @event@ -- has the type 'KeyUpdateEvent'. -- -- Subscribers can filter the types of event they receive by using the lower -- level @monitor@ function (defined in /this/ module - not the one defined -- in distributed-process' @Primitives@) and passing a list of filtering -- 'KeyUpdateEventMask'. Without these filters in place, a monitor event will -- be fired for /every/ pertinent change. -- ----------------------------------------------------------------------------- module Control.Distributed.Process.Registry ( -- * Registry Keys KeyType(..) , Key(..) , Keyable -- * Defining / Starting A Registry , Registry(..) , start , run -- * Registration / Unregistration , addName , addProperty , registerName , registerValue , giveAwayName , RegisterKeyReply(..) , unregisterName , UnregisterKeyReply(..) -- * Queries / Lookups , lookupName , lookupProperty , registeredNames , foldNames , SearchHandle() , member , queryNames , findByProperty , findByPropertyValue -- * Monitoring / Waiting , monitor , monitorName , monitorProp , unmonitor , await , awaitTimeout , AwaitResult(..) , KeyUpdateEventMask(..) , KeyUpdateEvent(..) , RegKeyMonitorRef , RegistryKeyMonitorNotification(RegistryKeyMonitorNotification) ) where {- DESIGN NOTES This registry is a single process, parameterised by the types of key and property value it can manage. It is, of course, possible to start multiple registries and inter-connect them via registration, with one another. The /Service/ API is intended to be a declarative layer in which you define the managed processes that make up your services, and each /Service Component/ is registered and supervised appropriately for you, with the correct restart strategies and start order calculated and so on. The registry is not only a service locator, but provides the /wait for these dependencies to start first/ bit of the puzzle. At some point, we'd like to offer a shared memory based registry, created on behalf of a particular subsystem (i.e., some service or service group) and passed implicitly using a reader monad or some such. This would allow multiple processes to interact with the registry using STM (or perhaps a simple RWLock) and could facilitate reduced contention. Even for the singleton-process based registry (i.e., this one) we /might/ also be better off separating the monitoring (or at least the notifications) from the registration/mapping parts into separate processes. -} import Control.Distributed.Process hiding (call, monitor, unmonitor, mask) import qualified Control.Distributed.Process.UnsafePrimitives as Unsafe (send) import qualified Control.Distributed.Process as P (monitor) import Control.Distributed.Process.Serializable import Control.Distributed.Process.Extras hiding (monitor, wrapMessage) import qualified Control.Distributed.Process.Extras as PL ( monitor ) import Control.Distributed.Process.ManagedProcess ( call , cast , handleInfo , reply , continue , input , defaultProcess , prioritised , InitResult(..) , ProcessAction , ProcessReply , ProcessDefinition(..) , PrioritisedProcessDefinition(..) , DispatchPriority , CallRef ) import qualified Control.Distributed.Process.ManagedProcess as MP ( pserve ) import Control.Distributed.Process.ManagedProcess.Server ( handleCallIf , handleCallFrom , handleCallFromIf , handleCast ) import Control.Distributed.Process.ManagedProcess.Server.Priority ( prioritiseInfo_ , setPriority ) import Control.Distributed.Process.ManagedProcess.Server.Restricted ( RestrictedProcess , Result , getState ) import qualified Control.Distributed.Process.ManagedProcess.Server.Restricted as Restricted ( handleCall , reply ) import Control.Distributed.Process.Extras.Time import Control.Monad (forM_, void) import Data.Accessor ( Accessor , accessor , (^:) , (^=) , (^.) ) import Data.Binary import Data.Foldable (Foldable) import qualified Data.Foldable as Foldable import Data.Maybe (fromJust, isJust) import Data.Hashable import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as Map import Control.Distributed.Process.Extras.Internal.Containers.MultiMap (MultiMap) import qualified Control.Distributed.Process.Extras.Internal.Containers.MultiMap as MultiMap import Data.HashSet (HashSet) import qualified Data.HashSet as Set import Data.Typeable (Typeable) import GHC.Generics -------------------------------------------------------------------------------- -- Types -- -------------------------------------------------------------------------------- -- | Describes how a key will be used - for storing names or properties. data KeyType = KeyTypeAlias -- ^ the key will refer to a name (i.e., named process) | KeyTypeProperty -- ^ the key will refer to a (per-process) property deriving (Typeable, Generic, Show, Eq) instance Binary KeyType where instance Hashable KeyType where -- | A registered key. Keys can be mapped to names or (process-local) properties -- in the registry. The 'keyIdentity' holds the key's value (e.g., a string or -- similar simple data type, which must provide a 'Keyable' instance), whilst -- the 'keyType' and 'keyScope' describe the key's intended use and ownership. data Key a = Key { keyIdentity :: !a , keyType :: !KeyType , keyScope :: !(Maybe ProcessId) } deriving (Typeable, Generic, Show, Eq) instance (Serializable a) => Binary (Key a) where instance (Hashable a) => Hashable (Key a) where -- | The 'Keyable' class describes types that can be used as registry keys. -- The constraints ensure that the key can be stored and compared appropriately. class (Show a, Eq a, Hashable a, Serializable a) => Keyable a instance (Show a, Eq a, Hashable a, Serializable a) => Keyable a -- | A phantom type, used to parameterise registry startup -- with the required key and value types. data Registry k v = Registry { registryPid :: ProcessId } deriving (Typeable, Generic, Show, Eq) instance (Keyable k, Serializable v) => Binary (Registry k v) where instance Resolvable (Registry k v) where resolve = return . Just . registryPid instance Linkable (Registry k v) where linkTo = link . registryPid -- Internal/Private Request/Response Types data LookupKeyReq k = LookupKeyReq !(Key k) deriving (Typeable, Generic) instance (Serializable k) => Binary (LookupKeyReq k) where data LookupPropReq k = PropReq (Key k) deriving (Typeable, Generic) instance (Serializable k) => Binary (LookupPropReq k) where data LookupPropReply = PropFound !Message | PropNotFound deriving (Typeable, Generic) instance Binary LookupPropReply where data InvalidPropertyType = InvalidPropertyType deriving (Typeable, Generic, Show, Eq) instance Binary InvalidPropertyType where data RegNamesReq = RegNamesReq !ProcessId deriving (Typeable, Generic) instance Binary RegNamesReq where data UnregisterKeyReq k = UnregisterKeyReq !(Key k) deriving (Typeable, Generic) instance (Serializable k) => Binary (UnregisterKeyReq k) where -- | The result of an un-registration attempt. data UnregisterKeyReply = UnregisterOk -- ^ The given key was successfully unregistered | UnregisterInvalidKey -- ^ The given key was invalid and could not be unregistered | UnregisterKeyNotFound -- ^ The given key was not found (i.e., was not registered) deriving (Typeable, Generic, Eq, Show) instance Binary UnregisterKeyReply where -- Types used in (setting up and interacting with) key monitors -- | Used to describe a subset of monitoring events to listen for. data KeyUpdateEventMask = OnKeyRegistered -- ^ receive an event when a key is registered | OnKeyUnregistered -- ^ receive an event when a key is unregistered | OnKeyOwnershipChange -- ^ receive an event when a key's owner changes | OnKeyLeaseExpiry -- ^ receive an event when a key's lease expires deriving (Typeable, Generic, Eq, Show) instance Binary KeyUpdateEventMask where instance Hashable KeyUpdateEventMask where -- | An opaque reference used for matching monitoring events. See -- 'RegistryKeyMonitorNotification' for more details. newtype RegKeyMonitorRef = RegKeyMonitorRef { unRef :: (ProcessId, Integer) } deriving (Typeable, Generic, Eq, Show) instance Binary RegKeyMonitorRef where instance Hashable RegKeyMonitorRef where instance Resolvable RegKeyMonitorRef where resolve = return . Just . fst . unRef -- | Provides information about a key monitoring event. data KeyUpdateEvent = KeyRegistered { owner :: !ProcessId } | KeyUnregistered | KeyLeaseExpired | KeyOwnerDied { diedReason :: !DiedReason } | KeyOwnerChanged { previousOwner :: !ProcessId , newOwner :: !ProcessId } deriving (Typeable, Generic, Eq, Show) instance Binary KeyUpdateEvent where -- | This message is delivered to processes which are monioring a -- registry key. The opaque monitor reference will match (i.e., be equal -- to) the reference returned from the @monitor@ function, which the -- 'KeyUpdateEvent' describes the change that took place. data RegistryKeyMonitorNotification k = RegistryKeyMonitorNotification !k !RegKeyMonitorRef !KeyUpdateEvent !ProcessId deriving (Typeable, Generic) instance (Keyable k) => Binary (RegistryKeyMonitorNotification k) where deriving instance (Keyable k) => Eq (RegistryKeyMonitorNotification k) deriving instance (Keyable k) => Show (RegistryKeyMonitorNotification k) data RegisterKeyReq k = RegisterKeyReq !(Key k) deriving (Typeable, Generic) instance (Serializable k) => Binary (RegisterKeyReq k) where -- | The (return) value of an attempted registration. data RegisterKeyReply = RegisteredOk -- ^ The given key was registered successfully | AlreadyRegistered -- ^ The key was already registered deriving (Typeable, Generic, Eq, Show) instance Binary RegisterKeyReply where -- | A cast message used to atomically give a name/key away to another process. data GiveAwayName k = GiveAwayName !ProcessId !(Key k) deriving (Typeable, Generic) instance (Keyable k) => Binary (GiveAwayName k) where deriving instance (Keyable k) => Eq (GiveAwayName k) deriving instance (Keyable k) => Show (GiveAwayName k) data MonitorReq k = MonitorReq !(Key k) !(Maybe [KeyUpdateEventMask]) deriving (Typeable, Generic) instance (Keyable k) => Binary (MonitorReq k) where data UnmonitorReq = UnmonitorReq !RegKeyMonitorRef deriving (Typeable, Generic) instance Binary UnmonitorReq where -- | The result of an @await@ operation. data AwaitResult k = RegisteredName !ProcessId !k -- ^ The name was registered | ServerUnreachable !DiedReason -- ^ The server was unreachable (or died) | AwaitTimeout -- ^ The operation timed out deriving (Typeable, Generic, Eq, Show) instance (Keyable k) => Binary (AwaitResult k) where -- Server state -- On the server, a monitor reference consists of the actual -- RegKeyMonitorRef which we can 'sendTo' /and/ the which -- the client matches on, plus an optional list of event masks data KMRef = KMRef { ref :: !RegKeyMonitorRef , mask :: !(Maybe [KeyUpdateEventMask]) -- use Nothing to monitor every event } deriving (Typeable, Generic, Show) instance Hashable KMRef where -- instance Binary KMRef where instance Eq KMRef where (KMRef a _) == (KMRef b _) = a == b data State k v = State { _names :: !(HashMap k ProcessId) , _properties :: !(HashMap (ProcessId, k) v) , _monitors :: !(MultiMap k KMRef) , _registeredPids :: !(HashSet ProcessId) , _listeningPids :: !(HashSet ProcessId) , _monitorIdCount :: !Integer } deriving (Typeable, Generic) -- Types used in \direct/ queries -- TODO: enforce QueryDirect's usage over only local channels data QueryDirect = QueryDirectNames | QueryDirectProperties | QueryDirectValues deriving (Typeable, Generic) instance Binary QueryDirect where -- NB: SHashMap is basically a shim, allowing us to copy a -- pointer to our HashMap directly to the querying process' -- mailbox with no serialisation or even deepseq evaluation -- required. We disallow remote queries (i.e., from other nodes) -- and thus the Binary instance below is never used (though it's -- required by the type system) and will in fact generate errors if -- you attempt to use it at runtime. data SHashMap k v = SHashMap [(k, v)] (HashMap k v) deriving (Typeable, Generic) instance (Keyable k, Serializable v) => Binary (SHashMap k v) where put = error "AttemptedToUseBinaryShim" get = error "AttemptedToUseBinaryShim" {- a real instance could look something like this: put (SHashMap _ hmap) = put (toList hmap) get = do hm <- get :: Get [(k, v)] return $ SHashMap [] (fromList hm) -} newtype SearchHandle k v = RS { getRS :: HashMap k v } deriving (Typeable) instance (Keyable k) => Functor (SearchHandle k) where fmap f (RS m) = RS $ Map.map f m instance (Keyable k) => Foldable (SearchHandle k) where foldr f acc = Foldable.foldr f acc . getRS -- TODO: add Functor and Traversable instances -------------------------------------------------------------------------------- -- Starting / Running A Registry -- -------------------------------------------------------------------------------- start :: forall k v. (Keyable k, Serializable v) => Process (Registry k v) start = return . Registry =<< spawnLocal (run (undefined :: Registry k v)) run :: forall k v. (Keyable k, Serializable v) => Registry k v -> Process () run _ = MP.pserve () (const $ return $ InitOk initState Infinity) serverDefinition where initState = State { _names = Map.empty , _properties = Map.empty , _monitors = MultiMap.empty , _registeredPids = Set.empty , _listeningPids = Set.empty , _monitorIdCount = (1 :: Integer) } :: State k v -------------------------------------------------------------------------------- -- Client Facing API -- -------------------------------------------------------------------------------- -- -- | Sends a message to the process, or processes, corresponding to @key@. -- -- If Key belongs to a unique object (name or aggregated counter), this -- -- function will send a message to the corresponding process, or fail if there -- -- is no such process. If Key is for a non-unique object type (counter or -- -- property), Msg will be send to all processes that have such an object. -- -- -- dispatch svr ky msg = undefined -- -- TODO: do a local-lookup and then sendTo the target -- | Associate the calling process with the given (unique) key. addName :: forall k v. (Keyable k) => Registry k v -> k -> Process RegisterKeyReply addName s n = getSelfPid >>= registerName s n -- | Atomically transfer a (registered) name to another process. Has no effect -- if the name does is not registered to the calling process! -- giveAwayName :: forall k v . (Keyable k) => Registry k v -> k -> ProcessId -> Process () giveAwayName s n p = do us <- getSelfPid cast s $ GiveAwayName p $ Key n KeyTypeAlias (Just us) -- | Associate the given (non-unique) property with the current process. -- If the property already exists, it will be overwritten with the new value. addProperty :: (Keyable k, Serializable v) => Registry k v -> k -> v -> Process RegisterKeyReply addProperty s k v = do call s $ (RegisterKeyReq (Key k KeyTypeProperty $ Nothing), v) -- | Register the item at the given address. registerName :: forall k v . (Keyable k) => Registry k v -> k -> ProcessId -> Process RegisterKeyReply registerName s n p = do call s $ RegisterKeyReq (Key n KeyTypeAlias $ Just p) -- | Register an item at the given address and associate it with a value. -- If the property already exists, it will be overwritten with the new value. registerValue :: (Resolvable b, Keyable k, Serializable v) => Registry k v -> b -> k -> v -> Process RegisterKeyReply registerValue s t n v = do Just p <- resolve t call s $ (RegisterKeyReq (Key n KeyTypeProperty $ Just p), v) -- | Un-register a (unique) name for the calling process. unregisterName :: forall k v . (Keyable k) => Registry k v -> k -> Process UnregisterKeyReply unregisterName s n = do self <- getSelfPid call s $ UnregisterKeyReq (Key n KeyTypeAlias $ Just self) -- | Lookup the process identified by the supplied key. Evaluates to -- @Nothing@ if the key is not registered. lookupName :: forall k v . (Keyable k) => Registry k v -> k -> Process (Maybe ProcessId) lookupName s n = call s $ LookupKeyReq (Key n KeyTypeAlias Nothing) -- | Lookup the value of a named property for the calling process. Evaluates to -- @Nothing@ if the property (key) is not registered. If the assignment to a -- value of type @v@ does not correspond to the type of properties stored by -- the registry, the calling process will exit with the reason set to -- @InvalidPropertyType@. lookupProperty :: (Keyable k, Serializable v) => Registry k v -> k -> Process (Maybe v) lookupProperty s n = do us <- getSelfPid res <- call s $ PropReq (Key n KeyTypeProperty (Just us)) case res of PropNotFound -> return Nothing PropFound msg -> do val <- unwrapMessage msg if (isJust val) then return val else die InvalidPropertyType -- | Obtain a list of all registered keys. registeredNames :: forall k v . (Keyable k) => Registry k v -> ProcessId -> Process [k] registeredNames s p = call s $ RegNamesReq p -- | Monitor changes to the supplied name. -- monitorName :: forall k v. (Keyable k) => Registry k v -> k -> Process RegKeyMonitorRef monitorName svr name = do let key' = Key { keyIdentity = name , keyScope = Nothing , keyType = KeyTypeAlias } monitor svr key' Nothing -- | Monitor changes to the supplied (property) key. -- monitorProp :: forall k v. (Keyable k) => Registry k v -> k -> ProcessId -> Process RegKeyMonitorRef monitorProp svr key pid = do let key' = Key { keyIdentity = key , keyScope = Just pid , keyType = KeyTypeProperty } monitor svr key' Nothing -- | Low level monitor operation. For the given key, set up a monitor -- filtered by any 'KeyUpdateEventMask' entries that are supplied. monitor :: forall k v. (Keyable k) => Registry k v -> Key k -> Maybe [KeyUpdateEventMask] -> Process RegKeyMonitorRef monitor svr key' mask' = call svr $ MonitorReq key' mask' -- | Remove a previously set monitor. -- unmonitor :: forall k v. (Keyable k) => Registry k v -> RegKeyMonitorRef -> Process () unmonitor s = call s . UnmonitorReq -- | Await registration of a given key. This function will subsequently -- block the evaluating process until the key is registered and a registration -- event is dispatched to the caller's mailbox. -- await :: forall k v. (Keyable k) => Registry k v -> k -> Process (AwaitResult k) await a k = awaitTimeout a Infinity k -- | Await registration of a given key, but give up and return @AwaitTimeout@ -- if registration does not take place within the specified time period (@delay@). awaitTimeout :: forall k v. (Keyable k) => Registry k v -> Delay -> k -> Process (AwaitResult k) awaitTimeout a d k = do p <- forceResolve a Just mRef <- PL.monitor p kRef <- monitor a (Key k KeyTypeAlias Nothing) (Just [OnKeyRegistered]) let matches' = matches mRef kRef k let recv = case d of Infinity -> receiveWait matches' >>= return . Just Delay t -> receiveTimeout (asTimeout t) matches' NoDelay -> receiveTimeout 0 matches' recv >>= return . maybe AwaitTimeout id where forceResolve addr = do mPid <- resolve addr case mPid of Nothing -> die "InvalidAddressable" Just p -> return p matches mr kr k' = [ matchIf (\(RegistryKeyMonitorNotification mk' kRef' ev' _) -> (matchEv ev' && kRef' == kr && mk' == k')) (\(RegistryKeyMonitorNotification _ _ (KeyRegistered pid) _) -> return $ RegisteredName pid k') , matchIf (\(ProcessMonitorNotification mRef' _ _) -> mRef' == mr) (\(ProcessMonitorNotification _ _ dr) -> return $ ServerUnreachable dr) ] matchEv ev' = case ev' of KeyRegistered _ -> True _ -> False -- Local (non-serialised) shared data access. See note [sharing] below. findByProperty :: forall k v. (Keyable k) => Registry k v -> k -> Process [ProcessId] findByProperty r key = do let pid = registryPid r self <- getSelfPid withMonitor pid $ do cast r $ (self, QueryDirectProperties) answer <- receiveWait [ match (\(SHashMap _ m :: SHashMap ProcessId [k]) -> return $ Just m) , matchIf (\(ProcessMonitorNotification _ p _) -> p == pid) (\_ -> return Nothing) , matchAny (\_ -> return Nothing) ] case answer of Nothing -> die "DisconnectedFromServer" Just m -> return $ Map.foldlWithKey' matchKey [] m where matchKey ps p ks | key `elem` ks = p:ps | otherwise = ps findByPropertyValue :: (Keyable k, Serializable v, Eq v) => Registry k v -> k -> v -> Process [ProcessId] findByPropertyValue r key val = do let pid = registryPid r self <- getSelfPid withMonitor pid $ do cast r $ (self, QueryDirectValues) answer <- receiveWait [ match (\(SHashMap _ m :: SHashMap ProcessId [(k, v)]) -> return $ Just m) , matchIf (\(ProcessMonitorNotification _ p _) -> p == pid) (\_ -> return Nothing) , matchAny (\_ -> return Nothing) -- TODO: logging? ] case answer of Nothing -> die "DisconnectedFromServer" Just m -> return $ Map.foldlWithKey' matchKey [] m where matchKey ps p ks | (key, val) `elem` ks = p:ps | otherwise = ps -- TODO: move to UnsafePrimitives over a passed {Send|Receive}Port here, and -- avoid interfering with the caller's mailbox. -- | Monadic left fold over all registered names/keys. The fold takes place -- in the evaluating process. foldNames :: forall b k v . Keyable k => Registry k v -> b -> (b -> (k, ProcessId) -> Process b) -> Process b foldNames pid acc fn = do self <- getSelfPid -- TODO: monitor @pid@ and die if necessary!!! cast pid $ (self, QueryDirectNames) -- Although we incur the cost of scanning our mailbox here (which we could -- avoid by spawning an intermediary perhaps), the message is delivered to -- us without any copying or serialisation overheads. SHashMap _ m <- expect :: Process (SHashMap k ProcessId) Foldable.foldlM fn acc (Map.toList m) -- | Evaluate a query on a 'SearchHandle', in the calling process. queryNames :: forall b k v . Keyable k => Registry k v -> (SearchHandle k ProcessId -> Process b) -> Process b queryNames pid fn = do self <- getSelfPid cast pid $ (self, QueryDirectNames) SHashMap _ m <- expect :: Process (SHashMap k ProcessId) fn (RS m) -- | Tests whether or not the supplied key is registered, evaluated in the -- calling process. member :: (Keyable k, Serializable v) => k -> SearchHandle k v -> Bool member k = Map.member k . getRS -- note [sharing]: -- We use the base library's UnsafePrimitives for these fold/query operations, -- to pass a pointer to our internal HashMaps for read-only operations. There -- is a potential cost to the caller, if their mailbox is full - we should move -- to use unsafe channel's for this at some point. -- -------------------------------------------------------------------------------- -- Server Process -- -------------------------------------------------------------------------------- serverDefinition :: forall k v. (Keyable k, Serializable v) => PrioritisedProcessDefinition (State k v) serverDefinition = prioritised processDefinition regPriorities where regPriorities :: [DispatchPriority (State k v)] regPriorities = [ prioritiseInfo_ (\(ProcessMonitorNotification _ _ _) -> setPriority 100) ] processDefinition :: forall k v. (Keyable k, Serializable v) => ProcessDefinition (State k v) processDefinition = defaultProcess { apiHandlers = [ handleCallIf (input ((\(RegisterKeyReq (Key{..} :: Key k)) -> keyType == KeyTypeAlias && (isJust keyScope)))) handleRegisterName , handleCallIf (input ((\((RegisterKeyReq (Key{..} :: Key k)), _ :: v) -> keyType == KeyTypeProperty && (isJust keyScope)))) handleRegisterProperty , handleCallFromIf (input ((\((RegisterKeyReq (Key{..} :: Key k)), _ :: v) -> keyType == KeyTypeProperty && (not $ isJust keyScope)))) handleRegisterPropertyCR , handleCast handleGiveAwayName , handleCallIf (input ((\(LookupKeyReq (Key{..} :: Key k)) -> keyType == KeyTypeAlias))) (\state (LookupKeyReq key') -> reply (findName key' state) state) , handleCallIf (input ((\(PropReq (Key{..} :: Key k)) -> keyType == KeyTypeProperty && (isJust keyScope)))) handleLookupProperty , handleCallIf (input ((\(UnregisterKeyReq (Key{..} :: Key k)) -> keyType == KeyTypeAlias && (isJust keyScope)))) handleUnregisterName , handleCallFrom handleMonitorReq , handleCallFrom handleUnmonitorReq , Restricted.handleCall handleRegNamesLookup , handleCast handleQuery ] , infoHandlers = [handleInfo handleMonitorSignal] } :: ProcessDefinition (State k v) handleQuery :: forall k v. (Keyable k, Serializable v) => State k v -> (ProcessId, QueryDirect) -> Process (ProcessAction (State k v)) handleQuery st@State{..} (pid, qd) = do case qd of QueryDirectNames -> Unsafe.send pid shmNames QueryDirectProperties -> Unsafe.send pid shmProps QueryDirectValues -> Unsafe.send pid shmVals continue st where shmNames = SHashMap [] $ st ^. names shmProps = SHashMap [] xfmProps shmVals = SHashMap [] xfmVals -- since we currently have to fold over our properties in order -- answer remote queries, the sharing we do here seems a bit pointless, -- however we'll be moving to a shared memory based registry soon xfmProps = Map.foldlWithKey' convProps Map.empty (st ^. properties) xfmVals = Map.foldlWithKey' convVals Map.empty (st ^. properties) convProps m (p, k) _ = case Map.lookup p m of Nothing -> Map.insert p [k] m Just ks -> Map.insert p (k:ks) m convVals m (p, k) v = case Map.lookup p m of Nothing -> Map.insert p [(k, v)] m Just ks -> Map.insert p ((k, v):ks) m handleRegisterName :: forall k v. (Keyable k, Serializable v) => State k v -> RegisterKeyReq k -> Process (ProcessReply RegisterKeyReply (State k v)) handleRegisterName state (RegisterKeyReq Key{..}) = do let found = Map.lookup keyIdentity (state ^. names) case found of Nothing -> do let pid = fromJust keyScope let refs = state ^. registeredPids refs' <- ensureMonitored pid refs notifySubscribers keyIdentity state (KeyRegistered pid) reply RegisteredOk $ ( (names ^: Map.insert keyIdentity pid) . (registeredPids ^= refs') $ state) Just pid -> if (pid == (fromJust keyScope)) then reply RegisteredOk state else reply AlreadyRegistered state handleRegisterPropertyCR :: forall k v. (Keyable k, Serializable v) => State k v -> CallRef (RegisterKeyReply) -> (RegisterKeyReq k, v) -> Process (ProcessReply RegisterKeyReply (State k v)) handleRegisterPropertyCR st cr req = do pid <- resolve cr doRegisterProperty (fromJust pid) st req handleRegisterProperty :: forall k v. (Keyable k, Serializable v) => State k v -> (RegisterKeyReq k, v) -> Process (ProcessReply RegisterKeyReply (State k v)) handleRegisterProperty state req@((RegisterKeyReq Key{..}), _) = do doRegisterProperty (fromJust keyScope) state req doRegisterProperty :: forall k v. (Keyable k, Serializable v) => ProcessId -> State k v -> (RegisterKeyReq k, v) -> Process (ProcessReply RegisterKeyReply (State k v)) doRegisterProperty scope state ((RegisterKeyReq Key{..}), v) = do void $ P.monitor scope notifySubscribers keyIdentity state (KeyRegistered scope) reply RegisteredOk $ ( (properties ^: Map.insert (scope, keyIdentity) v) $ state ) handleLookupProperty :: forall k v. (Keyable k, Serializable v) => State k v -> LookupPropReq k -> Process (ProcessReply LookupPropReply (State k v)) handleLookupProperty state (PropReq Key{..}) = do let entry = Map.lookup (fromJust keyScope, keyIdentity) (state ^. properties) case entry of Nothing -> reply PropNotFound state Just p -> reply (PropFound (wrapMessage p)) state handleUnregisterName :: forall k v. (Keyable k, Serializable v) => State k v -> UnregisterKeyReq k -> Process (ProcessReply UnregisterKeyReply (State k v)) handleUnregisterName state (UnregisterKeyReq Key{..}) = do let entry = Map.lookup keyIdentity (state ^. names) case entry of Nothing -> reply UnregisterKeyNotFound state Just pid -> case (pid /= (fromJust keyScope)) of True -> reply UnregisterInvalidKey state False -> do notifySubscribers keyIdentity state KeyUnregistered let state' = ( (names ^: Map.delete keyIdentity) . (monitors ^: MultiMap.filterWithKey (\k' _ -> k' /= keyIdentity)) $ state) reply UnregisterOk $ state' handleGiveAwayName :: forall k v. (Keyable k, Serializable v) => State k v -> GiveAwayName k -> Process (ProcessAction (State k v)) handleGiveAwayName state (GiveAwayName newPid Key{..}) = do maybe (continue state) giveAway $ Map.lookup keyIdentity (state ^. names) where giveAway pid = do let scope = fromJust keyScope case (pid == scope) of False -> continue state True -> do let state' = ((names ^: Map.insert keyIdentity newPid) $ state) notifySubscribers keyIdentity state (KeyOwnerChanged pid newPid) continue state' handleMonitorReq :: forall k v. (Keyable k, Serializable v) => State k v -> CallRef RegKeyMonitorRef -> MonitorReq k -> Process (ProcessReply RegKeyMonitorRef (State k v)) handleMonitorReq state cRef (MonitorReq Key{..} mask') = do let mRefId = (state ^. monitorIdCount) + 1 Just caller <- resolve cRef let mRef = RegKeyMonitorRef (caller, mRefId) let kmRef = KMRef mRef mask' let refs = state ^. listeningPids refs' <- ensureMonitored caller refs fireEventForPreRegisteredKey state keyIdentity keyScope kmRef reply mRef $ ( (monitors ^: MultiMap.insert keyIdentity kmRef) . (listeningPids ^= refs') . (monitorIdCount ^= mRefId) $ state ) where fireEventForPreRegisteredKey st kId kScope KMRef{..} = do let evMask = maybe [] id mask case (keyType, elem OnKeyRegistered evMask) of (KeyTypeAlias, True) -> do let found = Map.lookup kId (st ^. names) fireEvent found kId ref (KeyTypeProperty, _) -> do self <- getSelfPid let scope = maybe self id kScope let found = Map.lookup (scope, kId) (st ^. properties) case found of Nothing -> return () -- TODO: logging or some such!? Just _ -> fireEvent (Just scope) kId ref _ -> return () fireEvent fnd kId' ref' = do case fnd of Nothing -> return () Just p -> do us <- getSelfPid sendTo ref' $ (RegistryKeyMonitorNotification kId' ref' (KeyRegistered p) us) handleUnmonitorReq :: forall k v. (Keyable k, Serializable v) => State k v -> CallRef () -> UnmonitorReq -> Process (ProcessReply () (State k v)) handleUnmonitorReq state _cRef (UnmonitorReq ref') = do let pid = fst $ unRef ref' reply () $ ( (monitors ^: MultiMap.filter ((/= ref') . ref)) . (listeningPids ^: Set.delete pid) $ state ) handleRegNamesLookup :: forall k v. (Keyable k, Serializable v) => RegNamesReq -> RestrictedProcess (State k v) (Result [k]) handleRegNamesLookup (RegNamesReq p) = do state <- getState Restricted.reply $ Map.foldlWithKey' (acc p) [] (state ^. names) where acc pid ns n pid' | pid == pid' = (n:ns) | otherwise = ns handleMonitorSignal :: forall k v. (Keyable k, Serializable v) => State k v -> ProcessMonitorNotification -> Process (ProcessAction (State k v)) handleMonitorSignal state@State{..} (ProcessMonitorNotification _ pid diedReason) = do let state' = removeActiveSubscriptions pid state (deadNames, deadProps) <- notifyListeners state' pid diedReason continue $ ( (names ^= Map.difference _names deadNames) . (properties ^= Map.difference _properties deadProps) $ state) where removeActiveSubscriptions p s = let subscriptions = (state ^. listeningPids) in case (Set.member p subscriptions) of False -> s True -> ( (listeningPids ^: Set.delete p) -- delete any monitors this (now dead) process held . (monitors ^: MultiMap.filter ((/= p) . fst . unRef . ref)) $ s) notifyListeners :: State k v -> ProcessId -> DiedReason -> Process (HashMap k ProcessId, HashMap (ProcessId, k) v) notifyListeners st pid' dr = do let diedNames = Map.filter (== pid') (st ^. names) let diedProps = Map.filterWithKey (\(p, _) _ -> p == pid') (st ^. properties) let nameSubs = MultiMap.filterWithKey (\k _ -> Map.member k diedNames) (st ^. monitors) let propSubs = MultiMap.filterWithKey (\k _ -> Map.member (pid', k) diedProps) (st ^. monitors) forM_ (MultiMap.toList nameSubs) $ \(kIdent, KMRef{..}) -> do let kEvDied = KeyOwnerDied { diedReason = dr } let mRef = RegistryKeyMonitorNotification kIdent ref us <- getSelfPid case mask of Nothing -> sendTo ref (mRef kEvDied us) Just mask' -> do case (elem OnKeyOwnershipChange mask') of True -> sendTo ref (mRef kEvDied us) False -> do if (elem OnKeyUnregistered mask') then sendTo ref (mRef KeyUnregistered us) else return () forM_ (MultiMap.toList propSubs) (notifyPropSubscribers dr) return (diedNames, diedProps) notifyPropSubscribers dr' (kIdent, KMRef{..}) = do let died = maybe False (elem OnKeyOwnershipChange) mask let event = case died of True -> KeyOwnerDied { diedReason = dr' } False -> KeyUnregistered getSelfPid >>= sendTo ref . RegistryKeyMonitorNotification kIdent ref event ensureMonitored :: ProcessId -> HashSet ProcessId -> Process (HashSet ProcessId) ensureMonitored pid refs = do case (Set.member pid refs) of True -> return refs False -> P.monitor pid >> return (Set.insert pid refs) notifySubscribers :: forall k v. (Keyable k, Serializable v) => k -> State k v -> KeyUpdateEvent -> Process () notifySubscribers k st ev = do let subscribers = MultiMap.filterWithKey (\k' _ -> k' == k) (st ^. monitors) forM_ (MultiMap.toList subscribers) $ \(_, KMRef{..}) -> do if (maybe True (elem (maskFor ev)) mask) then getSelfPid >>= sendTo ref . RegistryKeyMonitorNotification k ref ev else {- (liftIO $ putStrLn "no mask") >> -} return () -------------------------------------------------------------------------------- -- Utilities / Accessors -- -------------------------------------------------------------------------------- maskFor :: KeyUpdateEvent -> KeyUpdateEventMask maskFor (KeyRegistered _) = OnKeyRegistered maskFor KeyUnregistered = OnKeyUnregistered maskFor (KeyOwnerDied _) = OnKeyOwnershipChange maskFor (KeyOwnerChanged _ _) = OnKeyOwnershipChange maskFor KeyLeaseExpired = OnKeyLeaseExpiry findName :: forall k v. (Keyable k, Serializable v) => Key k -> State k v -> Maybe ProcessId findName Key{..} state = Map.lookup keyIdentity (state ^. names) names :: forall k v. Accessor (State k v) (HashMap k ProcessId) names = accessor _names (\n' st -> st { _names = n' }) properties :: forall k v. Accessor (State k v) (HashMap (ProcessId, k) v) properties = accessor _properties (\ps st -> st { _properties = ps }) monitors :: forall k v. Accessor (State k v) (MultiMap k KMRef) monitors = accessor _monitors (\ms st -> st { _monitors = ms }) registeredPids :: forall k v. Accessor (State k v) (HashSet ProcessId) registeredPids = accessor _registeredPids (\mp st -> st { _registeredPids = mp }) listeningPids :: forall k v. Accessor (State k v) (HashSet ProcessId) listeningPids = accessor _listeningPids (\lp st -> st { _listeningPids = lp }) monitorIdCount :: forall k v. Accessor (State k v) Integer monitorIdCount = accessor _monitorIdCount (\i st -> st { _monitorIdCount = i })
haskell-distributed/distributed-process-registry
src/Control/Distributed/Process/Registry.hs
Haskell
bsd-3-clause
41,815
module Diag.Util.Encoding where import Data.Char import Data.Word import Data.Bits import Numeric import Data.List import qualified Data.ByteString.Char8 as B import qualified Data.ByteString as S int2Word8 x = fromIntegral x :: Word8 word8ToInt x = fromIntegral x :: Int encodeInt :: (Integral a, Bits a) => a -> Int -> [Word8] encodeInt n width = [int2Word8 $ 0xFF .&. (n `shiftR` s) | s <- reverse $ take width [0,8..]] encodeLength :: Int -> [Word8] encodeLength len = [0xFF .&. int2Word8 (len `shiftR` 24) ,0xFF .&. int2Word8 (len `shiftR` 16) ,0xFF .&. int2Word8 (len `shiftR` 8) ,0xFF .&. int2Word8 (len `shiftR` 0)] string2hex :: String -> Word8 string2hex = fst . head . readHex string2hex16 :: String -> Word16 string2hex16 = fst . head . readHex showAsHex :: Word8 -> String showAsHex = ((++) "0x") . (flip showHex "") showAsHexOneString :: [Word8] -> String showAsHexOneString bs = "0x" ++ (concatMap showMin2Chars bs) showMin2Chars :: Word8 -> String showMin2Chars n = let x = flip showHex "" n len = length x in replicate (2 - len) '0' ++ x showAsHexString :: [Word8] -> String showAsHexString bs = '[':(intercalate "," $ map (showAsHex) bs) ++ "]" showAsBin :: Word8 -> String showAsBin = flip showBin "" where showBin = showIntAtBase 2 intToDigit showBinString :: B.ByteString -> String showBinString xs = showAsHexNumbers $ S.unpack xs showAsHexNumbers :: [Word8] -> String showAsHexNumbers xs = concat $ intersperse "," $ map (showAsHex . int2Word8) xs nothingIf :: Bool -> Maybe Int nothingIf True = Nothing nothingIf False = Just 0 convert :: String -> Char convert = chr . fst . head . readHex toWord :: (Enum a) => a -> Word8 toWord = int2Word8 . fromEnum
marcmo/hsDiagnosis
src/Diag/Util/Encoding.hs
Haskell
bsd-3-clause
1,777
{-# LANGUAGE TemplateHaskell, QuasiQuotes #-} module Language.C.CPPPP.Transforms.Chs (mkChs, mkObjChs) where import Language.C.CPPPP.Transforms.CTypes import qualified Language.C.Syntax as C import Language.C.Quote.C import Data.Loc (SrcLoc) import Data.List import Language.Haskell.TH hiding (varP) import System.IO mkChs = (initHs, mkChs', closeHs) mkObjChs = (initHs', mkObjChs', closeHs) mkChs' :: Handle -> String -> [C.Id] -> SrcLoc -> IO (Handle, C.Initializer) mkChs' h ex vars loc = (fcall ex vars :: IO (FCall CLang)) >>= emit h loc mkObjChs' :: Handle -> String -> [C.Id] -> SrcLoc -> IO (Handle, C.Initializer) mkObjChs' h ex vars loc = (fcall ex vars :: IO (FCall ObjCLang)) >>= emit h loc initHs = do h <- openFile "HSAux.hs" WriteMode hPutStrLn h "module HSAux where\n" return h initHs' = do h <- openFile "HSAuxObjC.hs" WriteMode hPutStrLn h "module HSAuxObjC where\n" return h closeHs = hClose -- | Return the C expression and use IO to generate the auxiliary Haskell -- | The auxiliary Haskell will use the FFI -- It should also have a unique counter for generated function names (instead of Data.Unique). -- | Write out the aux Haskell and return the C Expression to substitute emit :: (FormatString a) => Handle -> SrcLoc -> FCall a -> IO (Handle, C.Initializer) emit h loc (FCall fname ffi_name args) = do let carg_list = map snd args cexpr = C.FnCall (C.Var (C.Id ffi_name loc) loc) (map (flip C.Var loc) carg_list) loc hs_expr <- runQ $ mkHsExpr ffi_name fname args hPutStrLn h $ pprint hs_expr return (h, [cinit|$cexpr|]) -- args: [(CType CInt,Id "x" ),(CType CInt,Id "y" )] mkHsExpr :: FormatString a => String -> String -> [(Arg a, C.Id)] -> Q [Dec] mkHsExpr ffi_name fname args = do names <- mapM newName $ replicate (length args) "x" let types = applyT $ map (mkName . mkType . fst) args mar = map (mkMarshalling . fst) args body = NormalB $ applyN (zip mar (reverse names)) (mkName fname) for = ForeignD $ ExportF CCall ffi_name (mkName ffi_name) types decl = FunD (mkName ffi_name) [Clause (map VarP names) body []] return [for, decl] applyN :: [(Exp, Name)] -> Name -> Exp applyN [] fname = VarE fname applyN [(m, x)] fname = AppE (VarE fname) (AppE m (VarE x)) applyN ((m, x):xs) fname = AppE (applyN xs fname) (AppE m (VarE x)) applyT :: [Name] -> Type -- applyT [] = boom applyT [x] = ConT x applyT (x:xs) = AppT (AppT ArrowT (ConT x)) (applyT xs)
mxswd/cpppp
Language/C/CPPPP/Transforms/Chs.hs
Haskell
bsd-3-clause
2,463
{-# OPTIONS -Wall #-} {-| Module : Esge.Base Description : Highlevel basic esge module. Copyright : (c) Simon Goller, 2015 License : BSD Maintainer : neosam@posteo.de Basic required functions in order create a game. They are higher level and let you for example move Individuals. Many features are introduced by this module * Error handling * Individual and Room interaction * State * Player handling * Provide basic 'EC.Action's -} module Esge.Base ( -- * Type definitions Error (RoomNotFoundError, ExitNotFoundError), State (stPlayer, stVersion, stName), -- * Error functions printError, -- * Individual/Room interaction individualsInRoomId, individualsInRoom, roomsOfIndividualId, roomOfIndividualId, roomOfIndividual, beam, move, -- * State functions nullState, state, -- * Player specific functions player, currRoom, -- * Actions -- ** Long term actions infinityAction, condInfinityAction, condDropableAction, condSingleAction, delayedAction, -- ** Game state actions moveRoomAction, showRoomAction, showIndAction, showStateAction, showStorageAction ) where import qualified Esge.Core as EC import qualified Esge.Room as ER import qualified Esge.Individual as EI import Data.Maybe (catMaybes) -- | Thrown in case of something goes wrong data Error = RoomNotFoundError String | ExitNotFoundError String deriving (Show, Read, Eq) -- | Return all individuals from the given room id. -- Result is Nothing if room is not found. individualsInRoomId :: String -> EC.Ingame -> Maybe [EI.Individual] individualsInRoomId key ingame = do room <- ER.getRoomMaybe ingame key let inds = ER.individual room :: [String] let storages = catMaybes $ map (flip EC.storageGet $ ingame) inds :: [EC.Storage] let maybeInds = map EC.fromStorage storages :: [Maybe EI.Individual] return $ catMaybes maybeInds -- | Return all individuals from the given room individualsInRoom :: ER.Room -> EC.Ingame -> Maybe [EI.Individual] individualsInRoom room ingame = individualsInRoomId (ER.key room) ingame -- | Room which contains the given Individual id. -- Returns nullRoom if not found roomOfIndividualId :: String -> EC.Ingame -> ER.Room roomOfIndividualId key ingame = let rooms = roomsOfIndividualId key ingame in if null rooms then ER.nullRoom else head rooms -- | Return all rooms, where the individual is located. -- -- This should only be one or nothing otherwise there is most likely an issue -- in the story setup. Normally, 'roomOfIndividualId' or 'roomOfIndividual' -- should be used. The purpose of this function is as helper for the -- plausability check. roomsOfIndividualId :: String -> EC.Ingame -> [ER.Room] roomsOfIndividualId key ingame = let rooms = ER.allRooms ingame :: [ER.Room] in filter (\x -> elem key $ ER.individual x) rooms -- | Room which contains the given Individual roomOfIndividual :: EI.Individual -> EC.Ingame -> ER.Room roomOfIndividual ind ingame = roomOfIndividualId (EI.key ind) ingame -- | Place Individual in other room beam :: EI.Individual -> String -> EC.Action (Either Error ()) beam ind roomId = do ingame <- EC.getIngame let indKey = EI.key ind fromRoom = roomOfIndividual ind ingame case ER.getRoomMaybe ingame roomId of Nothing -> return $ Left $ RoomNotFoundError roomId Just room -> do let room' = ER.addIndividualId indKey room fromRoom' = ER.removeIndividualId indKey fromRoom EC.storageInsertA fromRoom' EC.storageInsertA room' return $ Right () -- | Move individual through an exit to another room move :: EI.Individual -> String -> EC.Action (Either Error ()) move ind exitRoom = do ingame <- EC.getIngame let fromRoom = roomOfIndividual ind ingame if exitRoom `elem` (map fst $ ER.exits fromRoom) then beam ind (maybe "" id $ lookup exitRoom $ ER.exits fromRoom) else return $ Left $ ExitNotFoundError exitRoom -- | Important state values data State = State { stPlayer :: String, stVersion :: String, stName :: String } deriving (Eq, Read, Show) -- | State to use in case of an error nullState :: State nullState = State "" "" "" -- | State can be stored in 'EC.Ingame' instance EC.Storageable State where toStorage st = EC.Storage "state" "esgeState" [ ("player", stPlayer st), ("version", stVersion st), ("name", stName st) ] fromStorage (EC.Storage _ t metas) = if t /= "esgeState" then Nothing else do ply <- lookup "player" metas version <- lookup "version" metas name <- lookup "name" metas return State { stPlayer = ply, stVersion = version, stName = name } -- | Get state from 'EC.Ingame' state :: EC.Ingame -> State state ingame = maybe nullState id $ do storage <- EC.storageGet "state" ingame st <- EC.fromStorage storage return st -- | Get player from 'EC.Ingame' player :: EC.Ingame -> EI.Individual player ingame = let playerId = stPlayer $ state ingame in EI.getIndividualNull ingame playerId -- | Get room where player is located currRoom :: EC.Ingame -> ER.Room currRoom ingame = roomOfIndividual (player ingame) ingame -- | Print 'Error' to 'EC.Ingame' output response printError :: Error -> EC.Action () printError err = EC.setIngameResponseA "output" ( case err of RoomNotFoundError str -> "Room not found: '" ++ str ++ "'" ExitNotFoundError str -> "Exit not found: " ++ str ++ "'" ) -- | Move player in 'Room' of behind exit. moveRoomAction :: String -> EC.Action () moveRoomAction exitName = do ingame <- EC.getIngame res <- move (player ingame) exitName case res of Left err -> printError err Right () -> return () -- | Display room showRoomAction :: EC.Action () showRoomAction = do ingame <- EC.getIngame let room = currRoom ingame roomText = ER.title room ++ "\n" ++ ER.desc room ++ "\n" ++ "Exits: " ++ (unwords $ ER.exitNames room) EC.setIngameResponseA "output" roomText -- | Show individual showIndAction :: EI.Individual -> EC.Action () showIndAction ind = EC.setIngameResponseA "output" indText where indText = EI.name ind -- | Show state for debugging showStateAction :: EC.Action () showStateAction = do ingame <- EC.getIngame let stateText = show $ state ingame EC.setIngameResponseA "output" stateText -- | Show the whole 'Storage' showStorageAction :: EC.Action () showStorageAction = do ingame <- EC.getIngame let stateText = show $ EC.storage ingame EC.setIngameResponseA "output" stateText -- | Run given action and re register infinityAction :: EC.Action () -> EC.Action () infinityAction act = do let self = infinityAction act EC.replaceIngame $ EC.scheduleAction self act -- | Run given action only if condition is true condInfinityAction :: (EC.Ingame -> Bool) -> EC.Action () -> EC.Action () condInfinityAction condFn act = do let self = condInfinityAction condFn act EC.replaceIngame $ EC.scheduleAction self ingame <- EC.getIngame if condFn ingame then act else return () -- | Run given action as long as condition is true, then remove it condDropableAction :: (EC.Ingame -> Bool) -> EC.Action () -> EC.Action () condDropableAction condFn act = do let self = condDropableAction condFn act ingame <- EC.getIngame if condFn ingame then do EC.replaceIngame $ EC.scheduleAction self act else return () -- | Do nothing until the condition becomes true, then run 'Action' once -- and remove. condSingleAction :: (EC.Ingame -> Bool) -> EC.Action () -> EC.Action () condSingleAction condFn act = do let self = condSingleAction condFn act ingame <- EC.getIngame if condFn ingame then act else EC.replaceIngame $ EC.scheduleAction self -- | Wait n times and then run the action delayedAction :: Int -> EC.Action () -> EC.Action () delayedAction n act = do let self = delayedAction (n - 1) act if n <= 0 then act else EC.replaceIngame $ EC.scheduleAction self
neosam/esge
src/Esge/Base.hs
Haskell
bsd-3-clause
8,528
module TestData where import Data.IntMap as IMap import Data.Set as Set data Codegen = C | JS deriving (Show, Eq, Ord) type Index = Int data CompatCodegen = ANY | C_CG | NODE_CG | NONE -- A TestFamily groups tests that share the same theme data TestFamily = TestFamily { -- A shorter lowcase name to use in filenames id :: String, -- A proper name for the test family that will be displayed name :: String, -- A map of test metadata: -- - The key is the index (>=1 && <1000) -- - The value is the set of compatible code generators, -- or Nothing if the test doesn't depend on a code generator tests :: IntMap (Maybe (Set Codegen)) } deriving (Show) toCodegenSet :: CompatCodegen -> Maybe (Set Codegen) toCodegenSet compatCodegen = fmap Set.fromList mList where mList = case compatCodegen of ANY -> Just [ C, JS ] C_CG -> Just [ C ] NODE_CG -> Just [ JS ] NONE -> Nothing testFamilies :: [TestFamily] testFamilies = fmap instantiate testFamiliesData where instantiate (id, name, testsData) = TestFamily id name tests where tests = IMap.fromList (fmap makeSetCodegen testsData) makeSetCodegen (index, codegens) = (index, toCodegenSet codegens) testFamiliesForCodegen :: Codegen -> [TestFamily] testFamiliesForCodegen codegen = fmap (\testFamily -> testFamily {tests = IMap.filter f (tests testFamily)}) testFamilies where f mCodegens = case mCodegens of Just codegens -> Set.member codegen codegens Nothing -> True -- The data to instanciate testFamilies -- The first column is the id -- The second column is the proper name (the prefix of the subfolders) -- The third column is the data for each test testFamiliesData :: [(String, String, [(Index, CompatCodegen)])] testFamiliesData = [ ("base", "Base", [ ( 1, C_CG )]), ("basic", "Basic", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, C_CG ), ( 8, ANY ), ( 9, ANY ), ( 10, ANY ), ( 11, C_CG ), ( 12, ANY ), ( 13, ANY ), ( 14, ANY ), ( 15, ANY ), ( 16, ANY ), ( 17, ANY ), ( 18, ANY ), ( 19, ANY ), ( 20, ANY ), ( 21, C_CG )]), ("bignum", "Bignum", [ ( 1, ANY ), ( 2, ANY )]), ("bounded", "Bounded", [ ( 1, ANY )]), ("buffer", "Buffer", [ ( 1, C_CG )]), ("corecords", "Corecords", [ ( 1, ANY ), ( 2, ANY )]), ("delab", "De-elaboration", [ ( 1, ANY )]), ("directives", "Directives", [ ( 1, ANY ), ( 2, ANY )]), ("disambig", "Disambiguation", [ ( 2, ANY )]), ("docs", "Documentation", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY )]), ("dsl", "DSL", [ ( 1, ANY ), ( 2, C_CG ), ( 3, ANY ), ( 4, ANY )]), ("effects", "Effects", [ ( 1, C_CG ), ( 2, C_CG ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY )]), ("error", "Errors", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY ), ( 9, ANY )]), ("ffi", "FFI", [ ( 1, ANY ) , ( 2, ANY ) , ( 3, ANY ) , ( 4, ANY ) , ( 5, ANY ) , ( 6, C_CG ) , ( 7, C_CG ) , ( 8, C_CG ) , ( 9, C_CG ) , ( 10, NODE_CG ) , ( 11, NODE_CG ) ]), ("folding", "Folding", [ ( 1, ANY )]), ("idrisdoc", "Idris documentation", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY ), ( 9, ANY )]), ("interactive", "Interactive editing", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY ), ( 9, ANY ), ( 10, ANY ), ( 11, ANY ), ( 12, ANY ), ( 13, ANY ), ( 14, C_CG ), ( 15, ANY ), ( 16, ANY ), -- FIXME: Re-enable interactive017 once it works with and without node. -- FIXME: See https://github.com/idris-lang/Idris-dev/pull/4046#issuecomment-326910042 -- ( 17, ANY ), ( 18, ANY )]), ("interfaces", "Interfaces", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), -- ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY )]), ("interpret", "Interpret", [ ( 1, ANY ), ( 2, ANY )]), ("io", "IO monad", [ ( 1, C_CG ), ( 2, ANY ), ( 3, C_CG )]), ("layout", "Layout", [ ( 1, ANY )]), ("literate", "Literate programming", [ ( 1, ANY )]), ("meta", "Meta-programming", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY )]), ("pkg", "Packages", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY )]), ("prelude", "Prelude", [ ( 1, ANY )]), ("primitives", "Primitive types", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 5, C_CG ), ( 6, C_CG )]), ("proof", "Theorem proving", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY ), ( 9, ANY ), ( 10, ANY ), ( 11, ANY )]), ("proofsearch", "Proof search", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY )]), ("pruviloj", "Pruviloj", [ ( 1, ANY )]), ("quasiquote", "Quasiquotations", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY )]), ("records", "Records", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY )]), ("reg", "Regressions", [ ( 1, ANY ), ( 2, ANY ), ( 4, ANY ), ( 5, ANY ), ( 13, ANY ), ( 16, ANY ), ( 17, ANY ), ( 20, ANY ), ( 24, ANY ), ( 25, ANY ), ( 27, ANY ), ( 29, C_CG ), ( 31, ANY ), ( 32, ANY ), ( 39, ANY ), ( 40, ANY ), ( 41, ANY ), ( 42, ANY ), ( 45, ANY ), ( 48, ANY ), ( 52, C_CG ), ( 67, ANY ), ( 75, ANY ), ( 76, ANY ), ( 77, ANY )]), ("regression", "Regression", [ ( 1 , ANY ), ( 2 , ANY ), ( 3 , ANY )]), ("sourceLocation", "Source location", [ ( 1 , ANY )]), ("sugar", "Syntactic sugar", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, C_CG ), ( 5, ANY )]), ("syntax", "Syntax extensions", [ ( 1, ANY ), ( 2, ANY )]), ("tactics", "Tactics", [ ( 1, ANY )]), ("totality", "Totality checking", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY ), ( 9, ANY ), ( 10, ANY ), ( 11, ANY ), ( 12, ANY ), ( 13, ANY ), ( 14, ANY ), ( 15, ANY ), ( 16, ANY ), ( 17, ANY ), ( 18, ANY ), ( 19, ANY ), ( 20, ANY ), ( 21, ANY ), ( 22, ANY ), ( 23, ANY )]), ("tutorial", "Tutorial examples", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, C_CG )]), ("unique", "Uniqueness types", [ ( 1, ANY ), ( 4, ANY )]), ("universes", "Universes", [ ( 1, ANY ), ( 2, ANY )]), ("views", "Views", [ ( 1, ANY ), ( 2, ANY ), ( 3, C_CG )])]
uuhan/Idris-dev
test/TestData.hs
Haskell
bsd-3-clause
8,201
module HLearn.Data.UnsafeVector ( setptsize ) where import Control.DeepSeq import Control.Monad import Data.IORef import Debug.Trace import qualified Data.Foldable as F import Data.Primitive import Data.Primitive.MachDeps import qualified Data.Vector.Generic as VG import qualified Data.Vector.Generic.Mutable as VGM import qualified Data.Vector.Unboxed as VU import qualified Data.Vector.Unboxed.Mutable as VUM import System.IO.Unsafe import qualified Data.Strict.Maybe as Strict import Data.Csv import Unsafe.Coerce import Data.Hashable import Data.Primitive.ByteArray import GHC.Prim import GHC.Int import GHC.Types import SubHask hiding (Functor(..), Applicative(..), Monad(..), Then(..), fail, return, liftM, forM_) -- import SubHask.Compatibility.Vector.HistogramMetrics import SubHask.Compatibility.Vector.Lebesgue ------------------------------------------------------------------------------- -- unsafe globals {-# NOINLINE ptsizeIO #-} ptsizeIO = unsafeDupablePerformIO $ newIORef (16::Int) {-# NOINLINE ptalignIO #-} ptalignIO = unsafeDupablePerformIO $ newIORef (16::Int) {-# NOINLINE ptsize #-} ptsize = unsafeDupablePerformIO $ readIORef ptsizeIO {-# NOINLINE ptalign #-} ptalign = unsafeDupablePerformIO $ readIORef ptalignIO setptsize :: Int -> IO () setptsize len = do writeIORef ptsizeIO len writeIORef ptalignIO (4::Int) ------------------------------------------------------------------------------- -- l2 vector ops instance VUM.Unbox elem => VUM.Unbox (L2 VU.Vector elem) data instance VUM.MVector s (L2 VU.Vector elem) = UnsafeMVector { elemsizeM :: {-#UNPACK#-} !Int , elemsizerealM :: {-#UNPACK#-} !Int , lenM :: {-#UNPACK#-} !Int , vecM :: !(VUM.MVector s elem) } instance ( VG.Vector VU.Vector elem , VGM.MVector VUM.MVector elem ) => VGM.MVector VUM.MVector (L2 VU.Vector elem) where {-# INLINABLE basicLength #-} basicLength uv = lenM uv {-# INLINABLE basicUnsafeSlice #-} basicUnsafeSlice i lenM' uv = UnsafeMVector { elemsizeM = elemsizeM uv , elemsizerealM = elemsizerealM uv , lenM = lenM' , vecM = VGM.basicUnsafeSlice (i*elemsizerealM uv) (lenM'*elemsizerealM uv) $ vecM uv } {-# INLINABLE basicOverlaps #-} basicOverlaps uv1 uv2 = VGM.basicOverlaps (vecM uv1) (vecM uv2) {-# INLINABLE basicUnsafeNew #-} basicUnsafeNew lenM' = do let elemsizeM'=ptsize -- let elemsizerealM'=20 let elemsizerealM'=ptalign*(ptsize `div` ptalign) +if ptsize `mod` ptalign == 0 then 0 else ptalign -- trace ("elemsizeM' = "++show elemsizeM') $ return () -- trace ("elemsizerealM' = "++show elemsizerealM') $ return () vecM' <- VGM.basicUnsafeNew (lenM'*elemsizerealM') return $ UnsafeMVector { elemsizeM=elemsizeM' , elemsizerealM=elemsizerealM' , lenM=lenM' , vecM=vecM' } {-# INLINABLE basicUnsafeRead #-} basicUnsafeRead uv i = liftM L2 $ VG.freeze $ VGM.unsafeSlice (i*elemsizerealM uv) (elemsizeM uv) (vecM uv) {-# INLINABLE basicUnsafeWrite #-} -- FIXME: this is probably better, but it causes GHC to panic -- basicUnsafeWrite uv loc v = go 0 -- where -- go i = if i <= elemsizerealM uv -- then do -- VGM.unsafeWrite (vecM uv) (start+i) $ v `VG.unsafeIndex` i -- go (i+1) -- else return () -- start = loc*elemsizerealM uv basicUnsafeWrite uv loc v = forM_ [0..elemsizeM uv-1] $ \i -> do let x = v `VG.unsafeIndex` i VGM.unsafeWrite (vecM uv) (start+i) x where start = loc*elemsizerealM uv {-# INLINABLE basicUnsafeCopy #-} basicUnsafeCopy v1 v2 = VGM.basicUnsafeCopy (vecM v1) (vecM v2) {-# INLINABLE basicUnsafeMove #-} basicUnsafeMove v1 v2 = VGM.basicUnsafeMove (vecM v1) (vecM v2) -- {-# INLINABLE basicSet #-} -- basicSet v x = VGM.basicSet (vecM v) x ------------------------------------------------------------------------------- -- immutable vector data instance VU.Vector (L2 VU.Vector elem) = UnsafeVector { elemsize :: {-# UNPACK #-} !Int , elemsizereal :: {-# UNPACK #-} !Int , len :: {-# UNPACK #-} !Int , vec :: !(L2 VU.Vector elem) } instance ( VG.Vector VU.Vector elem , VGM.MVector VUM.MVector elem ) => VG.Vector VU.Vector (L2 VU.Vector elem) where {-# INLINABLE basicUnsafeFreeze #-} basicUnsafeFreeze uv = do vec' <- VG.basicUnsafeFreeze (vecM uv) return $ UnsafeVector { elemsize = elemsizeM uv , elemsizereal = elemsizerealM uv , len = lenM uv , vec = L2 vec' } {-# INLINABLE basicUnsafeThaw #-} basicUnsafeThaw uv = do vecM' <- VG.basicUnsafeThaw (unL2 $ vec uv) return $ UnsafeMVector { elemsizeM = elemsize uv , elemsizerealM = elemsizereal uv , lenM = len uv , vecM = vecM' } {-# INLINABLE basicLength #-} basicLength uv = len uv {-# INLINABLE basicUnsafeSlice #-} basicUnsafeSlice i len' uv = uv { len = len' , vec = VG.basicUnsafeSlice (i*elemsizereal uv) (len'*elemsizereal uv) (vec uv) } {-# INLINABLE basicUnsafeIndexM #-} basicUnsafeIndexM uv i = return $ VG.basicUnsafeSlice (i*elemsizereal uv) (elemsize uv) (vec uv) -- {-# INLINABLE basicUnsafeCopy #-} -- basicUnsafeCopy mv v = VG.basicUnsafeCopy (vecM mv) (vec v) ------------------------------------------------------------------------------- -- Labeled' instance (VUM.Unbox x, VUM.Unbox y) => VUM.Unbox (Labeled' x y) newtype instance VUM.MVector s (Labeled' x y) = UMV_Labeled' (VUM.MVector s (x,y)) instance ( VUM.Unbox x , VUM.Unbox y ) => VGM.MVector VUM.MVector (Labeled' x y) where {-# INLINABLE basicLength #-} {-# INLINABLE basicUnsafeSlice #-} {-# INLINABLE basicOverlaps #-} {-# INLINABLE basicUnsafeNew #-} {-# INLINABLE basicUnsafeRead #-} {-# INLINABLE basicUnsafeWrite #-} {-# INLINABLE basicUnsafeCopy #-} {-# INLINABLE basicUnsafeMove #-} {-# INLINABLE basicSet #-} basicLength (UMV_Labeled' v) = VGM.basicLength v basicUnsafeSlice i len (UMV_Labeled' v) = UMV_Labeled' $ VGM.basicUnsafeSlice i len v basicOverlaps (UMV_Labeled' v1) (UMV_Labeled' v2) = VGM.basicOverlaps v1 v2 basicUnsafeNew len = liftM UMV_Labeled' $ VGM.basicUnsafeNew len basicUnsafeRead (UMV_Labeled' v) i = do (!x,!y) <- VGM.basicUnsafeRead v i return $ Labeled' x y basicUnsafeWrite (UMV_Labeled' v) i (Labeled' x y) = VGM.basicUnsafeWrite v i (x,y) basicUnsafeCopy (UMV_Labeled' v1) (UMV_Labeled' v2) = VGM.basicUnsafeCopy v1 v2 basicUnsafeMove (UMV_Labeled' v1) (UMV_Labeled' v2) = VGM.basicUnsafeMove v1 v2 basicSet (UMV_Labeled' v1) (Labeled' x y) = VGM.basicSet v1 (x,y) newtype instance VU.Vector (Labeled' x y) = UV_Labeled' (VU.Vector (x,y)) instance ( VUM.Unbox x , VUM.Unbox y ) => VG.Vector VU.Vector (Labeled' x y) where {-# INLINABLE basicUnsafeFreeze #-} {-# INLINABLE basicUnsafeThaw #-} {-# INLINABLE basicLength #-} {-# INLINABLE basicUnsafeSlice #-} {-# INLINABLE basicUnsafeIndexM #-} basicUnsafeFreeze (UMV_Labeled' v) = liftM UV_Labeled' $ VG.basicUnsafeFreeze v basicUnsafeThaw (UV_Labeled' v) = liftM UMV_Labeled' $ VG.basicUnsafeThaw v basicLength (UV_Labeled' v) = VG.basicLength v basicUnsafeSlice i len (UV_Labeled' v) = UV_Labeled' $ VG.basicUnsafeSlice i len v basicUnsafeIndexM (UV_Labeled' v) i = do (!x,!y) <- VG.basicUnsafeIndexM v i return $ Labeled' x y
iamkingmaker/HLearn
src/HLearn/Data/UnsafeVector.hs
Haskell
bsd-3-clause
7,912
{-# LANGUAGE QuasiQuotes #-} module Test0 () where import LiquidHaskell [lq| thing :: Int -> x:Int |] thing = undefined
spinda/liquidhaskell
benchmarks/gsoc15/neg/test5.hs
Haskell
bsd-3-clause
124
{-# LANGUAGE DoRec, GeneralizedNewtypeDeriving #-} module Language.Brainfuck.CompileToIA32 (compile) where import qualified Language.Brainfuck.Syntax as BF import Language.IA32.Syntax import Control.Monad.RWS newtype Compiler a = Compiler { runCompiler :: RWS () [Directive] Label a } deriving (Monad, MonadFix) compile :: [BF.Stmt] -> Program compile program = Program $ snd $ execRWS (runCompiler (compileMain program)) () (Label 0) label :: Compiler Label label = Compiler $ do lbl <- get tell [LabelDef lbl] modify succ return lbl tellOp :: [Op] -> Compiler () tellOp = Compiler . tell . map Op (ptr, dat) = (Reg reg, Deref reg) where reg = EBP compileMain program = do tellOp [Mov ptr (Macro "BUF")] mapM_ compileStep $ group program tellOp [Mov (Reg EAX) (Imm 1), Mov (Reg EBX) (Imm 0), Int80] group = foldr f [] where f x (y@(x', n):ys) | x ≈ x' = (x', n+1):ys | otherwise = (x, 1):y:ys f x [] = [(x, 1)] BF.IncPtr ≈ BF.IncPtr = True BF.DecPtr ≈ BF.DecPtr = True BF.IncData ≈ BF.IncData = True BF.DecData ≈ BF.DecData = True _ ≈ _ = False arith 1 arg = Inc arg arith (-1) arg = Dec arg arith n arg | n > 0 = Add arg (Imm $ fromInteger n) | n < 0 = Sub arg (Imm $ fromInteger (abs n)) compileStep (BF.IncPtr, n) = tellOp [arith n ptr] compileStep (BF.DecPtr, n) = tellOp [arith (-n) ptr] compileStep (BF.IncData, n) = tellOp [arith n dat] compileStep (BF.DecData, n) = tellOp [arith (-n) dat] compileStep (BF.Output, 1) = tellOp [Mov (Reg EDX) (Imm 1), Mov (Reg ECX) (Target ptr), Mov (Reg EBX) (Imm 1), Mov (Reg EAX) (Imm 4), Int80] compileStep (BF.While prog, 1) = do rec l <- label tellOp [Cmp (Target dat) (Imm 0), JmpZero l'] mapM_ compileStep $ group prog tellOp [Jmp l] l' <- label return ()
gergoerdi/brainfuck
language-brainfuck/src/Language/Brainfuck/CompileToIA32.hs
Haskell
bsd-3-clause
2,123
{-# OPTIONS -XDeriveDataTypeable -XCPP #-} module ShopCart ( shopCart) where import Data.Typeable import qualified Data.Vector as V import Text.Blaze.Html5 as El import Text.Blaze.Html5.Attributes as At hiding (step) import Data.Monoid import Data.String import Data.Typeable -- #define ALONE -- to execute it alone, uncomment this #ifdef ALONE import MFlow.Wai.Blaze.Html.All main= runNavigation "" $ transientNav grid #else import MFlow.Wai.Blaze.Html.All hiding(retry, page) import Menu #endif data ShopOptions= IPhone | IPod | IPad deriving (Bounded, Enum, Show,Read , Typeable) newtype Cart= Cart (V.Vector Int) deriving Typeable emptyCart= Cart $ V.fromList [0,0,0] shopCart= shopCart1 shopCart1 = do -- setHeader stdheader -- setTimeouts 200 $ 60*60 prod <- step . page $ do Cart cart <- getSessionData `onNothing` return emptyCart moreexplain ++> (table ! At.style (attr "border:1;width:20%;margin-left:auto;margin-right:auto") <<< caption << "choose an item" ++> thead << tr << ( th << b << "item" <> th << b << "times chosen") ++> (tbody <<< tr ! rowspan (attr "2") << td << linkHome ++> (tr <<< td <<< wlink IPhone (b << "iphone") <++ tdc << ( b << show ( cart V.! 0)) <|> tr <<< td <<< wlink IPod (b << "ipod") <++ tdc << ( b << show ( cart V.! 1)) <|> tr <<< td <<< wlink IPad (b << "ipad") <++ tdc << ( b << show ( cart V.! 2))) <++ tr << td << linkHome )) let i = fromEnum prod Cart cart <- getSessionData `onNothing` return emptyCart setSessionData . Cart $ cart V.// [(i, cart V.! i + 1 )] shopCart1 where tdc= td ! At.style (attr "text-align:center") linkHome= a ! href (attr $ "/" ++ noScript) << b << "home" attr= fromString moreexplain= do p $ El.span <<( "A persistent flow (uses step). The process is killed after the timeout set by setTimeouts "++ "but it is restarted automatically. Event If you restart the whole server, it remember the shopping cart "++ " The shopping cart is not logged, just the products bought returned by step are logged. The shopping cart "++ " is rebuild from the events (that is an example of event sourcing."++ " .Defines a table with links that return ints and a link to the menu, that abandon this flow. "++ " .The cart state is not stored, Only the history of events is saved. The cart is recreated by running the history of events.") p << "The second parameter of \"setTimeout\" is the time during which the cart is recorded"
agocorona/MFlow
Demos/ShopCart.hs
Haskell
bsd-3-clause
2,856
{-# OPTIONS -XCPP -#include "comPrim.h" #-} ----------------------------------------------------------------------------- -- | -- Module : System.Win32.Com.Exception -- Copyright : (c) 2009, Sigbjorn Finne -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : sof@forkIO.com -- Stability : provisional -- Portability : portable -- -- Representing and working with COM's 'exception model' (@HRESULT@s) in Haskell. -- Failures in COM method calls are mapped into 'Control.Exception' Haskell exceptions, -- providing convenient handlers to catch and throw these. -- ----------------------------------------------------------------------------- module System.Win32.Com.Exception where import System.Win32.Com.HDirect.HDirect hiding ( readFloat ) import System.Win32.Com.Base import Data.Int import Data.Word import Data.Bits import Data.Dynamic import Data.Maybe ( isJust, fromMaybe ) import Numeric ( showHex ) import System.IO.Error ( ioeGetErrorString ) #if BASE == 3 import GHC.IOBase import Control.Exception -- | @act `catchComException` (ex -> hdlr ex)@ performs the -- IO action @act@, but catches any IO or COM exceptions @ex@, -- passing them to the handler @hdlr@. catchComException :: IO a -> (Com_Exception -> IO a) -> IO a catchComException act hdlr = Control.Exception.catch act (\ ex -> case ex of DynException d -> case fromDynamic d of Just ce -> hdlr (Right ce) _ -> throwIO ex IOException ioe -> hdlr (Left ioe) _ -> throwIO ex) catch_ce_ :: IO a -> (Maybe ComException -> IO a) -> IO a catch_ce_ act hdlr = catchComException act (\ e -> case e of Left ioe -> hdlr Nothing Right ce -> hdlr (Just ce)) #else import Control.Exception -- | @act `catchComException` (ex -> hdlr ex)@ performs the -- IO action @act@, but catches any IO or COM exceptions @ex@, -- passing them to the handler @hdlr@. catchComException :: IO a -> (Com_Exception -> IO a) -> IO a catchComException act hdlr = Control.Exception.catch act (\ e -> case fromException e of Just ioe -> hdlr (Left ioe) _ -> case fromException e of Just d -> hdlr (Right d) _ -> throwIO e) catch_ce_ :: IO a -> (Maybe ComException -> IO a) -> IO a catch_ce_ act hdlr = catchComException act (\ e -> case e of Left ioe -> hdlr Nothing Right ce -> hdlr (Just ce)) #endif -- | @Com_Exception@ is either an 'IOException' or 'ComException'; -- no attempt is made to embed one inside the other. type Com_Exception = Either IOException ComException -- | @throwIOComException ex@ raises/throws the exception @ex@; -- @ex@ is either an 'IOException' or a 'ComException'. throwIOComException :: Com_Exception -> IO a throwIOComException (Left e) = ioError e throwIOComException (Right ce) = throwComException ce -- | @check2HR hr@ triggers a COM exception if the HRESULT -- @hr@ represent an error condition. The current /last error/ -- value embedded in the exception gives more information about -- cause. check2HR :: HRESULT -> IO () check2HR hr | succeeded hr = return () | otherwise = do dw <- getLastError coFailHR (word32ToInt32 dw) -- | @checkBool mbZero@ raises a COM exception if @mbZero@ is equal -- to...zero. The /last error/ is embedded inside the exception. checkBool :: Int32 -> IO () checkBool flg | flg /=0 = return () | otherwise = do dw <- getLastError coFailHR (word32ToInt32 dw) -- | @returnHR act@ runs the IO action @act@, catching any -- COM exceptions. Success or failure is then mapped back into -- the corresponding HRESULT. In the case of success, 's_OK'. returnHR :: IO () -> IO HRESULT returnHR act = catch_ce_ (act >> return s_OK) (\ mb_hr -> return (maybe failure toHR mb_hr)) where toHR ComException{comException=(ComError hr)} = hr -- better return codes could easily be imagined.. failure = e_FAIL -- | @isCoError e@ returns @True@ for COM exceptions; @False@ -- for IO exception values. isCoError :: Com_Exception -> Bool isCoError Right{} = True isCoError Left{} = False -- | @coGetException ei@ picks out the COM exception @ei@, if one. coGetException :: Com_Exception -> Maybe ComException coGetException (Right ce) = Just ce coGetException _ = Nothing -- | @coGetException ei@ picks out the COM HRESULT from the exception, if any. coGetErrorHR :: Com_Exception -> Maybe HRESULT coGetErrorHR Left{} = Nothing coGetErrorHR (Right ce) = Just (case comException ce of (ComError hr) -> hr) -- | @coGetException ei@ returns a user-friendlier representation of the @ei@ exception. coGetErrorString :: Com_Exception -> String coGetErrorString (Left ioe) = ioeGetErrorString ioe coGetErrorString (Right ce) = comExceptionMsg ce ++ showParen True (showHex (int32ToWord32 (comExceptionHR ce))) "" printComError :: Com_Exception -> IO () printComError ce = putStrLn (coGetErrorString ce) -- | An alias to 'coGetErrorString'. hresultToString :: HRESULT -> IO String hresultToString = stringFromHR coAssert :: Bool -> String -> IO () coAssert True msg = return () coAssert False msg = coFail msg coOnFail :: IO a -> String -> IO a coOnFail io msg = catchComException io (\ e -> case e of Left ioe -> coFail (msg ++ ": " ++ ioeGetErrorString ioe) Right ce -> coFail (msg ++ ": " ++ comExceptionMsg ce)) -- | @coFail msg@ raised the @E_FAIL@ COM exception along with -- the descriptive string @msg@. coFail :: String -> IO a coFail = coFailWithHR e_FAIL -- | @s_OK@ and @s_FALSE@ are the boolean values encoded as 'HRESULT's. s_FALSE, s_OK :: HRESULT s_OK = 0 s_FALSE = 1 nOERROR :: HRESULT nOERROR = 0 nO_ERROR :: HRESULT nO_ERROR = 0 sEVERITY_ERROR :: Int32 sEVERITY_ERROR = 1 sEVERITY_SUCCESS :: Int32 sEVERITY_SUCCESS = 0 succeeded :: HRESULT -> Bool succeeded hr = hr >=0 winErrorToHR :: Int32 -> HRESULT winErrorToHR 0 = 0 winErrorToHR x = (fACILITY_WIN32 `shiftL` 16) .|. (bit 31) .|. (x .&. 0xffff) hRESULT_CODE :: HRESULT -> Int32 hRESULT_CODE hr = hr .&. (fromIntegral 0xffff) hRESULT_FACILITY :: HRESULT -> Int32 hRESULT_FACILITY hr = (hr `shiftR` 16) .&. 0x1fff hRESULT_SEVERITY :: HRESULT -> Int32 hRESULT_SEVERITY hr = (hr `shiftR` 31) .&. 0x1 mkHRESULT :: Int32 -> Int32 -> Int32 -> HRESULT mkHRESULT sev fac code = word32ToInt32 ( ((int32ToWord32 sev) `shiftL` 31) .|. ((int32ToWord32 fac) `shiftL` 16) .|. (int32ToWord32 code) ) cAT_E_CATIDNOEXIST :: HRESULT cAT_E_CATIDNOEXIST = word32ToInt32 (0x80040160 ::Word32) cAT_E_FIRST :: HRESULT cAT_E_FIRST = word32ToInt32 (0x80040160 ::Word32) cAT_E_LAST :: HRESULT cAT_E_LAST = word32ToInt32 (0x80040161 ::Word32) cAT_E_NODESCRIPTION :: HRESULT cAT_E_NODESCRIPTION = word32ToInt32 (0x80040161 ::Word32) cLASS_E_CLASSNOTAVAILABLE :: HRESULT cLASS_E_CLASSNOTAVAILABLE = word32ToInt32 (0x80040111 ::Word32) cLASS_E_NOAGGREGATION :: HRESULT cLASS_E_NOAGGREGATION = word32ToInt32 (0x80040110 ::Word32) cLASS_E_NOTLICENSED :: HRESULT cLASS_E_NOTLICENSED = word32ToInt32 (0x80040112 ::Word32) cO_E_ACCESSCHECKFAILED :: HRESULT cO_E_ACCESSCHECKFAILED = word32ToInt32 (0x80040207 ::Word32) cO_E_ACESINWRONGORDER :: HRESULT cO_E_ACESINWRONGORDER = word32ToInt32 (0x80040217 ::Word32) cO_E_ACNOTINITIALIZED :: HRESULT cO_E_ACNOTINITIALIZED = word32ToInt32 (0x8004021B ::Word32) cO_E_ALREADYINITIALIZED :: HRESULT cO_E_ALREADYINITIALIZED = word32ToInt32 (0x800401F1 ::Word32) cO_E_APPDIDNTREG :: HRESULT cO_E_APPDIDNTREG = word32ToInt32 (0x800401FE ::Word32) cO_E_APPNOTFOUND :: HRESULT cO_E_APPNOTFOUND = word32ToInt32 (0x800401F5 ::Word32) cO_E_APPSINGLEUSE :: HRESULT cO_E_APPSINGLEUSE = word32ToInt32 (0x800401F6 ::Word32) cO_E_BAD_PATH :: HRESULT cO_E_BAD_PATH = word32ToInt32 (0x80080004 ::Word32) cO_E_BAD_SERVER_NAME :: HRESULT cO_E_BAD_SERVER_NAME = word32ToInt32 (0x80004014 ::Word32) cO_E_CANTDETERMINECLASS :: HRESULT cO_E_CANTDETERMINECLASS = word32ToInt32 (0x800401F2 ::Word32) cO_E_CANT_REMOTE :: HRESULT cO_E_CANT_REMOTE = word32ToInt32 (0x80004013 ::Word32) cO_E_CLASSSTRING :: HRESULT cO_E_CLASSSTRING = word32ToInt32 (0x800401F3 ::Word32) cO_E_CLASS_CREATE_FAILED :: HRESULT cO_E_CLASS_CREATE_FAILED = word32ToInt32 (0x80080001 ::Word32) cO_E_CLSREG_INCONSISTENT :: HRESULT cO_E_CLSREG_INCONSISTENT = word32ToInt32 (0x8000401F ::Word32) cO_E_CONVERSIONFAILED :: HRESULT cO_E_CONVERSIONFAILED = word32ToInt32 (0x8004020B ::Word32) cO_E_CREATEPROCESS_FAILURE :: HRESULT cO_E_CREATEPROCESS_FAILURE = word32ToInt32 (0x80004018 ::Word32) cO_E_DECODEFAILED :: HRESULT cO_E_DECODEFAILED = word32ToInt32 (0x8004021A ::Word32) cO_E_DLLNOTFOUND :: HRESULT cO_E_DLLNOTFOUND = word32ToInt32 (0x800401F8 ::Word32) cO_E_ERRORINAPP :: HRESULT cO_E_ERRORINAPP = word32ToInt32 (0x800401F7 ::Word32) cO_E_ERRORINDLL :: HRESULT cO_E_ERRORINDLL = word32ToInt32 (0x800401F9 ::Word32) cO_E_EXCEEDSYSACLLIMIT :: HRESULT cO_E_EXCEEDSYSACLLIMIT = word32ToInt32 (0x80040216 ::Word32) cO_E_FAILEDTOCLOSEHANDLE :: HRESULT cO_E_FAILEDTOCLOSEHANDLE = word32ToInt32 (0x80040215 ::Word32) cO_E_FAILEDTOCREATEFILE :: HRESULT cO_E_FAILEDTOCREATEFILE = word32ToInt32 (0x80040214 ::Word32) cO_E_FAILEDTOGENUUID :: HRESULT cO_E_FAILEDTOGENUUID = word32ToInt32 (0x80040213 ::Word32) cO_E_FAILEDTOGETSECCTX :: HRESULT cO_E_FAILEDTOGETSECCTX = word32ToInt32 (0x80040201 ::Word32) cO_E_FAILEDTOGETTOKENINFO :: HRESULT cO_E_FAILEDTOGETTOKENINFO = word32ToInt32 (0x80040203 ::Word32) cO_E_FAILEDTOGETWINDIR :: HRESULT cO_E_FAILEDTOGETWINDIR = word32ToInt32 (0x80040211 ::Word32) cO_E_FAILEDTOIMPERSONATE :: HRESULT cO_E_FAILEDTOIMPERSONATE = word32ToInt32 (0x80040200 ::Word32) cO_E_FAILEDTOOPENPROCESSTOKEN :: HRESULT cO_E_FAILEDTOOPENPROCESSTOKEN = word32ToInt32 (0x80040219 ::Word32) cO_E_FAILEDTOOPENTHREADTOKEN :: HRESULT cO_E_FAILEDTOOPENTHREADTOKEN = word32ToInt32 (0x80040202 ::Word32) cO_E_FAILEDTOQUERYCLIENTBLANKET :: HRESULT cO_E_FAILEDTOQUERYCLIENTBLANKET = word32ToInt32 (0x80040205 ::Word32) cO_E_FAILEDTOSETDACL :: HRESULT cO_E_FAILEDTOSETDACL = word32ToInt32 (0x80040206 ::Word32) cO_E_FIRST :: HRESULT cO_E_FIRST = word32ToInt32 (0x800401F0 ::Word32) cO_E_IIDREG_INCONSISTENT :: HRESULT cO_E_IIDREG_INCONSISTENT = word32ToInt32 (0x80004020 ::Word32) cO_E_IIDSTRING :: HRESULT cO_E_IIDSTRING = word32ToInt32 (0x800401F4 ::Word32) cO_E_INCOMPATIBLESTREAMVERSION :: HRESULT cO_E_INCOMPATIBLESTREAMVERSION = word32ToInt32 (0x80040218 ::Word32) cO_E_INIT_CLASS_CACHE :: HRESULT cO_E_INIT_CLASS_CACHE = word32ToInt32 (0x80004009 ::Word32) cO_E_INIT_MEMORY_ALLOCATOR :: HRESULT cO_E_INIT_MEMORY_ALLOCATOR = word32ToInt32 (0x80004008 ::Word32) cO_E_INIT_ONLY_SINGLE_THREADED :: HRESULT cO_E_INIT_ONLY_SINGLE_THREADED = word32ToInt32 (0x80004012 ::Word32) cO_E_INIT_RPC_CHANNEL :: HRESULT cO_E_INIT_RPC_CHANNEL = word32ToInt32 (0x8000400A ::Word32) cO_E_INIT_SCM_EXEC_FAILURE :: HRESULT cO_E_INIT_SCM_EXEC_FAILURE = word32ToInt32 (0x80004011 ::Word32) cO_E_INIT_SCM_FILE_MAPPING_EXISTS :: HRESULT cO_E_INIT_SCM_FILE_MAPPING_EXISTS = word32ToInt32 (0x8000400F ::Word32) cO_E_INIT_SCM_MAP_VIEW_OF_FILE :: HRESULT cO_E_INIT_SCM_MAP_VIEW_OF_FILE = word32ToInt32 (0x80004010 ::Word32) cO_E_INIT_SCM_MUTEX_EXISTS :: HRESULT cO_E_INIT_SCM_MUTEX_EXISTS = word32ToInt32 (0x8000400E ::Word32) cO_E_INIT_SHARED_ALLOCATOR :: HRESULT cO_E_INIT_SHARED_ALLOCATOR = word32ToInt32 (0x80004007 ::Word32) cO_E_INIT_TLS :: HRESULT cO_E_INIT_TLS = word32ToInt32 (0x80004006 ::Word32) cO_E_INIT_TLS_CHANNEL_CONTROL :: HRESULT cO_E_INIT_TLS_CHANNEL_CONTROL = word32ToInt32 (0x8000400C ::Word32) cO_E_INIT_TLS_SET_CHANNEL_CONTROL :: HRESULT cO_E_INIT_TLS_SET_CHANNEL_CONTROL = word32ToInt32 (0x8000400B ::Word32) cO_E_INIT_UNACCEPTED_USER_ALLOCATOR :: HRESULT cO_E_INIT_UNACCEPTED_USER_ALLOCATOR = word32ToInt32 (0x8000400D ::Word32) cO_E_INVALIDSID :: HRESULT cO_E_INVALIDSID = word32ToInt32 (0x8004020A ::Word32) cO_E_LAST :: HRESULT cO_E_LAST = word32ToInt32 (0x800401FF ::Word32) cO_E_LAUNCH_PERMSSION_DENIED :: HRESULT cO_E_LAUNCH_PERMSSION_DENIED = word32ToInt32 (0x8000401B ::Word32) cO_E_LOOKUPACCNAMEFAILED :: HRESULT cO_E_LOOKUPACCNAMEFAILED = word32ToInt32 (0x8004020F ::Word32) cO_E_LOOKUPACCSIDFAILED :: HRESULT cO_E_LOOKUPACCSIDFAILED = word32ToInt32 (0x8004020D ::Word32) cO_E_MSI_ERROR :: HRESULT cO_E_MSI_ERROR = word32ToInt32 (0x80004023 ::Word32) cO_E_NETACCESSAPIFAILED :: HRESULT cO_E_NETACCESSAPIFAILED = word32ToInt32 (0x80040208 ::Word32) cO_E_NOMATCHINGNAMEFOUND :: HRESULT cO_E_NOMATCHINGNAMEFOUND = word32ToInt32 (0x8004020E ::Word32) cO_E_NOMATCHINGSIDFOUND :: HRESULT cO_E_NOMATCHINGSIDFOUND = word32ToInt32 (0x8004020C ::Word32) cO_E_NOTINITIALIZED :: HRESULT cO_E_NOTINITIALIZED = word32ToInt32 (0x800401F0 ::Word32) cO_E_NOT_SUPPORTED :: HRESULT cO_E_NOT_SUPPORTED = word32ToInt32 (0x80004021 ::Word32) cO_E_OBJISREG :: HRESULT cO_E_OBJISREG = word32ToInt32 (0x800401FC ::Word32) cO_E_OBJNOTCONNECTED :: HRESULT cO_E_OBJNOTCONNECTED = word32ToInt32 (0x800401FD ::Word32) cO_E_OBJNOTREG :: HRESULT cO_E_OBJNOTREG = word32ToInt32 (0x800401FB ::Word32) cO_E_OBJSRV_RPC_FAILURE :: HRESULT cO_E_OBJSRV_RPC_FAILURE = word32ToInt32 (0x80080006 ::Word32) cO_E_OLE1DDE_DISABLED :: HRESULT cO_E_OLE1DDE_DISABLED = word32ToInt32 (0x80004016 ::Word32) cO_E_PATHTOOLONG :: HRESULT cO_E_PATHTOOLONG = word32ToInt32 (0x80040212 ::Word32) cO_E_RELEASED :: HRESULT cO_E_RELEASED = word32ToInt32 (0x800401FF ::Word32) cO_E_RELOAD_DLL :: HRESULT cO_E_RELOAD_DLL = word32ToInt32 (0x80004022 ::Word32) cO_E_REMOTE_COMMUNICATION_FAILURE :: HRESULT cO_E_REMOTE_COMMUNICATION_FAILURE = word32ToInt32 (0x8000401D ::Word32) cO_E_RUNAS_CREATEPROCESS_FAILURE :: HRESULT cO_E_RUNAS_CREATEPROCESS_FAILURE = word32ToInt32 (0x80004019 ::Word32) cO_E_RUNAS_LOGON_FAILURE :: HRESULT cO_E_RUNAS_LOGON_FAILURE = word32ToInt32 (0x8000401A ::Word32) cO_E_RUNAS_SYNTAX :: HRESULT cO_E_RUNAS_SYNTAX = word32ToInt32 (0x80004017 ::Word32) cO_E_SCM_ERROR :: HRESULT cO_E_SCM_ERROR = word32ToInt32 (0x80080002 ::Word32) cO_E_SCM_RPC_FAILURE :: HRESULT cO_E_SCM_RPC_FAILURE = word32ToInt32 (0x80080003 ::Word32) cO_E_SERVER_EXEC_FAILURE :: HRESULT cO_E_SERVER_EXEC_FAILURE = word32ToInt32 (0x80080005 ::Word32) cO_E_SERVER_START_TIMEOUT :: HRESULT cO_E_SERVER_START_TIMEOUT = word32ToInt32 (0x8000401E ::Word32) cO_E_SERVER_STOPPING :: HRESULT cO_E_SERVER_STOPPING = word32ToInt32 (0x80080008 ::Word32) cO_E_SETSERLHNDLFAILED :: HRESULT cO_E_SETSERLHNDLFAILED = word32ToInt32 (0x80040210 ::Word32) cO_E_START_SERVICE_FAILURE :: HRESULT cO_E_START_SERVICE_FAILURE = word32ToInt32 (0x8000401C ::Word32) cO_E_TRUSTEEDOESNTMATCHCLIENT :: HRESULT cO_E_TRUSTEEDOESNTMATCHCLIENT = word32ToInt32 (0x80040204 ::Word32) cO_E_WRONGOSFORAPP :: HRESULT cO_E_WRONGOSFORAPP = word32ToInt32 (0x800401FA ::Word32) cO_E_WRONGTRUSTEENAMESYNTAX :: HRESULT cO_E_WRONGTRUSTEENAMESYNTAX = word32ToInt32 (0x80040209 ::Word32) cO_E_WRONG_SERVER_IDENTITY :: HRESULT cO_E_WRONG_SERVER_IDENTITY = word32ToInt32 (0x80004015 ::Word32) cO_S_FIRST :: HRESULT cO_S_FIRST = word32ToInt32 (0x000401F0 ::Word32) cO_S_LAST :: HRESULT cO_S_LAST = word32ToInt32 (0x000401FF ::Word32) cO_S_NOTALLINTERFACES :: HRESULT cO_S_NOTALLINTERFACES = word32ToInt32 (0x00080012 ::Word32) dISP_E_ARRAYISLOCKED :: HRESULT dISP_E_ARRAYISLOCKED = word32ToInt32 (0x8002000D ::Word32) dISP_E_BADCALLEE :: HRESULT dISP_E_BADCALLEE = word32ToInt32 (0x80020010 ::Word32) dISP_E_BADINDEX :: HRESULT dISP_E_BADINDEX = word32ToInt32 (0x8002000B ::Word32) dISP_E_BADPARAMCOUNT :: HRESULT dISP_E_BADPARAMCOUNT = word32ToInt32 (0x8002000E ::Word32) dISP_E_BADVARTYPE :: HRESULT dISP_E_BADVARTYPE = word32ToInt32 (0x80020008 ::Word32) dISP_E_DIVBYZERO :: HRESULT dISP_E_DIVBYZERO = word32ToInt32 (0x80020012 ::Word32) dISP_E_EXCEPTION :: HRESULT dISP_E_EXCEPTION = word32ToInt32 (0x80020009 ::Word32) dISP_E_MEMBERNOTFOUND :: HRESULT dISP_E_MEMBERNOTFOUND = word32ToInt32 (0x80020003 ::Word32) dISP_E_NONAMEDARGS :: HRESULT dISP_E_NONAMEDARGS = word32ToInt32 (0x80020007 ::Word32) dISP_E_NOTACOLLECTION :: HRESULT dISP_E_NOTACOLLECTION = word32ToInt32 (0x80020011 ::Word32) dISP_E_OVERFLOW :: HRESULT dISP_E_OVERFLOW = word32ToInt32 (0x8002000A ::Word32) dISP_E_PARAMNOTFOUND :: HRESULT dISP_E_PARAMNOTFOUND = word32ToInt32 (0x80020004 ::Word32) dISP_E_PARAMNOTOPTIONAL :: HRESULT dISP_E_PARAMNOTOPTIONAL = word32ToInt32 (0x8002000F ::Word32) dISP_E_TYPEMISMATCH :: HRESULT dISP_E_TYPEMISMATCH = word32ToInt32 (0x80020005 ::Word32) dISP_E_UNKNOWNINTERFACE :: HRESULT dISP_E_UNKNOWNINTERFACE = word32ToInt32 (0x80020001 ::Word32) dISP_E_UNKNOWNLCID :: HRESULT dISP_E_UNKNOWNLCID = word32ToInt32 (0x8002000C ::Word32) dISP_E_UNKNOWNNAME :: HRESULT dISP_E_UNKNOWNNAME = word32ToInt32 (0x80020006 ::Word32) dV_E_CLIPFORMAT :: HRESULT dV_E_CLIPFORMAT = word32ToInt32 (0x8004006A ::Word32) dV_E_DVASPECT :: HRESULT dV_E_DVASPECT = word32ToInt32 (0x8004006B ::Word32) dV_E_DVTARGETDEVICE :: HRESULT dV_E_DVTARGETDEVICE = word32ToInt32 (0x80040065 ::Word32) dV_E_DVTARGETDEVICE_SIZE :: HRESULT dV_E_DVTARGETDEVICE_SIZE = word32ToInt32 (0x8004006C ::Word32) dV_E_FORMATETC :: HRESULT dV_E_FORMATETC = word32ToInt32 (0x80040064 ::Word32) dV_E_LINDEX :: HRESULT dV_E_LINDEX = word32ToInt32 (0x80040068 ::Word32) dV_E_NOIVIEWOBJECT :: HRESULT dV_E_NOIVIEWOBJECT = word32ToInt32 (0x8004006D ::Word32) dV_E_STATDATA :: HRESULT dV_E_STATDATA = word32ToInt32 (0x80040067 ::Word32) dV_E_STGMEDIUM :: HRESULT dV_E_STGMEDIUM = word32ToInt32 (0x80040066 ::Word32) dV_E_TYMED :: HRESULT dV_E_TYMED = word32ToInt32 (0x80040069 ::Word32) e_ABORT :: HRESULT e_ABORT = word32ToInt32 (0x80004004 ::Word32) e_ACCESSDENIED :: HRESULT e_ACCESSDENIED = word32ToInt32 (0x80070005 ::Word32) e_FAIL :: HRESULT e_FAIL = word32ToInt32 (0x80004005 ::Word32) e_HANDLE :: HRESULT e_HANDLE = word32ToInt32 (0x80070006 ::Word32) e_INVALIDARG :: HRESULT e_INVALIDARG = word32ToInt32 (0x80070057 ::Word32) e_NOINTERFACE :: HRESULT e_NOINTERFACE = word32ToInt32 (0x80004002 ::Word32) e_NOTIMPL :: HRESULT e_NOTIMPL = word32ToInt32 (0x80004001 ::Word32) e_OUTOFMEMORY :: HRESULT e_OUTOFMEMORY = word32ToInt32 (0x8007000E ::Word32) e_PENDING :: HRESULT e_PENDING = word32ToInt32 (0x8000000A ::Word32) e_POINTER :: HRESULT e_POINTER = word32ToInt32 (0x80004003 ::Word32) e_UNEXPECTED :: HRESULT e_UNEXPECTED = word32ToInt32 (0x8000FFFF ::Word32) fACILITY_CERT :: HRESULT fACILITY_CERT = 11 fACILITY_CONTROL :: HRESULT fACILITY_CONTROL = 10 fACILITY_DISPATCH :: HRESULT fACILITY_DISPATCH = 2 fACILITY_INTERNET :: HRESULT fACILITY_INTERNET = 12 fACILITY_ITF :: HRESULT fACILITY_ITF = 4 fACILITY_MEDIASERVER :: HRESULT fACILITY_MEDIASERVER = 13 fACILITY_MSMQ :: HRESULT fACILITY_MSMQ = 14 fACILITY_NT_BIT :: HRESULT fACILITY_NT_BIT = word32ToInt32 (0x10000000 ::Word32) fACILITY_NULL :: HRESULT fACILITY_NULL = 0 fACILITY_RPC :: HRESULT fACILITY_RPC = 1 fACILITY_SETUPAPI :: HRESULT fACILITY_SETUPAPI = 15 fACILITY_SSPI :: HRESULT fACILITY_SSPI = 9 fACILITY_STORAGE :: HRESULT fACILITY_STORAGE = 3 fACILITY_WIN32 :: HRESULT fACILITY_WIN32 = 7 fACILITY_WINDOWS :: HRESULT fACILITY_WINDOWS = 8 iNPLACE_E_FIRST :: HRESULT iNPLACE_E_FIRST = word32ToInt32 (0x800401A0 ::Word32) iNPLACE_E_LAST :: HRESULT iNPLACE_E_LAST = word32ToInt32 (0x800401AF ::Word32) iNPLACE_E_NOTOOLSPACE :: HRESULT iNPLACE_E_NOTOOLSPACE = word32ToInt32 (0x800401A1 ::Word32) iNPLACE_E_NOTUNDOABLE :: HRESULT iNPLACE_E_NOTUNDOABLE = word32ToInt32 (0x800401A0 ::Word32) iNPLACE_S_FIRST :: HRESULT iNPLACE_S_FIRST = word32ToInt32 (0x000401A0 ::Word32) iNPLACE_S_LAST :: HRESULT iNPLACE_S_LAST = word32ToInt32 (0x000401AF ::Word32) iNPLACE_S_TRUNCATED :: HRESULT iNPLACE_S_TRUNCATED = word32ToInt32 (0x000401A0 ::Word32) mARSHAL_E_FIRST :: HRESULT mARSHAL_E_FIRST = word32ToInt32 (0x80040120 ::Word32) mARSHAL_E_LAST :: HRESULT mARSHAL_E_LAST = word32ToInt32 (0x8004012F ::Word32) mARSHAL_S_FIRST :: HRESULT mARSHAL_S_FIRST = word32ToInt32 (0x00040120 ::Word32) mARSHAL_S_LAST :: HRESULT mARSHAL_S_LAST = word32ToInt32 (0x0004012F ::Word32) mEM_E_INVALID_LINK :: HRESULT mEM_E_INVALID_LINK = word32ToInt32 (0x80080010 ::Word32) mEM_E_INVALID_ROOT :: HRESULT mEM_E_INVALID_ROOT = word32ToInt32 (0x80080009 ::Word32) mEM_E_INVALID_SIZE :: HRESULT mEM_E_INVALID_SIZE = word32ToInt32 (0x80080011 ::Word32) mK_E_CANTOPENFILE :: HRESULT mK_E_CANTOPENFILE = word32ToInt32 (0x800401EA ::Word32) mK_E_CONNECTMANUALLY :: HRESULT mK_E_CONNECTMANUALLY = word32ToInt32 (0x800401E0 ::Word32) mK_E_ENUMERATION_FAILED :: HRESULT mK_E_ENUMERATION_FAILED = word32ToInt32 (0x800401EF ::Word32) mK_E_EXCEEDEDDEADLINE :: HRESULT mK_E_EXCEEDEDDEADLINE = word32ToInt32 (0x800401E1 ::Word32) mK_E_FIRST :: HRESULT mK_E_FIRST = word32ToInt32 (0x800401E0 ::Word32) mK_E_INTERMEDIATEINTERFACENOTSUPPORTED :: HRESULT mK_E_INTERMEDIATEINTERFACENOTSUPPORTED = word32ToInt32 (0x800401E7 ::Word32) mK_E_INVALIDEXTENSION :: HRESULT mK_E_INVALIDEXTENSION = word32ToInt32 (0x800401E6 ::Word32) mK_E_LAST :: HRESULT mK_E_LAST = word32ToInt32 (0x800401EF ::Word32) mK_E_MUSTBOTHERUSER :: HRESULT mK_E_MUSTBOTHERUSER = word32ToInt32 (0x800401EB ::Word32) mK_E_NEEDGENERIC :: HRESULT mK_E_NEEDGENERIC = word32ToInt32 (0x800401E2 ::Word32) mK_E_NOINVERSE :: HRESULT mK_E_NOINVERSE = word32ToInt32 (0x800401EC ::Word32) mK_E_NOOBJECT :: HRESULT mK_E_NOOBJECT = word32ToInt32 (0x800401E5 ::Word32) mK_E_NOPREFIX :: HRESULT mK_E_NOPREFIX = word32ToInt32 (0x800401EE ::Word32) mK_E_NOSTORAGE :: HRESULT mK_E_NOSTORAGE = word32ToInt32 (0x800401ED ::Word32) mK_E_NOTBINDABLE :: HRESULT mK_E_NOTBINDABLE = word32ToInt32 (0x800401E8 ::Word32) mK_E_NOTBOUND :: HRESULT mK_E_NOTBOUND = word32ToInt32 (0x800401E9 ::Word32) mK_E_NO_NORMALIZED :: HRESULT mK_E_NO_NORMALIZED = word32ToInt32 (0x80080007 ::Word32) mK_E_SYNTAX :: HRESULT mK_E_SYNTAX = word32ToInt32 (0x800401E4 ::Word32) mK_E_UNAVAILABLE :: HRESULT mK_E_UNAVAILABLE = word32ToInt32 (0x800401E3 ::Word32) mK_S_FIRST :: HRESULT mK_S_FIRST = word32ToInt32 (0x000401E0 ::Word32) mK_S_HIM :: HRESULT mK_S_HIM = word32ToInt32 (0x000401E5 ::Word32) mK_S_LAST :: HRESULT mK_S_LAST = word32ToInt32 (0x000401EF ::Word32) mK_S_ME :: HRESULT mK_S_ME = word32ToInt32 (0x000401E4 ::Word32) mK_S_MONIKERALREADYREGISTERED :: HRESULT mK_S_MONIKERALREADYREGISTERED = word32ToInt32 (0x000401E7 ::Word32) mK_S_REDUCED_TO_SELF :: HRESULT mK_S_REDUCED_TO_SELF = word32ToInt32 (0x000401E2 ::Word32) mK_S_US :: HRESULT mK_S_US = word32ToInt32 (0x000401E6 ::Word32) oLEOBJ_E_FIRST :: HRESULT oLEOBJ_E_FIRST = word32ToInt32 (0x80040180 ::Word32) oLEOBJ_E_INVALIDVERB :: HRESULT oLEOBJ_E_INVALIDVERB = word32ToInt32 (0x80040181 ::Word32) oLEOBJ_E_LAST :: HRESULT oLEOBJ_E_LAST = word32ToInt32 (0x8004018F ::Word32) oLEOBJ_E_NOVERBS :: HRESULT oLEOBJ_E_NOVERBS = word32ToInt32 (0x80040180 ::Word32) oLEOBJ_S_CANNOT_DOVERB_NOW :: HRESULT oLEOBJ_S_CANNOT_DOVERB_NOW = word32ToInt32 (0x00040181 ::Word32) oLEOBJ_S_FIRST :: HRESULT oLEOBJ_S_FIRST = word32ToInt32 (0x00040180 ::Word32) oLEOBJ_S_INVALIDHWND :: HRESULT oLEOBJ_S_INVALIDHWND = word32ToInt32 (0x00040182 ::Word32) oLEOBJ_S_INVALIDVERB :: HRESULT oLEOBJ_S_INVALIDVERB = word32ToInt32 (0x00040180 ::Word32) oLEOBJ_S_LAST :: HRESULT oLEOBJ_S_LAST = word32ToInt32 (0x0004018F ::Word32) oLE_E_ADVF :: HRESULT oLE_E_ADVF = word32ToInt32 (0x80040001 ::Word32) oLE_E_ADVISENOTSUPPORTED :: HRESULT oLE_E_ADVISENOTSUPPORTED = word32ToInt32 (0x80040003 ::Word32) oLE_E_BLANK :: HRESULT oLE_E_BLANK = word32ToInt32 (0x80040007 ::Word32) oLE_E_CANTCONVERT :: HRESULT oLE_E_CANTCONVERT = word32ToInt32 (0x80040011 ::Word32) oLE_E_CANT_BINDTOSOURCE :: HRESULT oLE_E_CANT_BINDTOSOURCE = word32ToInt32 (0x8004000A ::Word32) oLE_E_CANT_GETMONIKER :: HRESULT oLE_E_CANT_GETMONIKER = word32ToInt32 (0x80040009 ::Word32) oLE_E_CLASSDIFF :: HRESULT oLE_E_CLASSDIFF = word32ToInt32 (0x80040008 ::Word32) oLE_E_ENUM_NOMORE :: HRESULT oLE_E_ENUM_NOMORE = word32ToInt32 (0x80040002 ::Word32) oLE_E_FIRST :: HRESULT oLE_E_FIRST = word32ToInt32 (0x80040000::Word32) oLE_E_INVALIDHWND :: HRESULT oLE_E_INVALIDHWND = word32ToInt32 (0x8004000F ::Word32) oLE_E_INVALIDRECT :: HRESULT oLE_E_INVALIDRECT = word32ToInt32 (0x8004000D ::Word32) oLE_E_LAST :: HRESULT oLE_E_LAST = word32ToInt32 (0x800400FF::Word32) oLE_E_NOCACHE :: HRESULT oLE_E_NOCACHE = word32ToInt32 (0x80040006 ::Word32) oLE_E_NOCONNECTION :: HRESULT oLE_E_NOCONNECTION = word32ToInt32 (0x80040004 ::Word32) oLE_E_NOSTORAGE :: HRESULT oLE_E_NOSTORAGE = word32ToInt32 (0x80040012 ::Word32) oLE_E_NOTRUNNING :: HRESULT oLE_E_NOTRUNNING = word32ToInt32 (0x80040005 ::Word32) oLE_E_NOT_INPLACEACTIVE :: HRESULT oLE_E_NOT_INPLACEACTIVE = word32ToInt32 (0x80040010 ::Word32) oLE_E_OLEVERB :: HRESULT oLE_E_OLEVERB = word32ToInt32 (0x80040000 ::Word32) oLE_E_PROMPTSAVECANCELLED :: HRESULT oLE_E_PROMPTSAVECANCELLED = word32ToInt32 (0x8004000C ::Word32) oLE_E_STATIC :: HRESULT oLE_E_STATIC = word32ToInt32 (0x8004000B ::Word32) oLE_E_WRONGCOMPOBJ :: HRESULT oLE_E_WRONGCOMPOBJ = word32ToInt32 (0x8004000E ::Word32) oLE_S_FIRST :: HRESULT oLE_S_FIRST = word32ToInt32 (0x00040000 ::Word32) oLE_S_LAST :: HRESULT oLE_S_LAST = word32ToInt32 (0x000400FF ::Word32) oLE_S_MAC_CLIPFORMAT :: HRESULT oLE_S_MAC_CLIPFORMAT = word32ToInt32 (0x00040002 ::Word32) oLE_S_STATIC :: HRESULT oLE_S_STATIC = word32ToInt32 (0x00040001 ::Word32) oLE_S_USEREG :: HRESULT oLE_S_USEREG = word32ToInt32 (0x00040000 ::Word32) pERSIST_E_NOTSELFSIZING :: HRESULT pERSIST_E_NOTSELFSIZING = word32ToInt32 (0x800B000B ::Word32) pERSIST_E_SIZEDEFINITE :: HRESULT pERSIST_E_SIZEDEFINITE = word32ToInt32 (0x800B0009 ::Word32) pERSIST_E_SIZEINDEFINITE :: HRESULT pERSIST_E_SIZEINDEFINITE = word32ToInt32 (0x800B000A ::Word32) sTG_E_ABNORMALAPIEXIT :: HRESULT sTG_E_ABNORMALAPIEXIT = word32ToInt32 (0x800300FA ::Word32) sTG_E_ACCESSDENIED :: HRESULT sTG_E_ACCESSDENIED = word32ToInt32 (0x80030005 ::Word32) sTG_E_BADBASEADDRESS :: HRESULT sTG_E_BADBASEADDRESS = word32ToInt32 (0x80030110 ::Word32) sTG_E_CANTSAVE :: HRESULT sTG_E_CANTSAVE = word32ToInt32 (0x80030103 ::Word32) sTG_E_DISKISWRITEPROTECTED :: HRESULT sTG_E_DISKISWRITEPROTECTED = word32ToInt32 (0x80030013 ::Word32) sTG_E_DOCFILECORRUPT :: HRESULT sTG_E_DOCFILECORRUPT = word32ToInt32 (0x80030109 ::Word32) sTG_E_EXTANTMARSHALLINGS :: HRESULT sTG_E_EXTANTMARSHALLINGS = word32ToInt32 (0x80030108 ::Word32) sTG_E_FILEALREADYEXISTS :: HRESULT sTG_E_FILEALREADYEXISTS = word32ToInt32 (0x80030050 ::Word32) sTG_E_FILENOTFOUND :: HRESULT sTG_E_FILENOTFOUND = word32ToInt32 (0x80030002 ::Word32) sTG_E_INCOMPLETE :: HRESULT sTG_E_INCOMPLETE = word32ToInt32 (0x80030201 ::Word32) sTG_E_INSUFFICIENTMEMORY :: HRESULT sTG_E_INSUFFICIENTMEMORY = word32ToInt32 (0x80030008 ::Word32) sTG_E_INUSE :: HRESULT sTG_E_INUSE = word32ToInt32 (0x80030100 ::Word32) sTG_E_INVALIDFLAG :: HRESULT sTG_E_INVALIDFLAG = word32ToInt32 (0x800300FF ::Word32) sTG_E_INVALIDFUNCTION :: HRESULT sTG_E_INVALIDFUNCTION = word32ToInt32 (0x80030001 ::Word32) sTG_E_INVALIDHANDLE :: HRESULT sTG_E_INVALIDHANDLE = word32ToInt32 (0x80030006 ::Word32) sTG_E_INVALIDHEADER :: HRESULT sTG_E_INVALIDHEADER = word32ToInt32 (0x800300FB ::Word32) sTG_E_INVALIDNAME :: HRESULT sTG_E_INVALIDNAME = word32ToInt32 (0x800300FC ::Word32) sTG_E_INVALIDPARAMETER :: HRESULT sTG_E_INVALIDPARAMETER = word32ToInt32 (0x80030057 ::Word32) sTG_E_INVALIDPOINTER :: HRESULT sTG_E_INVALIDPOINTER = word32ToInt32 (0x80030009 ::Word32) sTG_E_LOCKVIOLATION :: HRESULT sTG_E_LOCKVIOLATION = word32ToInt32 (0x80030021 ::Word32) sTG_E_MEDIUMFULL :: HRESULT sTG_E_MEDIUMFULL = word32ToInt32 (0x80030070 ::Word32) sTG_E_NOMOREFILES :: HRESULT sTG_E_NOMOREFILES = word32ToInt32 (0x80030012 ::Word32) sTG_E_NOTCURRENT :: HRESULT sTG_E_NOTCURRENT = word32ToInt32 (0x80030101 ::Word32) sTG_E_NOTFILEBASEDSTORAGE :: HRESULT sTG_E_NOTFILEBASEDSTORAGE = word32ToInt32 (0x80030107 ::Word32) sTG_E_OLDDLL :: HRESULT sTG_E_OLDDLL = word32ToInt32 (0x80030105 ::Word32) sTG_E_OLDFORMAT :: HRESULT sTG_E_OLDFORMAT = word32ToInt32 (0x80030104 ::Word32) sTG_E_PATHNOTFOUND :: HRESULT sTG_E_PATHNOTFOUND = word32ToInt32 (0x80030003 ::Word32) sTG_E_PROPSETMISMATCHED :: HRESULT sTG_E_PROPSETMISMATCHED = word32ToInt32 (0x800300F0 ::Word32) sTG_E_READFAULT :: HRESULT sTG_E_READFAULT = word32ToInt32 (0x8003001E ::Word32) sTG_E_REVERTED :: HRESULT sTG_E_REVERTED = word32ToInt32 (0x80030102 ::Word32) sTG_E_SEEKERROR :: HRESULT sTG_E_SEEKERROR = word32ToInt32 (0x80030019 ::Word32) sTG_E_SHAREREQUIRED :: HRESULT sTG_E_SHAREREQUIRED = word32ToInt32 (0x80030106 ::Word32) sTG_E_SHAREVIOLATION :: HRESULT sTG_E_SHAREVIOLATION = word32ToInt32 (0x80030020 ::Word32) sTG_E_TERMINATED :: HRESULT sTG_E_TERMINATED = word32ToInt32 (0x80030202 ::Word32) sTG_E_TOOMANYOPENFILES :: HRESULT sTG_E_TOOMANYOPENFILES = word32ToInt32 (0x80030004 ::Word32) sTG_E_UNIMPLEMENTEDFUNCTION :: HRESULT sTG_E_UNIMPLEMENTEDFUNCTION = word32ToInt32 (0x800300FE ::Word32) sTG_E_UNKNOWN :: HRESULT sTG_E_UNKNOWN = word32ToInt32 (0x800300FD ::Word32) sTG_E_WRITEFAULT :: HRESULT sTG_E_WRITEFAULT = word32ToInt32 (0x8003001D ::Word32) sTG_S_BLOCK :: HRESULT sTG_S_BLOCK = word32ToInt32 (0x00030201 ::Word32) sTG_S_CANNOTCONSOLIDATE :: HRESULT sTG_S_CANNOTCONSOLIDATE = word32ToInt32 (0x00030206 ::Word32) sTG_S_CONSOLIDATIONFAILED :: HRESULT sTG_S_CONSOLIDATIONFAILED = word32ToInt32 (0x00030205 ::Word32) sTG_S_CONVERTED :: HRESULT sTG_S_CONVERTED = word32ToInt32 (0x00030200 ::Word32) sTG_S_MONITORING :: HRESULT sTG_S_MONITORING = word32ToInt32 (0x00030203 ::Word32) sTG_S_MULTIPLEOPENS :: HRESULT sTG_S_MULTIPLEOPENS = word32ToInt32 (0x00030204 ::Word32) sTG_S_RETRYNOW :: HRESULT sTG_S_RETRYNOW = word32ToInt32 (0x00030202 ::Word32) tYPE_E_AMBIGUOUSNAME :: HRESULT tYPE_E_AMBIGUOUSNAME = word32ToInt32 (0x8002802C ::Word32) tYPE_E_BADMODULEKIND :: HRESULT tYPE_E_BADMODULEKIND = word32ToInt32 (0x800288BD ::Word32) tYPE_E_BUFFERTOOSMALL :: HRESULT tYPE_E_BUFFERTOOSMALL = word32ToInt32 (0x80028016 ::Word32) tYPE_E_CANTCREATETMPFILE :: HRESULT tYPE_E_CANTCREATETMPFILE = word32ToInt32 (0x80028CA3 ::Word32) tYPE_E_CANTLOADLIBRARY :: HRESULT tYPE_E_CANTLOADLIBRARY = word32ToInt32 (0x80029C4A ::Word32) tYPE_E_CIRCULARTYPE :: HRESULT tYPE_E_CIRCULARTYPE = word32ToInt32 (0x80029C84 ::Word32) tYPE_E_DLLFUNCTIONNOTFOUND :: HRESULT tYPE_E_DLLFUNCTIONNOTFOUND = word32ToInt32 (0x8002802F ::Word32) tYPE_E_DUPLICATEID :: HRESULT tYPE_E_DUPLICATEID = word32ToInt32 (0x800288C6 ::Word32) tYPE_E_ELEMENTNOTFOUND :: HRESULT tYPE_E_ELEMENTNOTFOUND = word32ToInt32 (0x8002802B ::Word32) tYPE_E_FIELDNOTFOUND :: HRESULT tYPE_E_FIELDNOTFOUND = word32ToInt32 (0x80028017 ::Word32) tYPE_E_INCONSISTENTPROPFUNCS :: HRESULT tYPE_E_INCONSISTENTPROPFUNCS = word32ToInt32 (0x80029C83 ::Word32) tYPE_E_INVALIDID :: HRESULT tYPE_E_INVALIDID = word32ToInt32 (0x800288CF ::Word32) tYPE_E_INVALIDSTATE :: HRESULT tYPE_E_INVALIDSTATE = word32ToInt32 (0x80028029 ::Word32) tYPE_E_INVDATAREAD :: HRESULT tYPE_E_INVDATAREAD = word32ToInt32 (0x80028018 ::Word32) tYPE_E_IOERROR :: HRESULT tYPE_E_IOERROR = word32ToInt32 (0x80028CA2 ::Word32) tYPE_E_LIBNOTREGISTERED :: HRESULT tYPE_E_LIBNOTREGISTERED = word32ToInt32 (0x8002801D ::Word32) tYPE_E_NAMECONFLICT :: HRESULT tYPE_E_NAMECONFLICT = word32ToInt32 (0x8002802D ::Word32) tYPE_E_OUTOFBOUNDS :: HRESULT tYPE_E_OUTOFBOUNDS = word32ToInt32 (0x80028CA1 ::Word32) tYPE_E_QUALIFIEDNAMEDISALLOWED :: HRESULT tYPE_E_QUALIFIEDNAMEDISALLOWED = word32ToInt32 (0x80028028 ::Word32) tYPE_E_REGISTRYACCESS :: HRESULT tYPE_E_REGISTRYACCESS = word32ToInt32 (0x8002801C ::Word32) tYPE_E_SIZETOOBIG :: HRESULT tYPE_E_SIZETOOBIG = word32ToInt32 (0x800288C5 ::Word32) tYPE_E_TYPEMISMATCH :: HRESULT tYPE_E_TYPEMISMATCH = word32ToInt32 (0x80028CA0 ::Word32) tYPE_E_UNDEFINEDTYPE :: HRESULT tYPE_E_UNDEFINEDTYPE = word32ToInt32 (0x80028027 ::Word32) tYPE_E_UNKNOWNLCID :: HRESULT tYPE_E_UNKNOWNLCID = word32ToInt32 (0x8002802E ::Word32) tYPE_E_UNSUPFORMAT :: HRESULT tYPE_E_UNSUPFORMAT = word32ToInt32 (0x80028019 ::Word32) tYPE_E_WRONGTYPEKIND :: HRESULT tYPE_E_WRONGTYPEKIND = word32ToInt32 (0x8002802A ::Word32) vIEW_E_DRAW :: HRESULT vIEW_E_DRAW = word32ToInt32 (0x80040140 ::Word32) vIEW_E_FIRST :: HRESULT vIEW_E_FIRST = word32ToInt32 (0x80040140 ::Word32) vIEW_E_LAST :: HRESULT vIEW_E_LAST = word32ToInt32 (0x8004014F ::Word32) vIEW_S_ALREADY_FROZEN :: HRESULT vIEW_S_ALREADY_FROZEN = word32ToInt32 (0x00040140 ::Word32) vIEW_S_FIRST :: HRESULT vIEW_S_FIRST = word32ToInt32 (0x00040140 ::Word32) vIEW_S_LAST :: HRESULT vIEW_S_LAST = word32ToInt32 (0x0004014F ::Word32)
HJvT/com
System/Win32/Com/Exception.hs
Haskell
bsd-3-clause
32,564
-- | -- Module : Crypto.Cipher.Types -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : Stable -- Portability : Excellent -- -- symmetric cipher basic types -- module Crypto.Internal ( -- * Key type and constructor KeyError(..) , Key(..) , makeKey -- * pack/unpack , myPack , myUnpack ) where import Data.Char (ord,chr) -- | Create a Key for a specified cipher makeKey :: String -> Key makeKey b' = either (error . show) id key where b = myUnpack b' smLen = length b key :: Either KeyError Key key | smLen < 6 = Left KeyErrorTooSmall | smLen > 56 = Left KeyErrorTooBig | otherwise = Right $ Key b -- | Possible Error that can be reported when initializating a key data KeyError = KeyErrorTooSmall | KeyErrorTooBig deriving (Show,Eq) -- | a Key parametrized by the cipher newtype Key = Key [Int] deriving (Eq) myPack :: [Int] -> String myPack = map chr myUnpack :: String -> [Int] myUnpack = map (fromIntegral . ord)
jonathankochems/hs-crypto-cipher
src/Crypto/Internal.hs
Haskell
bsd-3-clause
1,085
-- Copyright © 2010 Greg Weber and Bart Massey -- [This program is licensed under the "3-clause ('new') BSD License"] -- Please see the file COPYING in this distribution for license information. -- | Read a spelling dictionary. module Text.SpellingSuggest.Dictionary ( defaultDictionary, readDictionary ) where import Data.Maybe import System.IO -- | File path for default dictionary. defaultDictionary :: String defaultDictionary = "/usr/share/dict/words" -- | Read the words out of the dictionary at the given -- path. XXX Will leak a file handle until/unless it is -- finalized, since there's no non-trivial way to arrange -- for the dictionary file to be closed explicitly. readDictionary :: Maybe String -> IO [String] readDictionary dictPath = do wf <- flip openFile ReadMode $ fromMaybe defaultDictionary dictPath hSetEncoding wf utf8 wc <- hGetContents wf return $ lines wc
gregwebs/haskell-spell-suggest
Text/SpellingSuggest/Dictionary.hs
Haskell
bsd-3-clause
899
module Main where import Ivory.Tower.Options import Tower.AADL import Ivory.Tower.Config import Tower.AADL.Build.Common import Tower.AADL.Build.EChronos import Ivory.BSP.STM32.Config import BSP.Tests.Platforms import BSP.Tests.LED.TestApp (app) main :: IO () main = compileTowerAADLForPlatform f p $ do app testplatform_leds where f :: TestPlatform -> (AADLConfig, OSSpecific STM32Config) f tp = ( defaultAADLConfig { configSystemOS = EChronos , configSystemHW = PIXHAWK } , defaultEChronosOS (testplatform_stm32 tp) ) p :: TOpts -> IO TestPlatform p topts = fmap fst (getConfig' topts testPlatformParser)
GaloisInc/ivory-tower-stm32
ivory-bsp-tests/tests/LEDAADLTest.hs
Haskell
bsd-3-clause
704
{-# LANGUAGE OverloadedStrings #-} import Test.Hspec import Test.QuickCheck import Flux main = hspec $ do describe "The delegation graph" $ it "Should have size 0 when empty" $ do graphSize emptyGraph `shouldBe` 0 -- adding and removing a voter is a no-op -- adding a voter is idempotent -- removing a voter is idempotent -- graph always meets internal invariants instance Arbitrary VoterId where arbitrary = VoterId <$> choose (0,9)
timbod7/flux-model
test/Spec.hs
Haskell
bsd-3-clause
477
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE BangPatterns #-} module Sky.Parsing.Invertible3.Isomorphism where import Prelude hiding (id, (.)) import Data.Data (Data) import Data.Proxy (Proxy(..)) import Control.Category (Category(..)) import Sky.Parsing.Invertible3.PartialType -- import Data.Function ((&)) -- import Debug.Trace ---------------------------------------------------------------------------------------------------- -- class IsoError e where -- errorComposition :: Iso e b c -> Iso e a b -> e -- showError :: e -> String class Category i => Isomorphism i where apply :: i s a -> s -> a unapply :: i s a -> a -> s reverseIso :: i s a -> i a s addIso :: (Data s) => i s a -> i s b -> i s (Either a b) ---------------------------------------------------------------------------------------------------- -- Implementation: Errors data IsoError = CompositionError { codomainLeft :: PartialType' , domainRight :: PartialType' } | IsoAdditionError { domain1 :: PartialType' , domain2 :: PartialType' } -- instance IsoError DefaultIsoError where -- errorComposition isoBC isoAB = CompositionError (_codomain isoAB) (_domain isoBC) -- showError (CompositionError codom dom) = "Iso composition domain mismatch: " ++ show codom ++ " vs " ++ show dom errorComposition :: Iso b c -> Iso a b -> IsoError errorComposition isoBC isoAB = CompositionError (_codomain isoAB) (_domain isoBC) errorAddition :: Iso s a -> Iso s b -> IsoError errorAddition isoS1A isoS2B = IsoAdditionError (_domain isoS1A) (_domain isoS2B) --err = error $ "Iso sum domain clash: " ++ show (_domain isoS1A) ++ " vs " ++ show (_domain isoS2B) showError :: IsoError -> String showError (CompositionError codom dom) = "Isomorphisms mismatch on composition:\n" ++ " The codomain of the first isomorphism:\n" ++ " " ++ show codom ++ "\n" ++ " doesn't match the domain of the second:\n" ++ " " ++ show dom ++ "\n" showError (IsoAdditionError dom1 dom2) = "Isomorphisms mismatch on addition:\n" ++ " The domain of the first isomorphism:\n" ++ " " ++ show dom1 ++ "\n" ++ " is not disjunct from the the domain of the second:\n" ++ " " ++ show dom2 ++ "\n" --throwError :: IsoError e => e -> a throwError :: IsoError -> a throwError e = error $ showError e ---------------------------------------------------------------------------------------------------- -- Implementation: Iso data Iso s a = Iso { _rawIso :: (s -> a, a -> s) , _domain :: PartialType s , _codomain :: PartialType a } | Error IsoError instance Category (Iso) where id :: Iso a a id = iso id id (.) :: Iso b c -> Iso a b -> Iso a c (.) (Error e) _ = Error e (.) _ (Error e) = Error e (.) !isoBC !isoAB = if check then isoAC else err where check = _codomain isoAB == _domain isoBC -- & ( trace $ "Check " ++ (show $ _codomain isoAB) ++ " == " ++ (show $ _domain isoBC) ) err = Error $ errorComposition isoBC isoAB (bmc, cmb) = _rawIso isoBC (amb, bma) = _rawIso isoAB amc = bmc . amb cma = bma . cmb isoAC = Iso (amc, cma) (_domain isoAB) (_codomain isoBC) instance Isomorphism (Iso) where apply (Error e) = throwError e apply (Iso (forward, _) _ _) = forward unapply (Error e) = throwError e unapply (Iso (_, backward) _ _) = backward reverseIso (Error e) = Error e reverseIso (Iso (f, b) d c) = Iso (b, f) c d addIso :: forall s a b. (Data s) => Iso s a -> Iso s b -> Iso s (Either a b) addIso (Error e) _ = Error e addIso _ (Error e) = Error e addIso isoS1A isoS2B = if check then Iso (forward, backward) newDomain newCodomain else err where check = disjunct (_domain isoS1A) (_domain isoS2B) err = Error $ errorAddition isoS1A isoS2B newDomain = (_domain isoS1A) `union` (_domain isoS2B) newCodomain = basicType (Proxy :: Proxy (Either a b)) forward :: s -> Either a b forward v = if v `isOfType` _domain isoS1A then Left $ apply isoS1A v else Right $ apply isoS2B v backward :: Either a b -> s backward (Left b1) = unapply isoS1A b1 backward (Right b2) = unapply isoS2B b2 ---------------------------------------------------------------------------------------------------- -- Simple total iso iso :: (s -> a) -> (a -> s) -> Iso s a iso forward backward = Iso (forward, backward) (basicType (Proxy :: Proxy s)) (basicType (Proxy :: Proxy a)) -- Construction from a data constructor: Partial on the left data type (s) partialIso :: forall e s a. (Data s) => s -> (s -> a) -> (a -> s) -> Iso s a partialIso dConstr forward backward = Iso (forward, backward) (partialAlgebraicType dConstr) (basicType (Proxy :: Proxy a)) -- Construction from a data constructor: Partial on the right data type (s) partialIsoR :: forall e s a. (Data a) => a -> (s -> a) -> (a -> s) -> Iso s a partialIsoR dConstr forward backward = Iso (forward, backward) (basicType (Proxy :: Proxy s)) (partialAlgebraicType dConstr) --partialIsoR dConstr forward backward = reverseIso $ partialIso dConstr backward forward ---------------------------------------------------------------------------------------------------- -- For invertible syntax parsing we need: -- A "failure" isomorphism -- TODO: The "parser" side should not accept anything, this still has to compose (e.g. with alt) isoFail :: String -> Iso a b isoFail e = iso (error e) (error e) -- An isomorphism between fixed values (i.e. "pure" & "token" for the parser) isoPure :: s -> a -> Iso s a isoPure s a = iso (const a) (const s) -- Alternative choice: Having parsed either "s" or "t", generate "a" -- this is just "addIso" for the partial isos above! (reversed, in this case) isoAlt :: (Data a) => Iso s a -> Iso t a -> Iso (Either s t) a isoAlt sa ta = reverseIso $ addIso (reverseIso sa) (reverseIso ta) -- Sequential combination -- TODO: Parse side needs to be able to make a choice (for determinism) isoSeq :: Iso [s] a -> Iso [s] b -> Iso [s] (a, b) isoSeq lsa lsb = error $ "TODO" -- Because it happens a lot and haskell would "do it wrong": isoSeqL :: Iso [s] a -> Iso [s] () -> Iso [s] a isoSeqL lsa lsb = error $ "TODO" isoSeqR :: Iso [s] () -> Iso [s] b -> Iso [s] b isoSeqR lsa lsb = error $ "TODO" ---------------------------------------------------------------------------------------------------- -- Debug checkIso :: Iso a b -> Iso a b checkIso (Error e) = throwError e checkIso iso = iso instance Show (Iso a b) where show (Error e) = showError e show _ = "Iso (FIXME)"
xicesky/sky-haskell-playground
src/Sky/Parsing/Invertible3/Isomorphism.hs
Haskell
bsd-3-clause
6,820
module WildBind.ForTest ( SampleInput(..), SampleState(..), SampleBackState(..), inputAll, execAll, evalStateEmpty, boundDescs, boundDescs', curBoundInputs, curBoundDescs, curBoundDesc, checkBoundInputs, checkBoundDescs, checkBoundDesc, withRefChecker ) where import Control.Applicative ((<$>), (<*>), pure) import Control.Monad (join) import Control.Monad.IO.Class (liftIO, MonadIO) import qualified Control.Monad.Trans.State as State import Data.IORef (IORef, newIORef, readIORef) import Data.Monoid (mempty) import Test.QuickCheck (Arbitrary(arbitrary,shrink), arbitraryBoundedEnum) import Test.Hspec (shouldReturn, shouldMatchList, shouldBe) import qualified WildBind.Binding as WB import qualified WildBind.Description as WBD data SampleInput = SIa | SIb | SIc deriving (Show, Eq, Ord, Enum, Bounded) instance Arbitrary SampleInput where arbitrary = arbitraryBoundedEnum data SampleState = SS { unSS :: String } deriving (Show, Eq, Ord) instance Arbitrary SampleState where arbitrary = SS <$> arbitrary shrink (SS s) = SS <$> shrink s data SampleBackState = SB { unSB :: Int } deriving (Show, Eq, Ord) instance Enum SampleBackState where toEnum = SB fromEnum = unSB inputAll :: Ord i => WB.Binding s i -> s -> [i] -> IO (WB.Binding s i) inputAll b _ [] = return b inputAll binding state (i:rest) = case WB.boundAction binding state i of Nothing -> inputAll binding state rest Just act -> join $ inputAll <$> WB.actDo act <*> return state <*> return rest execAll :: Ord i => s -> [i] -> State.StateT (WB.Binding s i) IO () execAll state inputs = do b <- State.get next_b <- liftIO $ inputAll b state inputs State.put next_b evalStateEmpty :: State.StateT (WB.Binding SampleState SampleInput) IO () -> IO () evalStateEmpty s = State.evalStateT s mempty toDesc :: (i, WB.Action m a) -> (i, WBD.ActionDescription) toDesc (i, act) = (i, WB.actDescription act) boundDescs :: WB.Binding s i -> s -> [(i, WBD.ActionDescription)] boundDescs b s = map toDesc $ WB.boundActions b s boundDescs' :: WB.Binding' bs fs i -> bs -> fs -> [(i, WBD.ActionDescription)] boundDescs' b bs fs = map toDesc $ WB.boundActions' b bs fs curBoundInputs :: s -> State.StateT (WB.Binding s i) IO [i] curBoundInputs s = State.gets WB.boundInputs <*> pure s curBoundDescs :: s -> State.StateT (WB.Binding s i) IO [(i, WBD.ActionDescription)] curBoundDescs s = State.gets boundDescs <*> pure s curBoundDesc :: Ord i => s -> i -> State.StateT (WB.Binding s i) IO (Maybe WBD.ActionDescription) curBoundDesc s i = (fmap . fmap) WB.actDescription $ State.gets WB.boundAction <*> pure s <*> pure i checkBoundInputs :: (Eq i, Show i) => s -> [i] -> State.StateT (WB.Binding s i) IO () checkBoundInputs fs expected = liftIO . (`shouldMatchList` expected) =<< curBoundInputs fs checkBoundDescs :: (Eq i, Show i) => s -> [(i, WBD.ActionDescription)] -> State.StateT (WB.Binding s i) IO () checkBoundDescs fs expected = liftIO . (`shouldMatchList` expected) =<< curBoundDescs fs checkBoundDesc :: (Ord i) => s -> i -> WBD.ActionDescription -> State.StateT (WB.Binding s i) IO () checkBoundDesc fs input expected = liftIO . (`shouldBe` Just expected) =<< curBoundDesc fs input withRefChecker :: (Eq a, Show a, MonadIO m) => a -> (IORef a -> (a -> m ()) -> m ()) -> m () withRefChecker init_ref action = do out <- liftIO $ newIORef init_ref let checkOut expected = liftIO $ readIORef out `shouldReturn` expected action out checkOut
debug-ito/wild-bind
wild-bind/test/WildBind/ForTest.hs
Haskell
bsd-3-clause
3,683
module GLogger.Client ( initLogger, cleanLog, logDebug, logInfo, logNotice, logWarning, logError, logCritical, logAlert, logEmergency ) where import qualified System.Log.Logger as SL import System.Log.Handler.Simple (fileHandler) import System.Log.Handler (setFormatter) import System.Log.Formatter (tfLogFormatter) import System.IO (withFile, IOMode(..)) import Control.Monad (when) logFileName :: String logFileName = "client.log" loggerName :: String loggerName = "clientLogger" enableLogging :: Bool enableLogging = True initLogger :: IO () initLogger = when enableLogging $ do h <- fileHandler logFileName SL.DEBUG >>= \lh -> return $ setFormatter lh (tfLogFormatter "%T:%q" "[$time: $loggername : $prio] $msg") SL.updateGlobalLogger loggerName (SL.setLevel SL.DEBUG) SL.updateGlobalLogger loggerName (SL.addHandler h) cleanLog :: IO () cleanLog = when enableLogging $ do withFile logFileName WriteMode (\_ -> return ()) logDebug :: String -> IO () logDebug string = when enableLogging $ do SL.debugM loggerName string logInfo :: String -> IO () logInfo string = when enableLogging $ do SL.infoM loggerName string logNotice :: String -> IO () logNotice string = when enableLogging $ do SL.noticeM loggerName string logWarning :: String -> IO () logWarning string = when enableLogging $ do SL.warningM loggerName string logError :: String -> IO () logError string = when enableLogging $ do SL.errorM loggerName string logCritical :: String -> IO () logCritical string = when enableLogging $ do SL.criticalM loggerName string logAlert :: String -> IO () logAlert string = when enableLogging $ do SL.alertM loggerName string logEmergency :: String -> IO () logEmergency string = when enableLogging $ do SL.emergencyM loggerName string
cernat-catalin/haskellGame
src/GLogger/Client.hs
Haskell
bsd-3-clause
1,815
{-# LANGUAGE ViewPatterns #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Actions.FocusNth -- Description : Focus the nth window of the current workspace. -- Copyright : (c) Karsten Schoelzel <kuser@gmx.de> -- License : BSD -- -- Maintainer : Karsten Schoelzel <kuser@gmx.de> -- Stability : stable -- Portability : unportable -- -- Focus the nth window of the current workspace. ----------------------------------------------------------------------------- module XMonad.Actions.FocusNth ( -- * Usage -- $usage focusNth,focusNth', swapNth,swapNth') where import XMonad import XMonad.Prelude import XMonad.StackSet -- $usage -- Add the import to your @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Actions.FocusNth -- -- Then add appropriate keybindings, for example: -- -- > -- mod4-[1..9] @@ Switch to window N -- > ++ [((modm, k), focusNth i) -- > | (i, k) <- zip [0 .. 8] [xK_1 ..]] -- -- For detailed instructions on editing your key bindings, see -- "XMonad.Doc.Extending#Editing_key_bindings". -- | Give focus to the nth window of the current workspace. focusNth :: Int -> X () focusNth = windows . modify' . focusNth' focusNth' :: Int -> Stack a -> Stack a focusNth' n s | n >= 0, (ls, t:rs) <- splitAt n (integrate s) = Stack t (reverse ls) rs | otherwise = s -- | Swap current window with nth. Focus stays in the same position swapNth :: Int -> X () swapNth = windows . modify' . swapNth' swapNth' :: Int -> Stack a -> Stack a swapNth' n s@(Stack c l r) | (n < 0) || (n > length l + length r) || (n == length l) = s | n < length l = let (nl, notEmpty -> nc :| nr) = splitAt (length l - n - 1) l in Stack nc (nl ++ c : nr) r | otherwise = let (nl, notEmpty -> nc :| nr) = splitAt (n - length l - 1) r in Stack nc l (nl ++ c : nr)
xmonad/xmonad-contrib
XMonad/Actions/FocusNth.hs
Haskell
bsd-3-clause
1,920
module Language.Haskell.Liquid.Bare.SymSort ( txRefSort ) where import Control.Applicative ((<$>)) import qualified Data.List as L import Language.Fixpoint.Misc (errorstar, safeZip, fst3, snd3) import Language.Fixpoint.Types (meet) import Language.Haskell.Liquid.Types.RefType (appRTyCon, strengthen) import Language.Haskell.Liquid.Types import Language.Haskell.Liquid.Misc (safeZipWithError) -- EFFECTS: TODO is this the SAME as addTyConInfo? No. `txRefSort` -- (1) adds the _real_ sorts to RProp, -- (2) gathers _extra_ RProp at turnst them into refinements, -- e.g. tests/pos/multi-pred-app-00.hs txRefSort tyi tce = mapBot (addSymSort tce tyi) addSymSort tce tyi (RApp rc@(RTyCon _ _ _) ts rs r) = RApp rc ts (zipWith3 (addSymSortRef rc) pvs rargs [1..]) r' where rc' = appRTyCon tce tyi rc ts pvs = rTyConPVs rc' (rargs, rrest) = splitAt (length pvs) rs r' = L.foldl' go r rrest go r (RProp _ (RHole r')) = r' `meet` r go r (RProp _ _ ) = r -- is this correct? addSymSort _ _ t = t addSymSortRef rc p r i | isPropPV p = addSymSortRef' rc i p r | otherwise = errorstar "addSymSortRef: malformed ref application" addSymSortRef' _ _ p (RProp s (RVar v r)) | isDummy v = RProp xs t where t = ofRSort (pvType p) `strengthen` r xs = spliceArgs "addSymSortRef 1" s p addSymSortRef' rc i p (RProp _ (RHole r@(MkUReft _ (Pr [up]) _))) = RProp xts (RHole r) -- (ofRSort (pvType p) `strengthen` r) where xts = safeZipWithError msg xs ts xs = snd3 <$> pargs up ts = fst3 <$> pargs p msg = intToString i ++ " argument of " ++ show rc ++ " is " ++ show (pname up) ++ " that expects " ++ show (length ts) ++ " arguments, but it has " ++ show (length xs) addSymSortRef' _ _ _ (RProp s (RHole r)) = RProp s (RHole r) -- (ofRSort (pvType p) `strengthen` r) addSymSortRef' _ _ p (RProp s t) = RProp xs t where xs = spliceArgs "addSymSortRef 2" s p spliceArgs msg s p = safeZip msg (fst <$> s) (fst3 <$> pargs p) intToString 1 = "1st" intToString 2 = "2nd" intToString 3 = "3rd" intToString n = show n ++ "th"
abakst/liquidhaskell
src/Language/Haskell/Liquid/Bare/SymSort.hs
Haskell
bsd-3-clause
2,198
{- Copyright (C) 2012-2017 Kacper Bak, Jimmy Liang, Michal Antkiewicz <http://gsd.uwaterloo.ca> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} {-# LANGUAGE DeriveDataTypeable, NamedFieldPuns #-} module Main where import Prelude hiding (writeFile, readFile, print, putStrLn) import Data.Functor (void) import System.IO import System.Timeout import System.Process (system) import Language.Clafer main :: IO () main = do (args', model) <- mainArgs let timeInSec = (timeout_analysis args') * 10^(6::Integer) if timeInSec > 0 then timeout timeInSec $ start args' model else Just `fmap` start args' model return () start :: ClaferArgs -> InputModel-> IO () start args' model = if ecore2clafer args' then runEcore2Clafer (file args') $ (tooldir args') else runCompiler Nothing args' model runEcore2Clafer :: FilePath -> FilePath -> IO () runEcore2Clafer ecoreFile toolPath | null ecoreFile = do putStrLn "Error: Provide a file name of an ECore model." | otherwise = do putStrLn $ "Converting " ++ ecoreFile ++ " into Clafer" void $ system $ "java -jar " ++ toolPath ++ "/ecore2clafer.jar " ++ ecoreFile
juodaspaulius/clafer
src-cmd/clafer.hs
Haskell
mit
2,148
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Book ( Book (..) , Part (..) , Chapter (..) , loadBook ) where import Control.Exception (SomeException, evaluate, handle, throw) import Control.Monad (when) import Control.Monad.IO.Class (MonadIO (liftIO)) import Control.Monad.Trans.Resource import Control.Monad.Trans.Writer import qualified Data.ByteString.Lazy as L import Data.Conduit import Data.Conduit.Binary (sourceFile) import qualified Data.Conduit.List as CL import qualified Data.Conduit.Text as CT import qualified Data.Map as Map import Data.Maybe (listToMaybe, mapMaybe) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import qualified Filesystem as F import qualified Filesystem.Path.CurrentOS as F import Prelude import Text.Blaze.Html (Html, toHtml) import Text.Blaze.Html.Renderer.Utf8 (renderHtml) import Text.XML as X data Book = Book { bookParts :: [Part] , bookChapterMap :: Map.Map Text Chapter } data Part = Part { partTitle :: Text , partChapters :: [Chapter] } data Chapter = Chapter { chapterTitle :: Text , chapterPath :: F.FilePath , chapterSlug :: Text , chapterHtml :: Html } getTitle :: [Node] -> IO (Text, [Node]) getTitle = go id where go _ [] = error "Title not found" go front (NodeElement (Element "title" _ [NodeContent t]):rest) = return (t, front rest) go front (n:ns) = go (front . (n:)) ns mapWhile :: Monad m => (a -> Maybe b) -> Conduit a m b mapWhile f = loop where loop = await >>= maybe (return ()) go go x = case f x of Just y -> yield y >> loop Nothing -> leftover x data BookLine = Title Text | Include Text parseBookLine :: Text -> Maybe BookLine parseBookLine t | Just t' <- T.stripPrefix "= " t = Just $ Title t' | Just t' <- T.stripPrefix "include::chapters/" t >>= T.stripSuffix ".asciidoc[]" = Just $ Include t' | Just t' <- T.stripPrefix "include::" t >>= T.stripSuffix ".asciidoc[]" = Just $ Include t' | otherwise = Nothing loadBook :: F.FilePath -> IO Book loadBook dir = handle (\(e :: SomeException) -> return (throw e)) $ do fp <- trySuffixes [ "yesod-web-framework-book.asciidoc" , "asciidoc/book.asciidoc" ] parts <- runResourceT $ sourceFile (F.encodeString fp) $$ CT.decode CT.utf8 =$ CT.lines =$ CL.mapMaybe parseBookLine =$ (CL.drop 1 >> parseParts) =$ CL.consume let m = Map.fromList $ concatMap goP parts goC c = (chapterSlug c, c) goP = map goC . partChapters return $ Book parts m where trySuffixes [] = error "No suffixes worked for loading book" trySuffixes (x:xs) = do let fp = dir F.</> x exists <- F.isFile fp if exists then return fp else trySuffixes xs parseParts :: MonadIO m => Conduit BookLine m Part parseParts = start where start = await >>= maybe (return ()) start' start' (Title t) = do let getInclude (Include x) = Just x getInclude _ = Nothing chapters <- mapWhile getInclude =$= CL.mapM (liftIO . parseChapter) =$= CL.consume yield $ Part t chapters start start' (Include _t) = start -- error $ "Invalid beginning of a Part: " ++ show t ps = def { psDecodeEntities = decodeHtmlEntities } -- Read a chapter as an XML file, converting from AsciiDoc as necessary chapterToDoc fp' | F.hasExtension fp' "ad" || F.hasExtension fp' "asciidoc" = let fp'' = F.directory fp' F.</> "../generated-xml" F.</> F.replaceExtension (F.filename fp') "xml" in X.readFile ps $ F.encodeString fp'' | otherwise = X.readFile ps $ F.encodeString fp' getSection (NodeElement e@(Element "section" _ _)) = Just e getSection (NodeElement e@(Element "appendix" _ _)) = Just e getSection _ = Nothing parseChapter :: Text -> IO Chapter parseChapter slug = do let fp' = dir F.</> "generated-xml" F.</> F.fromText slug F.<.> "xml" Document _ (Element name _ csOrig) _ <- chapterToDoc fp' cs <- case name of "article" -> case listToMaybe $ mapMaybe getSection csOrig of Nothing -> error "article without child section" Just (Element _ _ cs) -> return cs "chapter" -> return csOrig _ -> error $ "Unknown root element: " ++ show name (title, rest) <- getTitle cs let content = mconcat $ map toHtml $ concatMap (goNode False) rest !_ <- evaluate $ L.length $ renderHtml content -- FIXME comment out to avoid eager error checking return $ Chapter title fp' slug content goNode :: Bool -> Node -> [Node] goNode b (NodeElement e) = goElem b e goNode _ n = [n] goElem :: Bool -- ^ inside figure? -> Element -> [Node] {- goElem _ (Element "apiname" _ [NodeContent t]) = goApiname t -} goElem _ (Element "programlisting" as [NodeContent t]) | Just "lhaskell" <- Map.lookup "language" as = goLHS t goElem _ (Element "programlisting" as [NodeContent t]) | Just "haskell" <- Map.lookup "language" as = [ NodeElement $ Element "pre" as [ NodeElement $ Element "code" (Map.singleton "class" $ T.unwords $ execWriter $ do tell ["haskell"] case filter ("main = " `T.isPrefixOf`) $ T.lines t of rest:_ -> do tell ["active"] when ("warp" `elem` T.words rest) $ tell ["web"] [] -> return () ) [ NodeContent $ goStartStop t ] ] ] goElem insideFigure (Element n as cs) {- | insideFigure && n == "h1" = [NodeElement $ Element "figcaption" as cs'] -} | nameLocalName n `Set.member` unchanged = [NodeElement $ Element n as cs'] | Just n' <- Map.lookup n simples = [NodeElement $ Element n' as cs'] | Just (n', clazz) <- Map.lookup n classes = [NodeElement $ Element n' (Map.insert "class" clazz as) cs'] | n `Set.member` deleted = [] | n `Set.member` stripped = cs' | n == "programlisting" = [NodeElement $ Element "pre" as [NodeElement $ Element "code" Map.empty cs']] | n == "imagedata" = goImage as cs' | n == "varlistentry" = goVarListEntry insideFigure cs | n == "ulink", Just url <- Map.lookup "url" as = [ NodeElement $ Element "a" (Map.delete "url" $ Map.insert "href" url as) cs' ] | otherwise = error $ "Unknown: " ++ show (nameLocalName n) where cs' = concatMap (goNode $ insideFigure || n == "figure") cs unchanged = Set.fromList $ T.words "section figure table tgroup thead tbody blockquote code" simples = Map.fromList [ ("para", "p") , ("simpara", "p") , ("emphasis", "em") , ("title", "h1") , ("itemizedlist", "ul") , ("orderedlist", "ol") , ("listitem", "li") , ("link", "a") , ("variablelist", "dl") , ("term", "dt") , ("literal", "code") , ("screen", "pre") , ("quote", "q") , ("row", "tr") , ("entry", "td") , ("citation", "cite") , ("literallayout", "pre") , ("informaltable", "table") , ("formalpara", "section") , ("attribution", "cite") ] {- , ("title", "h1") ] -} classes = Map.fromList [ ("glossterm", ("span", "term")) , ("function", ("span", "apiname")) , ("command", ("span", "cmdname")) , ("note", ("aside", "note")) , ("userinput", ("span", "userinput")) , ("varname", ("span", "varname")) , ("filename", ("span", "filepath")) ] {- , ("msgblock", ("pre", "msgblock")) ] -} deleted = Set.fromList [ "textobject" , "colspec" ] stripped = Set.fromList [ "mediaobject" , "imageobject" ] {- [ "conbody" , "dlentry" ] -} goVarListEntry insideFigure = concatMap go where go (NodeElement (Element "term" _ cs)) = [ NodeElement $ Element "dt" Map.empty $ concatMap (goNode insideFigure) cs ] go (NodeElement (Element "listitem" _ cs)) = [ NodeElement $ Element "dd" Map.empty $ concatMap (goNode insideFigure) cs ] go _ = [] goStartStop t | "-- START" `elem` ls = T.unlines $ go False ls | otherwise = t where ls = T.lines t go _ [] = [] go _ ("-- START":xs) = go True xs go _ ("-- STOP":xs) = go False xs go True (x:xs) = x : go True xs go False (_:xs) = go False xs goLHS t0 = map go lhBlocks where ls = T.lines t0 lhLines = map lhLine ls lhBlocks = map (fmap T.unlines) $ toBlocks lhLines go (LHCode t) = NodeElement $ Element "pre" Map.empty [NodeElement $ Element "code" Map.empty [NodeContent t]] go (LHText t) = NodeElement $ Element "p" (Map.singleton "style" "white-space:pre") [NodeContent t] goImage as cs = [NodeElement $ Element "img" (Map.singleton "src" href') cs] where href' = case Map.lookup "fileref" as of Just href -> let name = either id id $ F.toText $ F.basename $ F.fromText href in T.append "image/" name Nothing -> error "image without href" data LHask t = LHCode t | LHText t instance Functor LHask where fmap f (LHCode x) = LHCode (f x) fmap f (LHText x) = LHText (f x) lhLine :: Text -> LHask [Text] lhLine t = case T.stripPrefix "> " t of Nothing -> LHText [t] Just s -> LHCode [s] toBlocks :: [LHask [Text]] -> [LHask [Text]] toBlocks [] = [] toBlocks (LHCode x:LHCode y:rest) = toBlocks $ LHCode (x ++ y) : rest toBlocks (LHText x:LHText y:rest) = toBlocks $ LHText (x ++ y) : rest toBlocks (x:rest) = x : toBlocks rest
wolftune/yesodweb.com
Book.hs
Haskell
bsd-2-clause
10,973
-- print2.hs module Print2 where main :: IO () main = do putStrLn "Count to four for me:" putStr "one, two" putStr ", three, and" putStrLn " four!"
OCExercise/haskellbook-solutions
chapters/chapter03/scratch/print2.hs
Haskell
bsd-2-clause
169
{-# LANGUAGE CPP #-} {-# LANGUAGE ScopedTypeVariables #-} #if __GLASGOW_HASKELL__ >= 701 {-# LANGUAGE Trustworthy #-} #endif -- | -- Copyright : (c) 2010 Simon Meier -- -- License : BSD3-style (see LICENSE) -- -- Maintainer : Simon Meier <iridcode@gmail.com> -- Stability : experimental -- Portability : GHC -- -- Conversion of 'Float's and 'Double's to 'Word32's and 'Word64's. -- module Data.ByteString.Builder.Prim.Internal.Floating ( -- coerceFloatToWord32 -- , coerceDoubleToWord64 encodeFloatViaWord32F , encodeDoubleViaWord64F ) where import Foreign import Data.ByteString.Builder.Prim.Internal {- We work around ticket http://ghc.haskell.org/trac/ghc/ticket/4092 using the FFI to store the Float/Double in the buffer and peek it out again from there. -} -- | Encode a 'Float' using a 'Word32' encoding. -- -- PRE: The 'Word32' encoding must have a size of at least 4 bytes. {-# INLINE encodeFloatViaWord32F #-} encodeFloatViaWord32F :: FixedPrim Word32 -> FixedPrim Float encodeFloatViaWord32F w32fe | size w32fe < sizeOf (undefined :: Float) = error $ "encodeFloatViaWord32F: encoding not wide enough" | otherwise = fixedPrim (size w32fe) $ \x op -> do poke (castPtr op) x x' <- peek (castPtr op) runF w32fe x' op -- | Encode a 'Double' using a 'Word64' encoding. -- -- PRE: The 'Word64' encoding must have a size of at least 8 bytes. {-# INLINE encodeDoubleViaWord64F #-} encodeDoubleViaWord64F :: FixedPrim Word64 -> FixedPrim Double encodeDoubleViaWord64F w64fe | size w64fe < sizeOf (undefined :: Float) = error $ "encodeDoubleViaWord64F: encoding not wide enough" | otherwise = fixedPrim (size w64fe) $ \x op -> do poke (castPtr op) x x' <- peek (castPtr op) runF w64fe x' op
CloudI/CloudI
src/api/haskell/external/bytestring-0.10.10.0/Data/ByteString/Builder/Prim/Internal/Floating.hs
Haskell
mit
1,783
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Vimus.Command.Help ( Help (..) , help , commandShortHelp , commandHelpText ) where import Control.Monad import Data.Maybe import Data.String import Language.Haskell.TH import Language.Haskell.TH.Quote import Language.Haskell.TH.Syntax import Vimus.Command.Type import Vimus.Util (strip) -- | A `QuasiQuoter` for help text. help :: QuasiQuoter help = QuasiQuoter { quoteExp = lift . parseHelp , quotePat = error "Command.Help.help: quotePat is undefined!" , quoteType = error "Command.Help.help: quoteType is undefined!" , quoteDec = error "Command.Help.help: quoteDec is undefined!" } instance Lift Help where lift (Help xs) = AppE `fmap` [|Help|] `ap` lift xs instance IsString Help where fromString = parseHelp -- | Parse help text. parseHelp :: String -> Help parseHelp = Help . go . map strip . lines where go l = case dropWhile null l of [] -> [] xs -> let (ys, zs) = break null xs in (wordWrapping . unwords) ys ++ go zs -- | Apply automatic word wrapping. wordWrapping :: String -> [String] wordWrapping = run . words where -- we start each recursion step at 2, this makes sure that each step -- consumes at least one word run = go 2 go n xs | null xs = [] | 60 < length (unwords ys) = let (as, bs) = splitAt (pred n) xs in unwords as : run bs | null zs = [unwords ys] | otherwise = go (succ n) xs where (ys, zs) = splitAt n xs -- | The first line of the command description. commandShortHelp :: Command -> String commandShortHelp = fromMaybe "" . listToMaybe . unHelp . commandHelp_ commandHelpText :: Command -> [String] commandHelpText = unHelp . commandHelp_
haasn/vimus
src/Vimus/Command/Help.hs
Haskell
mit
1,881
module Control.Search.Combinator.Let (let', set') where import Control.Search.Language import Control.Search.GeneratorInfo import Control.Search.Generator import Control.Search.Stat stmPrefixLoop stm super = super { tryH = \i -> (stm i) @>>>@ (tryE super) i, startTryH = \i -> (stm i) @>>>@ (startTryH super) i, toString = "prefix(" ++ toString super ++ ")" } letLoop :: Evalable m => VarId -> Stat -> Eval m -> Eval m letLoop v@(VarId i) val super'' = let super' = evalStat val super'' super = super' { evalState_ = ("var" ++ (show i), Int, \i -> setVarInfo v i >> readStat val >>= \x -> return (x i)) : evalState_ super', toString = "let(" ++ show v ++ "," ++ show val ++ "," ++ toString super'' ++ ")" } in commentEval super let' :: VarId -> Stat -> Search -> Search let' var val s = case s of Search { mkeval = evals, runsearch = runs } -> Search { mkeval = \super -> do { ss <- evals super ; return $ letLoop var val ss } , runsearch = runs } set' :: VarId -> Stat -> Search -> Search set' var val s = case s of Search { mkeval = evals, runsearch = runs } -> Search { mkeval = \super -> do { ss <- evals super ; let ss1 = evalStat (varStat var) ss ; let ss2 = evalStat val ss1 ; return $ stmPrefixLoop (\i -> readStat (varStat var) >>= \rvar -> readStat val >>= \rval -> return $ Assign (rvar i) (rval i)) ss2 } , runsearch = runs }
neothemachine/monadiccp
src/Control/Search/Combinator/Let.hs
Haskell
bsd-3-clause
1,680
{-| Module : CSH.Eval.Cacheable.Make Description : Cacheable Actions to Create Objects Copyright : Stephen Demos, Matt Gambogi, Travis Whitaker, Computer Science House 2015 License : MIT Maintainer : pvals@csh.rit.edu Stability : Provisional Portability : POSIX CSH.Eval.Cacheable.Make defines 'Cacheable' computations for introducing state objects. -} {-# LANGUAGE OverloadedStrings #-} module CSH.Eval.Cacheable.Make ( -- * Object Instantiating Functions -- ** Member mkIntroMember , mkExtantMember -- ** Event , mkEvent -- ** Project , mkProject -- ** Evaluation , mkEvaluation -- ** Conditional , mkConditional -- ** FreshmanProject , mkFreshmanProject -- ** Packet , mkPacket -- ** Application , mkApplication -- ** Metric , mkMetric -- ** Review , mkReview -- ** Interview , mkInterview -- ** Question , mkQuestion -- ** Term , mkTerm -- * Context Instantiating Functions -- ** Eboard , grEboard -- ** Room , grRoom -- ** Queue , grQueue -- ** Membership , grMembership -- ** EventAttendee , grEventAttendee -- ** ProjectParticipant , grProjectParticipant -- ** FreshmanProjectParticipant , grFreshmanProjectParticipant -- ** Signature , grSignature -- ** ReviewMetric , grReviewMetric -- ** InterviewMetric , grInterviewMetric -- ** Answer , grAnswer -- ** Dues , grDues -- * ToRow Functions ) where import Data.Word import Data.UUID import Data.Time import qualified Data.ByteString as B import qualified Data.Text as T import CSH.Eval.Model import CSH.Eval.DB.Statements import CSH.Eval.Cacheable.Prim import CSH.Eval.Cacheable.Fetch mkIntroMember :: UUID -- ^ Member UUID. -> T.Text -- ^ Username. -> T.Text -- ^ Common name. -> B.ByteString -- ^ Passowrd hash. -> B.ByteString -- ^ Passowrd salt -> Cacheable () mkIntroMember uu u cn ph ps c = do mid <- liftInsertSingleQ (mkIntroMemberP uu u cn ph ps) c let m = Member mid uu u cn Nothing 0 False (getMemberEboards mid) (getMemberRooms mid) (getMemberMemberships mid) (getMemberEvaluations mid) (getMemberPackets mid) (getMemberQueues mid) (getMemberApplications mid) (getMemberDues mid) singletonGhost memberIDCache mid m c mkExtantMember :: UUID -- ^ Member UUID. -> T.Text -- ^ Username. -> T.Text -- ^ Common name. -> Int -- ^ Housing points. -> Bool -- ^ On floor status. -> Cacheable () mkExtantMember uu u cn hp os c = do mid <- liftInsertSingleQ (mkExtantMemberP uu u cn hp os) c let m = Member mid uu u cn Nothing hp os (getMemberEboards mid) (getMemberRooms mid) (getMemberMemberships mid) (getMemberEvaluations mid) (getMemberPackets mid) (getMemberQueues mid) (getMemberApplications mid) (getMemberDues mid) singletonGhost memberIDCache mid m c mkEvent :: T.Text -- ^ Title. -> UTCTime -- ^ Held time. -> EventType -- ^ Event type -> Committee -- ^ Event Committee -> T.Text -- ^ Description -> Cacheable () mkEvent t h et ec d c = do eid <- liftInsertSingleQ (mkEventP t h (eventTypeToVal et) (committeeToVal ec) d) c let e = Event eid t h et ec d (getEventEventAttendees eid) singletonGhost eventIDCache eid e c mkProject :: T.Text -- ^ Title. -> T.Text -- ^ Description. -> UTCTime -- ^ Submission time. -> Committee -- ^ Project committee. -> ProjectType -- ^ Project type. -> Cacheable () mkProject t d st pc pt c = do pid <- liftInsertSingleQ (mkProjectP t d st (committeeToVal pc) (projectTypeToVal pt)) c let p = Project pid t d st Nothing pc pt T.empty Pending (getProjectProjectParticipants pid) singletonGhost projectIDCache pid p c mkEvaluation :: Word64 -- ^ Member ID. -> UTCTime -- ^ Evaluation deadline. -> EvaluationType -- ^ Evaluation type. -> Cacheable () mkEvaluation mid t et c = do eid <- liftInsertSingleQ (mkEvaluationP mid t (evaluationTypeToVal et)) c let e = Evaluation eid T.empty t False Pending et (getMemberID mid) (getEvaluationConditionals eid) (getEvaluationFreshmanProjectParticipants eid) singletonGhost evaluationIDCache eid e c mkConditional :: Word64 -- ^ Evaluation ID. -> UTCTime -- ^ Due date. -> T.Text -- ^ Description. -> Cacheable () mkConditional eid dt d c = do cid <- liftInsertSingleQ (mkConditionalP eid dt d) c let c' = Conditional cid dt d T.empty (getEvaluationID eid) singletonGhost conditionalIDCache cid c' c mkFreshmanProject :: Word64 -- ^ Term ID. -> Word64 -- ^ Event ID. -> T.Text -- ^ Description. -> Cacheable () mkFreshmanProject tid eid d c = do fpid <- liftInsertSingleQ (mkFreshmanProjectP tid eid d) c let fp = FreshmanProject fpid d (getTermID tid) (getEventID eid) (getFreshmanProjectFreshmanProjectParticipants fpid) singletonGhost freshmanProjectIDCache fpid fp c mkPacket :: Word64 -- ^ Member ID. -> UTCTime -- ^ Due date. -> Int -- ^ Percent required. -> Cacheable () mkPacket mid d p c = do pid <- liftInsertSingleQ (mkPacketP mid d p) c let p' = Packet pid d p (getMemberID mid) (getPacketSignatures pid) singletonGhost packetIDCache pid p' c mkApplication :: Word64 -- ^ Member ID. -> UTCTime -- ^ Creation time. -> Cacheable () mkApplication mid t c = do aid <- liftInsertSingleQ (mkApplicationP mid t) c let a = Application aid t Pending (getMemberID mid) (getApplicationReviews aid) (getApplicationInterviews aid) (getApplicationAnswers aid) singletonGhost applicationIDCache aid a c mkMetric :: T.Text -- ^ Description. -> Cacheable () mkMetric d c = do mid <- liftInsertSingleQ (mkMetricP d) c let m = Metric mid d True singletonGhost metricIDCache mid m c mkReview :: Word64 -- ^ Member ID(reviewer). -> Word64 -- ^ Application ID. -> UTCTime -- ^ Start time. -> UTCTime -- ^ Submission time. -> Cacheable () mkReview mid aid st et c = do rid <- liftInsertSingleQ (mkReviewP mid aid st et) c let r = Review rid st et (getMemberID mid) (getApplicationID aid) (getReviewReviewMetrics rid) singletonGhost reviewIDCache rid r c mkInterview :: Word64 -- ^ Member ID(interviewer). -> Word64 -- ^ Application ID. -> UTCTime -- ^ Interview time. -> Cacheable () mkInterview mid aid t c = do iid <- liftInsertSingleQ (mkInterviewP mid aid t) c let i = Interview iid t (getMemberID mid) (getApplicationID aid) (getInterviewInterviewMetrics iid) singletonGhost interviewIDCache iid i c mkQuestion :: T.Text -- ^ Query. -> Cacheable () mkQuestion q c = do qid <- liftInsertSingleQ (mkQuestionP q) c let q' = Question qid q True singletonGhost questionIDCache qid q' c mkTerm :: Day -- ^ Start date. -> Cacheable () mkTerm s c = do tid <- liftInsertSingleQ (mkTermP s) c let t = Term tid s Nothing singletonGhost termIDCache tid t c grEboard :: Word64 -- ^ Member ID. -> Committee -- ^ Committee. -> Day -- ^ Service start date. -> Cacheable () grEboard mid cm s c = do liftUnitQ (grEboardP mid (committeeToVal cm) s) c let e = Eboard cm s Nothing (getMemberID mid) appendGhost eboardMemberIDCache mid e c grRoom :: Word64 -- ^ Member ID. -> T.Text -- ^ Room number. -> Day -- ^ Residence start date. -> Cacheable () grRoom mid rn s c = do liftUnitQ (grRoomP mid rn s) c let r = Room rn s Nothing (getMemberID mid) appendGhost roomMemberIDCache mid r c grQueue :: Word64 -- ^ Member ID. -> UTCTime -- ^ Entrance time. -> Cacheable () grQueue mid t c = do liftUnitQ (grQueueP mid t) c let q = Queue t Nothing (getMemberID mid) appendGhost queueMemberIDCache mid q c grMembership :: Word64 -- ^ Member ID. -> MemberStatus -- ^ Membership status. -> Day -- ^ Effective date. -> Cacheable () grMembership mid ms t c = do liftUnitQ (grMembershipP mid (memberStatusToVal ms) t) c let m = Membership ms t Nothing (getMemberID mid) appendGhost membershipMemberIDCache mid m c grEventAttendee :: Word64 -- ^ Member ID. -> Word64 -- ^ Event ID. -> Bool -- ^ Host status. -> Cacheable () grEventAttendee mid eid h c = do liftUnitQ (grEventAttendeeP mid eid h) c let e = EventAttendee h (getMemberID mid) (getEventID eid) appendGhost eventAttendeeMemberIDCache mid e c appendGhost eventAttendeeEventIDCache eid e c grProjectParticipant :: Word64 -- ^ Member ID. -> Word64 -- ^ Project ID. -> T.Text -- ^ Description. -> Cacheable () grProjectParticipant mid pid d c = do liftUnitQ (grProjectParticipantP mid pid d) c let p = ProjectParticipant d (getMemberID mid) (getProjectID pid) appendGhost projectParticipantMemberIDCache mid p c appendGhost projectParticipantProjectIDCache pid p c grFreshmanProjectParticipant :: Word64 -- ^ Freshman Project ID. -> Word64 -- ^ Evaluation ID. -> Cacheable () grFreshmanProjectParticipant pid eid c = do liftUnitQ (grFreshmanProjectParticipantP pid eid) c let f = FreshmanProjectParticipant False Pending T.empty (getFreshmanProjectID pid) (getEvaluationID eid) appendGhost freshProjParticipantProjectIDCache pid f c appendGhost freshProjParticipantEvaluationIDCache eid f c grSignature :: Word64 -- ^ Member ID. -> Word64 -- ^ Packet ID. -> Bool -- ^ Required. -> Cacheable () grSignature mid pid r c = do liftUnitQ (grSignatureP mid pid r) c let s = Signature r Nothing (getMemberID mid) (getPacketID pid) appendGhost signatureMemberIDCache mid s c appendGhost signaturePacketIDCache pid s c grReviewMetric :: Word64 -- ^ Metric ID. -> Word64 -- ^ Review ID. -> Int -- ^ Score. -> Cacheable () grReviewMetric mid rid s c = do liftUnitQ (grReviewMetricP mid rid s) c let r = ReviewMetric s (getMetricID mid) (getReviewID rid) appendGhost reviewMetricMetricIDCache mid r c appendGhost reviewMetricReviewIDCache rid r c grInterviewMetric :: Word64 -- ^ Metric ID. -> Word64 -- ^ Interview ID. -> Int -- ^ Score. -> Cacheable () grInterviewMetric mid iid s c = do liftUnitQ (grInterviewMetricP mid iid s) c let i = InterviewMetric s (getMetricID mid) (getInterviewID iid) appendGhost interviewMetricMetricIDCache mid i c appendGhost interviewMetricInterviewIDCache iid i c grAnswer :: Word64 -- ^ Application ID -> Word64 -- ^ Question ID -> T.Text -- ^ Response -> Cacheable () grAnswer aid qid r c = do liftUnitQ (grAnswerP aid qid r) c let a = Answer r (getQuestionID qid) (getApplicationID aid) appendGhost answerQuestionIDCache qid a c appendGhost answerApplicationIDCache aid a c grDues :: Word64 -- ^ Term ID. -> Word64 -- ^ Member ID. -> DuesStatus -- ^ Dues status. -> Cacheable () grDues tid mid s c = do liftUnitQ (grDuesP tid mid (duesStatusToVal s)) c let d = Dues s (getMemberID mid) (getTermID tid) appendGhost duesMemberIDCache mid d c appendGhost duesTermIDCache tid d c
TravisWhitaker/csh-eval
src/CSH/Eval/Cacheable/Make.hs
Haskell
mit
14,290
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="el-GR"> <title>Port Scan | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Ευρετήριο</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Αναζήτηση</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/zest/src/main/javahelp/org/zaproxy/zap/extension/zest/resources/help_el_GR/helpset_el_GR.hs
Haskell
apache-2.0
996
{-# LANGUAGE PatternGuards, ExistentialQuantification, CPP #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Idris.Core.Execute (execute) where import Idris.AbsSyntax import Idris.AbsSyntaxTree import IRTS.Lang(FDesc(..), FType(..)) import Idris.Primitives(Prim(..), primitives) import Idris.Core.TT import Idris.Core.Evaluate import Idris.Core.CaseTree import Idris.Error import Debug.Trace import Util.DynamicLinker import Util.System import Control.Applicative hiding (Const) import Control.Exception import Control.Monad.Trans import Control.Monad.Trans.State.Strict import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE) import Control.Monad hiding (forM) import Data.Maybe import Data.Bits import Data.Traversable (forM) import Data.Time.Clock.POSIX (getPOSIXTime) import qualified Data.Map as M #ifdef IDRIS_FFI import Foreign.LibFFI import Foreign.C.String import Foreign.Marshal.Alloc (free) import Foreign.Ptr #endif import System.IO #ifndef IDRIS_FFI execute :: Term -> Idris Term execute tm = fail "libffi not supported, rebuild Idris with -f FFI" #else -- else is rest of file readMay :: (Read a) => String -> Maybe a readMay s = case reads s of [(x, "")] -> Just x _ -> Nothing data Lazy = Delayed ExecEnv Context Term | Forced ExecVal deriving Show data ExecState = ExecState { exec_dynamic_libs :: [DynamicLib] -- ^ Dynamic libs from idris monad , binderNames :: [Name] -- ^ Used to uniquify binders when converting to TT } data ExecVal = EP NameType Name ExecVal | EV Int | EBind Name (Binder ExecVal) (ExecVal -> Exec ExecVal) | EApp ExecVal ExecVal | EType UExp | EUType Universe | EErased | EConstant Const | forall a. EPtr (Ptr a) | EThunk Context ExecEnv Term | EHandle Handle instance Show ExecVal where show (EP _ n _) = show n show (EV i) = "!!V" ++ show i ++ "!!" show (EBind n b body) = "EBind " ++ show b ++ " <<fn>>" show (EApp e1 e2) = show e1 ++ " (" ++ show e2 ++ ")" show (EType _) = "Type" show (EUType _) = "UType" show EErased = "[__]" show (EConstant c) = show c show (EPtr p) = "<<ptr " ++ show p ++ ">>" show (EThunk _ env tm) = "<<thunk " ++ show env ++ "||||" ++ show tm ++ ">>" show (EHandle h) = "<<handle " ++ show h ++ ">>" toTT :: ExecVal -> Exec Term toTT (EP nt n ty) = (P nt n) <$> (toTT ty) toTT (EV i) = return $ V i toTT (EBind n b body) = do n' <- newN n body' <- body $ EP Bound n' EErased b' <- fixBinder b Bind n' b' <$> toTT body' where fixBinder (Lam t) = Lam <$> toTT t fixBinder (Pi i t k) = Pi i <$> toTT t <*> toTT k fixBinder (Let t1 t2) = Let <$> toTT t1 <*> toTT t2 fixBinder (NLet t1 t2) = NLet <$> toTT t1 <*> toTT t2 fixBinder (Hole t) = Hole <$> toTT t fixBinder (GHole i ns t) = GHole i ns <$> toTT t fixBinder (Guess t1 t2) = Guess <$> toTT t1 <*> toTT t2 fixBinder (PVar t) = PVar <$> toTT t fixBinder (PVTy t) = PVTy <$> toTT t newN n = do (ExecState hs ns) <- lift get let n' = uniqueName n ns lift (put (ExecState hs (n':ns))) return n' toTT (EApp e1 e2) = do e1' <- toTT e1 e2' <- toTT e2 return $ App Complete e1' e2' toTT (EType u) = return $ TType u toTT (EUType u) = return $ UType u toTT EErased = return Erased toTT (EConstant c) = return (Constant c) toTT (EThunk ctxt env tm) = do env' <- mapM toBinder env return $ normalise ctxt env' tm where toBinder (n, v) = do v' <- toTT v return (n, Let Erased v') toTT (EHandle _) = execFail $ Msg "Can't convert handles back to TT after execution." toTT (EPtr ptr) = execFail $ Msg "Can't convert pointers back to TT after execution." unApplyV :: ExecVal -> (ExecVal, [ExecVal]) unApplyV tm = ua [] tm where ua args (EApp f a) = ua (a:args) f ua args t = (t, args) mkEApp :: ExecVal -> [ExecVal] -> ExecVal mkEApp f [] = f mkEApp f (a:args) = mkEApp (EApp f a) args initState :: Idris ExecState initState = do ist <- getIState return $ ExecState (idris_dynamic_libs ist) [] type Exec = ExceptT Err (StateT ExecState IO) runExec :: Exec a -> ExecState -> IO (Either Err a) runExec ex st = fst <$> runStateT (runExceptT ex) st getExecState :: Exec ExecState getExecState = lift get putExecState :: ExecState -> Exec () putExecState = lift . put execFail :: Err -> Exec a execFail = throwE execIO :: IO a -> Exec a execIO = lift . lift execute :: Term -> Idris Term execute tm = do est <- initState ctxt <- getContext res <- lift . lift . flip runExec est $ do res <- doExec [] ctxt tm toTT res case res of Left err -> ierror err Right tm' -> return tm' ioWrap :: ExecVal -> ExecVal ioWrap tm = mkEApp (EP (DCon 0 2 False) (sUN "prim__IO") EErased) [EErased, tm] ioUnit :: ExecVal ioUnit = ioWrap (EP Ref unitCon EErased) type ExecEnv = [(Name, ExecVal)] doExec :: ExecEnv -> Context -> Term -> Exec ExecVal doExec env ctxt p@(P Ref n ty) | Just v <- lookup n env = return v doExec env ctxt p@(P Ref n ty) = do let val = lookupDef n ctxt case val of [Function _ tm] -> doExec env ctxt tm [TyDecl _ _] -> return (EP Ref n EErased) -- abstract def [Operator tp arity op] -> return (EP Ref n EErased) -- will be special-cased later [CaseOp _ _ _ _ _ (CaseDefs _ ([], STerm tm) _ _)] -> -- nullary fun doExec env ctxt tm [CaseOp _ _ _ _ _ (CaseDefs _ (ns, sc) _ _)] -> return (EP Ref n EErased) [] -> execFail . Msg $ "Could not find " ++ show n ++ " in definitions." other | length other > 1 -> execFail . Msg $ "Multiple definitions found for " ++ show n | otherwise -> execFail . Msg . take 500 $ "got to " ++ show other ++ " lookup up " ++ show n doExec env ctxt p@(P Bound n ty) = case lookup n env of Nothing -> execFail . Msg $ "not found" Just tm -> return tm doExec env ctxt (P (DCon a b u) n _) = return (EP (DCon a b u) n EErased) doExec env ctxt (P (TCon a b) n _) = return (EP (TCon a b) n EErased) doExec env ctxt v@(V i) | i < length env = return (snd (env !! i)) | otherwise = execFail . Msg $ "env too small" doExec env ctxt (Bind n (Let t v) body) = do v' <- doExec env ctxt v doExec ((n, v'):env) ctxt body doExec env ctxt (Bind n (NLet t v) body) = trace "NLet" $ undefined doExec env ctxt tm@(Bind n b body) = do b' <- forM b (doExec env ctxt) return $ EBind n b' (\arg -> doExec ((n, arg):env) ctxt body) doExec env ctxt a@(App _ _ _) = do let (f, args) = unApply a f' <- doExec env ctxt f args' <- case f' of (EP _ d _) | d == delay -> case args of [t,a,tm] -> do t' <- doExec env ctxt t a' <- doExec env ctxt a return [t', a', EThunk ctxt env tm] _ -> mapM (doExec env ctxt) args -- partial applications are fine to evaluate fun' -> do mapM (doExec env ctxt) args execApp env ctxt f' args' doExec env ctxt (Constant c) = return (EConstant c) doExec env ctxt (Proj tm i) = let (x, xs) = unApply tm in doExec env ctxt ((x:xs) !! i) doExec env ctxt Erased = return EErased doExec env ctxt Impossible = fail "Tried to execute an impossible case" doExec env ctxt (TType u) = return (EType u) doExec env ctxt (UType u) = return (EUType u) execApp :: ExecEnv -> Context -> ExecVal -> [ExecVal] -> Exec ExecVal execApp env ctxt v [] = return v -- no args is just a constant! can result from function calls execApp env ctxt (EP _ f _) (t:a:delayed:rest) | f == force , (_, [_, _, EThunk tmCtxt tmEnv tm]) <- unApplyV delayed = do tm' <- doExec tmEnv tmCtxt tm execApp env ctxt tm' rest execApp env ctxt (EP _ fp _) (ty:action:rest) | fp == upio, (prim__IO, [_, v]) <- unApplyV action = execApp env ctxt v rest execApp env ctxt (EP _ fp _) args@(_:_:v:k:rest) | fp == piobind, (prim__IO, [_, v']) <- unApplyV v = do res <- execApp env ctxt k [v'] execApp env ctxt res rest execApp env ctxt con@(EP _ fp _) args@(tp:v:rest) | fp == pioret = execApp env ctxt (mkEApp con [tp, v]) rest -- Special cases arising from not having access to the C RTS in the interpreter execApp env ctxt f@(EP _ fp _) args@(xs:_:_:_:args') | fp == mkfprim, (ty : fn : w : rest) <- reverse args' = execForeign env ctxt getArity ty fn rest (mkEApp f args) where getArity = case unEList xs of Just as -> length as _ -> 0 execApp env ctxt c@(EP (DCon _ arity _) n _) args = do let args' = take arity args let restArgs = drop arity args execApp env ctxt (mkEApp c args') restArgs execApp env ctxt c@(EP (TCon _ arity) n _) args = do let args' = take arity args let restArgs = drop arity args execApp env ctxt (mkEApp c args') restArgs execApp env ctxt f@(EP _ n _) args | Just (res, rest) <- getOp n args = do r <- res execApp env ctxt r rest execApp env ctxt f@(EP _ n _) args = do let val = lookupDef n ctxt case val of [Function _ tm] -> fail "should already have been eval'd" [TyDecl nt ty] -> return $ mkEApp f args [Operator tp arity op] -> if length args >= arity then let args' = take arity args in case getOp n args' of Just (res, []) -> do r <- res execApp env ctxt r (drop arity args) _ -> return (mkEApp f args) else return (mkEApp f args) [CaseOp _ _ _ _ _ (CaseDefs _ ([], STerm tm) _ _)] -> -- nullary fun do rhs <- doExec env ctxt tm execApp env ctxt rhs args [CaseOp _ _ _ _ _ (CaseDefs _ (ns, sc) _ _)] -> do res <- execCase env ctxt ns sc args return $ fromMaybe (mkEApp f args) res thing -> return $ mkEApp f args execApp env ctxt bnd@(EBind n b body) (arg:args) = do ret <- body arg let (f', as) = unApplyV ret execApp env ctxt f' (as ++ args) execApp env ctxt app@(EApp _ _) args2 | (f, args1) <- unApplyV app = execApp env ctxt f (args1 ++ args2) execApp env ctxt f args = return (mkEApp f args) execForeign env ctxt arity ty fn xs onfail | Just (FFun "putStr" [(_, str)] _) <- foreignFromTT arity ty fn xs = case str of EConstant (Str arg) -> do execIO (putStr arg) execApp env ctxt ioUnit (drop arity xs) _ -> execFail . Msg $ "The argument to putStr should be a constant string, but it was " ++ show str ++ ". Are all cases covered?" | Just (FFun "putchar" [(_, ch)] _) <- foreignFromTT arity ty fn xs = case ch of EConstant (Ch c) -> do execIO (putChar c) execApp env ctxt ioUnit (drop arity xs) EConstant (I i) -> do execIO (putChar (toEnum i)) execApp env ctxt ioUnit (drop arity xs) _ -> execFail . Msg $ "The argument to putchar should be a constant character, but it was " ++ show str ++ ". Are all cases covered?" | Just (FFun "idris_readStr" [_, (_, handle)] _) <- foreignFromTT arity ty fn xs = case handle of EHandle h -> do contents <- execIO $ hGetLine h execApp env ctxt (EConstant (Str (contents ++ "\n"))) (drop arity xs) _ -> execFail . Msg $ "The argument to idris_readStr should be a handle, but it was " ++ show handle ++ ". Are all cases covered?" | Just (FFun "getchar" _ _) <- foreignFromTT arity ty fn xs = do -- The C API returns an Int which Idris library code -- converts; thus, we must make an int here. ch <- execIO $ fmap (ioWrap . EConstant . I . fromEnum) getChar execApp env ctxt ch xs | Just (FFun "idris_time" _ _) <- foreignFromTT arity ty fn xs = do execIO $ fmap (ioWrap . EConstant . I . round) getPOSIXTime | Just (FFun "fileOpen" [(_,fileStr), (_,modeStr)] _) <- foreignFromTT arity ty fn xs = case (fileStr, modeStr) of (EConstant (Str f), EConstant (Str mode)) -> do f <- execIO $ catch (do let m = case mode of "r" -> Right ReadMode "w" -> Right WriteMode "a" -> Right AppendMode "rw" -> Right ReadWriteMode "wr" -> Right ReadWriteMode "r+" -> Right ReadWriteMode _ -> Left ("Invalid mode for " ++ f ++ ": " ++ mode) case fmap (openFile f) m of Right h -> do h' <- h hSetBinaryMode h' True return $ Right (ioWrap (EHandle h'), drop arity xs) Left err -> return $ Left err) (\e -> let _ = ( e::SomeException) in return $ Right (ioWrap (EPtr nullPtr), drop arity xs)) case f of Left err -> execFail . Msg $ err Right (res, rest) -> execApp env ctxt res rest _ -> execFail . Msg $ "The arguments to fileOpen should be constant strings, but they were " ++ show fileStr ++ " and " ++ show modeStr ++ ". Are all cases covered?" | Just (FFun "fileEOF" [(_,handle)] _) <- foreignFromTT arity ty fn xs = case handle of EHandle h -> do eofp <- execIO $ hIsEOF h let res = ioWrap (EConstant (I $ if eofp then 1 else 0)) execApp env ctxt res (drop arity xs) _ -> execFail . Msg $ "The argument to fileEOF should be a file handle, but it was " ++ show handle ++ ". Are all cases covered?" | Just (FFun "fileError" [(_,handle)] _) <- foreignFromTT arity ty fn xs = case handle of -- errors handled differently in Haskell than in C, so if -- there's been an error we'll have had an exception already. -- Therefore, assume we're okay. EHandle h -> do let res = ioWrap (EConstant (I 0)) execApp env ctxt res (drop arity xs) _ -> execFail . Msg $ "The argument to fileError should be a file handle, but it was " ++ show handle ++ ". Are all cases covered?" | Just (FFun "fileClose" [(_,handle)] _) <- foreignFromTT arity ty fn xs = case handle of EHandle h -> do execIO $ hClose h execApp env ctxt ioUnit (drop arity xs) _ -> execFail . Msg $ "The argument to fileClose should be a file handle, but it was " ++ show handle ++ ". Are all cases covered?" | Just (FFun "isNull" [(_, ptr)] _) <- foreignFromTT arity ty fn xs = case ptr of EPtr p -> let res = ioWrap . EConstant . I $ if p == nullPtr then 1 else 0 in execApp env ctxt res (drop arity xs) -- Handles will be checked as null pointers sometimes - but if we got a -- real Handle, then it's valid, so just return 1. EHandle h -> let res = ioWrap . EConstant . I $ 0 in execApp env ctxt res (drop arity xs) -- A foreign-returned char* has to be tested for NULL sometimes EConstant (Str s) -> let res = ioWrap . EConstant . I $ 0 in execApp env ctxt res (drop arity xs) _ -> execFail . Msg $ "The argument to isNull should be a pointer or file handle or string, but it was " ++ show ptr ++ ". Are all cases covered?" -- Right now, there's no way to send command-line arguments to the executor, -- so just return 0. execForeign env ctxt arity ty fn xs onfail | Just (FFun "idris_numArgs" _ _) <- foreignFromTT arity ty fn xs = let res = ioWrap . EConstant . I $ 0 in execApp env ctxt res (drop arity xs) execForeign env ctxt arity ty fn xs onfail = case foreignFromTT arity ty fn xs of Just ffun@(FFun f argTs retT) | length xs >= arity -> do let (args', xs') = (take arity xs, -- foreign args drop arity xs) -- rest res <- call ffun (map snd argTs) case res of Nothing -> fail $ "Could not call foreign function \"" ++ f ++ "\" with args " ++ show (map snd argTs) Just r -> return (mkEApp r xs') _ -> return onfail splitArg tm | (_, [_,_,l,r]) <- unApplyV tm -- pair, two implicits = Just (toFDesc l, r) splitArg _ = Nothing toFDesc tm | (EP _ n _, []) <- unApplyV tm = FCon (deNS n) | (EP _ n _, as) <- unApplyV tm = FApp (deNS n) (map toFDesc as) toFDesc _ = FUnknown deNS (NS n _) = n deNS n = n prf = sUN "prim__readFile" pwf = sUN "prim__writeFile" prs = sUN "prim__readString" pws = sUN "prim__writeString" pbm = sUN "prim__believe_me" pstdin = sUN "prim__stdin" pstdout = sUN "prim__stdout" mkfprim = sUN "mkForeignPrim" pioret = sUN "prim_io_return" piobind = sUN "prim_io_bind" upio = sUN "unsafePerformPrimIO" delay = sUN "Delay" force = sUN "Force" -- | Look up primitive operations in the global table and transform -- them into ExecVal functions getOp :: Name -> [ExecVal] -> Maybe (Exec ExecVal, [ExecVal]) getOp fn (_ : _ : x : xs) | fn == pbm = Just (return x, xs) getOp fn (_ : EConstant (Str n) : xs) | fn == pws = Just (do execIO $ putStr n return (EConstant (I 0)), xs) getOp fn (_:xs) | fn == prs = Just (do line <- execIO getLine return (EConstant (Str line)), xs) getOp fn (_ : EP _ fn' _ : EConstant (Str n) : xs) | fn == pwf && fn' == pstdout = Just (do execIO $ putStr n return (EConstant (I 0)), xs) getOp fn (_ : EP _ fn' _ : xs) | fn == prf && fn' == pstdin = Just (do line <- execIO getLine return (EConstant (Str line)), xs) getOp fn (_ : EHandle h : EConstant (Str n) : xs) | fn == pwf = Just (do execIO $ hPutStr h n return (EConstant (I 0)), xs) getOp fn (_ : EHandle h : xs) | fn == prf = Just (do contents <- execIO $ hGetLine h return (EConstant (Str (contents ++ "\n"))), xs) getOp fn (_ : arg : xs) | fn == prf = Just $ (execFail (Msg "Can't use prim__readFile on a raw pointer in the executor."), xs) getOp n args = do (arity, prim) <- getPrim n primitives if (length args >= arity) then do res <- applyPrim prim (take arity args) Just (res, drop arity args) else Nothing where getPrim :: Name -> [Prim] -> Maybe (Int, [ExecVal] -> Maybe ExecVal) getPrim n [] = Nothing getPrim n ((Prim pn _ arity def _ _) : prims) | n == pn = Just (arity, execPrim def) | otherwise = getPrim n prims execPrim :: ([Const] -> Maybe Const) -> [ExecVal] -> Maybe ExecVal execPrim f args = EConstant <$> (mapM getConst args >>= f) getConst (EConstant c) = Just c getConst _ = Nothing applyPrim :: ([ExecVal] -> Maybe ExecVal) -> [ExecVal] -> Maybe (Exec ExecVal) applyPrim fn args = return <$> fn args -- | Overall wrapper for case tree execution. If there are enough arguments, it takes them, -- evaluates them, then begins the checks for matching cases. execCase :: ExecEnv -> Context -> [Name] -> SC -> [ExecVal] -> Exec (Maybe ExecVal) execCase env ctxt ns sc args = let arity = length ns in if arity <= length args then do let amap = zip ns args -- trace ("Case " ++ show sc ++ "\n in " ++ show amap ++"\n in env " ++ show env ++ "\n\n" ) $ return () caseRes <- execCase' env ctxt amap sc case caseRes of Just res -> Just <$> execApp (map (\(n, tm) -> (n, tm)) amap ++ env) ctxt res (drop arity args) Nothing -> return Nothing else return Nothing -- | Take bindings and a case tree and examines them, executing the matching case if possible. execCase' :: ExecEnv -> Context -> [(Name, ExecVal)] -> SC -> Exec (Maybe ExecVal) execCase' env ctxt amap (UnmatchedCase _) = return Nothing execCase' env ctxt amap (STerm tm) = Just <$> doExec (map (\(n, v) -> (n, v)) amap ++ env) ctxt tm execCase' env ctxt amap (Case sh n alts) | Just tm <- lookup n amap = case chooseAlt tm alts of Just (newCase, newBindings) -> let amap' = newBindings ++ (filter (\(x,_) -> not (elem x (map fst newBindings))) amap) in execCase' env ctxt amap' newCase Nothing -> return Nothing execCase' _ _ _ cse = fail $ "The impossible happened: tried to exec " ++ show cse chooseAlt :: ExecVal -> [CaseAlt] -> Maybe (SC, [(Name, ExecVal)]) chooseAlt tm (DefaultCase sc : alts) | ok tm = Just (sc, []) | otherwise = Nothing where -- Default cases should only work on applications of constructors or on constants ok (EApp f x) = ok f ok (EP Bound _ _) = False ok (EP Ref _ _) = False ok _ = True chooseAlt (EConstant c) (ConstCase c' sc : alts) | c == c' = Just (sc, []) chooseAlt tm (ConCase n i ns sc : alts) | ((EP _ cn _), args) <- unApplyV tm , cn == n = Just (sc, zip ns args) | otherwise = chooseAlt tm alts chooseAlt tm (_:alts) = chooseAlt tm alts chooseAlt _ [] = Nothing data Foreign = FFun String [(FDesc, ExecVal)] FDesc deriving Show toFType :: FDesc -> FType toFType (FCon c) | c == sUN "C_Str" = FString | c == sUN "C_Float" = FArith ATFloat | c == sUN "C_Ptr" = FPtr | c == sUN "C_MPtr" = FManagedPtr | c == sUN "C_Unit" = FUnit toFType (FApp c [_,ity]) | c == sUN "C_IntT" = FArith (toAType ity) where toAType (FCon i) | i == sUN "C_IntChar" = ATInt ITChar | i == sUN "C_IntNative" = ATInt ITNative | i == sUN "C_IntBits8" = ATInt (ITFixed IT8) | i == sUN "C_IntBits16" = ATInt (ITFixed IT16) | i == sUN "C_IntBits32" = ATInt (ITFixed IT32) | i == sUN "C_IntBits64" = ATInt (ITFixed IT64) toAType t = error (show t ++ " not defined in toAType") toFType (FApp c [_]) | c == sUN "C_Any" = FAny toFType t = error (show t ++ " not defined in toFType") call :: Foreign -> [ExecVal] -> Exec (Maybe ExecVal) call (FFun name argTypes retType) args = do fn <- findForeign name maybe (return Nothing) (\f -> Just . ioWrap <$> call' f args (toFType retType)) fn where call' :: ForeignFun -> [ExecVal] -> FType -> Exec ExecVal call' (Fun _ h) args (FArith (ATInt ITNative)) = do res <- execIO $ callFFI h retCInt (prepArgs args) return (EConstant (I (fromIntegral res))) call' (Fun _ h) args (FArith (ATInt (ITFixed IT8))) = do res <- execIO $ callFFI h retCChar (prepArgs args) return (EConstant (B8 (fromIntegral res))) call' (Fun _ h) args (FArith (ATInt (ITFixed IT16))) = do res <- execIO $ callFFI h retCWchar (prepArgs args) return (EConstant (B16 (fromIntegral res))) call' (Fun _ h) args (FArith (ATInt (ITFixed IT32))) = do res <- execIO $ callFFI h retCInt (prepArgs args) return (EConstant (B32 (fromIntegral res))) call' (Fun _ h) args (FArith (ATInt (ITFixed IT64))) = do res <- execIO $ callFFI h retCLong (prepArgs args) return (EConstant (B64 (fromIntegral res))) call' (Fun _ h) args (FArith ATFloat) = do res <- execIO $ callFFI h retCDouble (prepArgs args) return (EConstant (Fl (realToFrac res))) call' (Fun _ h) args (FArith (ATInt ITChar)) = do res <- execIO $ callFFI h retCChar (prepArgs args) return (EConstant (Ch (castCCharToChar res))) call' (Fun _ h) args FString = do res <- execIO $ callFFI h retCString (prepArgs args) if res == nullPtr then return (EPtr res) else do hStr <- execIO $ peekCString res return (EConstant (Str hStr)) call' (Fun _ h) args FPtr = EPtr <$> (execIO $ callFFI h (retPtr retVoid) (prepArgs args)) call' (Fun _ h) args FUnit = do _ <- execIO $ callFFI h retVoid (prepArgs args) return $ EP Ref unitCon EErased call' _ _ _ = fail "the impossible happened in call' in Execute.hs" prepArgs = map prepArg prepArg (EConstant (I i)) = argCInt (fromIntegral i) prepArg (EConstant (B8 i)) = argCChar (fromIntegral i) prepArg (EConstant (B16 i)) = argCWchar (fromIntegral i) prepArg (EConstant (B32 i)) = argCInt (fromIntegral i) prepArg (EConstant (B64 i)) = argCLong (fromIntegral i) prepArg (EConstant (Fl f)) = argCDouble (realToFrac f) prepArg (EConstant (Ch c)) = argCChar (castCharToCChar c) -- FIXME - castCharToCChar only safe for first 256 chars -- Issue #1720 on the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1720 prepArg (EConstant (Str s)) = argString s prepArg (EPtr p) = argPtr p prepArg other = trace ("Could not use " ++ take 100 (show other) ++ " as FFI arg.") undefined foreignFromTT :: Int -> ExecVal -> ExecVal -> [ExecVal] -> Maybe Foreign foreignFromTT arity ty (EConstant (Str name)) args = do argFTyVals <- mapM splitArg (take arity args) return $ FFun name argFTyVals (toFDesc ty) foreignFromTT arity ty fn args = trace ("failed to construct ffun from " ++ show (ty,fn,args)) Nothing getFTy :: ExecVal -> Maybe FType getFTy (EApp (EP _ (UN fi) _) (EP _ (UN intTy) _)) | fi == txt "FIntT" = case str intTy of "ITNative" -> Just (FArith (ATInt ITNative)) "ITChar" -> Just (FArith (ATInt ITChar)) "IT8" -> Just (FArith (ATInt (ITFixed IT8))) "IT16" -> Just (FArith (ATInt (ITFixed IT16))) "IT32" -> Just (FArith (ATInt (ITFixed IT32))) "IT64" -> Just (FArith (ATInt (ITFixed IT64))) _ -> Nothing getFTy (EP _ (UN t) _) = case str t of "FFloat" -> Just (FArith ATFloat) "FString" -> Just FString "FPtr" -> Just FPtr "FUnit" -> Just FUnit _ -> Nothing getFTy _ = Nothing unEList :: ExecVal -> Maybe [ExecVal] unEList tm = case unApplyV tm of (nil, [_]) -> Just [] (cons, ([_, x, xs])) -> do rest <- unEList xs return $ x:rest (f, args) -> Nothing toConst :: Term -> Maybe Const toConst (Constant c) = Just c toConst _ = Nothing mapMaybeM :: (Functor m, Monad m) => (a -> m (Maybe b)) -> [a] -> m [b] mapMaybeM f [] = return [] mapMaybeM f (x:xs) = do rest <- mapMaybeM f xs maybe rest (:rest) <$> f x findForeign :: String -> Exec (Maybe ForeignFun) findForeign fn = do est <- getExecState let libs = exec_dynamic_libs est fns <- mapMaybeM getFn libs case fns of [f] -> return (Just f) [] -> do execIO . putStrLn $ "Symbol \"" ++ fn ++ "\" not found" return Nothing fs -> do execIO . putStrLn $ "Symbol \"" ++ fn ++ "\" is ambiguous. Found " ++ show (length fs) ++ " occurrences." return Nothing where getFn lib = execIO $ catchIO (tryLoadFn fn lib) (\_ -> return Nothing) #endif
TimRichter/Idris-dev
src/Idris/Core/Execute.hs
Haskell
bsd-3-clause
30,115
{-# LANGUAGE RecordWildCards #-} module Network.Wai.Middleware.RequestLogger.JSON (formatAsJSON) where import qualified Blaze.ByteString.Builder as BB import Data.Aeson import Data.CaseInsensitive (original) import Data.Monoid ((<>)) import qualified Data.ByteString.Char8 as S8 import Data.IP import qualified Data.Text as T import Data.Text (Text) import Data.Text.Encoding (decodeUtf8) import Data.Time (NominalDiffTime) import Data.Word (Word32) import Network.HTTP.Types as H import Network.Socket (SockAddr (..), PortNumber) import Network.Wai import Network.Wai.Middleware.RequestLogger import System.Log.FastLogger (toLogStr) import Text.Printf (printf) formatAsJSON :: OutputFormatterWithDetails formatAsJSON date req status responseSize duration reqBody response = toLogStr (encode $ object [ "request" .= requestToJSON duration req reqBody , "response" .= object [ "status" .= statusCode status , "size" .= responseSize , "body" .= if statusCode status >= 400 then Just . decodeUtf8 . BB.toByteString $ response else Nothing ] , "time" .= decodeUtf8 date ]) <> "\n" word32ToHostAddress :: Word32 -> Text word32ToHostAddress = T.intercalate "." . map (T.pack . show) . fromIPv4 . fromHostAddress readAsDouble :: String -> Double readAsDouble = read requestToJSON :: NominalDiffTime -> Request -> [S8.ByteString] -> Value requestToJSON duration req reqBody = object [ "method" .= decodeUtf8 (requestMethod req) , "path" .= decodeUtf8 (rawPathInfo req) , "queryString" .= map queryItemToJSON (queryString req) , "durationMs" .= (readAsDouble . printf "%.2f" . rationalToDouble $ toRational duration * 1000) , "size" .= requestBodyLengthToJSON (requestBodyLength req) , "body" .= decodeUtf8 (S8.concat reqBody) , "remoteHost" .= sockToJSON (remoteHost req) , "httpVersion" .= httpVersionToJSON (httpVersion req) , "headers" .= requestHeadersToJSON (requestHeaders req) ] where rationalToDouble :: Rational -> Double rationalToDouble = fromRational sockToJSON :: SockAddr -> Value sockToJSON (SockAddrInet pn ha) = object [ "port" .= portToJSON pn , "hostAddress" .= word32ToHostAddress ha ] sockToJSON (SockAddrInet6 pn _ ha _) = object [ "port" .= portToJSON pn , "hostAddress" .= ha ] sockToJSON (SockAddrUnix sock) = object [ "unix" .= sock ] sockToJSON (SockAddrCan i) = object [ "can" .= i ] queryItemToJSON :: QueryItem -> Value queryItemToJSON (name, mValue) = toJSON (decodeUtf8 name, fmap decodeUtf8 mValue) requestHeadersToJSON :: RequestHeaders -> Value requestHeadersToJSON = toJSON . map hToJ where -- Redact cookies hToJ ("Cookie", _) = toJSON ("Cookie" :: Text, "-RDCT-" :: Text) hToJ hd = headerToJSON hd headerToJSON :: Header -> Value headerToJSON (headerName, header) = toJSON (decodeUtf8 . original $ headerName, decodeUtf8 header) portToJSON :: PortNumber -> Value portToJSON = toJSON . toInteger httpVersionToJSON :: HttpVersion -> Value httpVersionToJSON (HttpVersion major minor) = String $ T.pack (show major) <> "." <> T.pack (show minor) requestBodyLengthToJSON :: RequestBodyLength -> Value requestBodyLengthToJSON ChunkedBody = String "Unknown" requestBodyLengthToJSON (KnownLength l) = toJSON l
rgrinberg/wai
wai-extra/Network/Wai/Middleware/RequestLogger/JSON.hs
Haskell
mit
3,346
-- Copyright (c) 2014-present, Facebook, Inc. -- All rights reserved. -- -- This source code is distributed under the terms of a BSD license, -- found in the LICENSE file. An additional grant of patent rights can -- be found in the PATENTS file. {-# LANGUAGE CPP #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE RankNTypes #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- | A cache mapping data requests to their results. module Haxl.Core.DataCache ( DataCache , empty , insert , lookup , showCache ) where import Data.HashMap.Strict (HashMap) import Data.Hashable import Prelude hiding (lookup) import Unsafe.Coerce import qualified Data.HashMap.Strict as HashMap import Data.Typeable.Internal import Data.Maybe #if __GLASGOW_HASKELL__ < 710 import Control.Applicative hiding (empty) #endif import Control.Exception import Haxl.Core.Types -- | The 'DataCache' maps things of type @f a@ to @'ResultVar' a@, for -- any @f@ and @a@ provided @f a@ is an instance of 'Typeable'. In -- practice @f a@ will be a request type parameterised by its result. -- -- See the definition of 'ResultVar' for more details. newtype DataCache res = DataCache (HashMap TypeRep (SubCache res)) -- | The implementation is a two-level map: the outer level maps the -- types of requests to 'SubCache', which maps actual requests to their -- results. So each 'SubCache' contains requests of the same type. -- This works well because we only have to store the dictionaries for -- 'Hashable' and 'Eq' once per request type. data SubCache res = forall req a . (Hashable (req a), Eq (req a), Show (req a), Show a) => SubCache ! (HashMap (req a) (res a)) -- NB. the inner HashMap is strict, to avoid building up -- a chain of thunks during repeated insertions. -- | A new, empty 'DataCache'. empty :: DataCache res empty = DataCache HashMap.empty -- | Inserts a request-result pair into the 'DataCache'. insert :: (Hashable (req a), Typeable (req a), Eq (req a), Show (req a), Show a) => req a -- ^ Request -> res a -- ^ Result -> DataCache res -> DataCache res insert req result (DataCache m) = DataCache $ HashMap.insertWith fn (typeOf req) (SubCache (HashMap.singleton req result)) m where fn (SubCache new) (SubCache old) = SubCache (unsafeCoerce new `HashMap.union` old) -- | Looks up the cached result of a request. lookup :: Typeable (req a) => req a -- ^ Request -> DataCache res -> Maybe (res a) lookup req (DataCache m) = case HashMap.lookup (typeOf req) m of Nothing -> Nothing Just (SubCache sc) -> unsafeCoerce (HashMap.lookup (unsafeCoerce req) sc) -- | Dumps the contents of the cache, with requests and responses -- converted to 'String's using 'show'. The entries are grouped by -- 'TypeRep'. -- showCache :: DataCache ResultVar -> IO [(TypeRep, [(String, Either SomeException String)])] showCache (DataCache cache) = mapM goSubCache (HashMap.toList cache) where goSubCache :: (TypeRep,SubCache ResultVar) -> IO (TypeRep,[(String, Either SomeException String)]) goSubCache (ty, SubCache hmap) = do elems <- catMaybes <$> mapM go (HashMap.toList hmap) return (ty, elems) go :: (Show (req a), Show a) => (req a, ResultVar a) -> IO (Maybe (String, Either SomeException String)) go (req, rvar) = do maybe_r <- tryReadResult rvar case maybe_r of Nothing -> return Nothing Just (Left e) -> return (Just (show req, Left e)) Just (Right result) -> return (Just (show req, Right (show result)))
hiteshsuthar/Haxl
Haxl/Core/DataCache.hs
Haskell
bsd-3-clause
3,612
module ConstructorIn1 where data MyBTree a = Empty | T a (MyBTree a) (MyBTree a) deriving Show buildtree :: Ord a => [a] -> MyBTree a buildtree [] = Empty buildtree ((x : xs)) = insert x (buildtree xs) insert :: Ord a => a -> (MyBTree a) -> MyBTree a insert val Empty = T val Empty Empty insert val tree@(T tval left right) | val > tval = T tval left (insert val right) | otherwise = T tval (insert val left) right main :: MyBTree Int main = buildtree [3, 1, 2]
mpickering/HaRe
old/testing/renaming/ConstructorIn1_AstOut.hs
Haskell
bsd-3-clause
487
{-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -O #-} module T12944 () where class AdditiveGroup v where (^+^) :: v -> v -> v negateV :: v -> v (^-^) :: v -> v -> v v ^-^ v' = v ^+^ negateV v' class AdditiveGroup v => VectorSpace v where type Scalar v :: * (*^) :: Scalar v -> v -> v data Poly1 a = Poly1 a a data IntOfLog poly a = IntOfLog !a !(poly a) instance Num a => AdditiveGroup (Poly1 a) where {-# INLINE (^+^) #-} {-# INLINE negateV #-} Poly1 a b ^+^ Poly1 a' b' = Poly1 (a + a') (b + b') negateV (Poly1 a b) = Poly1 (negate a) (negate b) instance (AdditiveGroup (poly a), Num a) => AdditiveGroup (IntOfLog poly a) where {-# INLINE (^+^) #-} {-# INLINE negateV #-} IntOfLog k p ^+^ IntOfLog k' p' = IntOfLog (k + k') (p ^+^ p') negateV (IntOfLog k p) = IntOfLog (negate k) (negateV p) {-# SPECIALISE instance Num a => AdditiveGroup (IntOfLog Poly1 a) #-} -- This pragmas casued the crash instance (VectorSpace (poly a), Scalar (poly a) ~ a, Num a) => VectorSpace (IntOfLog poly a) where type Scalar (IntOfLog poly a) = a s *^ IntOfLog k p = IntOfLog (s * k) (s *^ p)
ezyang/ghc
testsuite/tests/deSugar/should_compile/T12944.hs
Haskell
bsd-3-clause
1,147
module Complex(Complex((:+)), realPart, imagPart, conjugate, mkPolar, cis, polar, magnitude, phase) where --import Prelude infix 6 :+ data (RealFloat a) => Complex a = !a :+ !a deriving (Eq,Read,Show) realPart, imagPart :: (RealFloat a) => Complex a -> a realPart (x:+y) = x imagPart (x:+y) = y conjugate :: (RealFloat a) => Complex a -> Complex a conjugate (x:+y) = x :+ (-y) mkPolar :: (RealFloat a) => a -> a -> Complex a mkPolar r theta = r * cos theta :+ r * sin theta cis :: (RealFloat a) => a -> Complex a cis theta = cos theta :+ sin theta polar :: (RealFloat a) => Complex a -> (a,a) polar z = (magnitude z, phase z) magnitude :: (RealFloat a) => Complex a -> a magnitude (x:+y) = scaleFloat k (sqrt ((scaleFloat mk x)^(2::Int) + (scaleFloat mk y)^(2::Int))) where k = max (exponent x) (exponent y) mk = - k phase :: (RealFloat a) => Complex a -> a phase (0 :+ 0) = 0 phase (x :+ y) = atan2 y x instance (RealFloat a) => Num (Complex a) where (x:+y) + (x':+y') = (x+x') :+ (y+y') (x:+y) - (x':+y') = (x-x') :+ (y-y') (x:+y) * (x':+y') = (x*x'-y*y') :+ (x*y'+y*x') negate (x:+y) = negate x :+ negate y abs z = magnitude z :+ 0 signum 0 = 0 signum z@(x:+y) = (x/r) :+ (y/r) where r = magnitude z fromInteger n = fromInteger n :+ 0 instance (RealFloat a) => Fractional (Complex a) where (x:+y) / (x':+y') = (x*x''+y*y'') / d :+ (y*x''-x*y'') / d where x'' = scaleFloat k x' y'' = scaleFloat k y' k = - max (exponent x') (exponent y') d = x'*x'' + y'*y'' fromRational a = fromRational a :+ 0 instance (RealFloat a) => Floating (Complex a) where pi = pi :+ 0 exp (x:+y) = expx * cos y :+ expx * sin y where expx = exp x log z = log (magnitude z) :+ phase z sqrt 0 = 0 sqrt z@(x:+y) = u :+ (if y < 0 then -v else v) where (u,v) = if x < 0 then (v',u') else (u',v') v' = abs y / (u'*2) u' = sqrt ((magnitude z + abs x) / 2) sin (x:+y) = sin x * cosh y :+ cos x * sinh y cos (x:+y) = cos x * cosh y :+ (- sin x * sinh y) tan (x:+y) = (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(-sinx*sinhy)) where sinx = sin x cosx = cos x sinhy = sinh y coshy = cosh y sinh (x:+y) = cos y * sinh x :+ sin y * cosh x cosh (x:+y) = cos y * cosh x :+ sin y * sinh x tanh (x:+y) = (cosy*sinhx:+siny*coshx)/(cosy*coshx:+siny*sinhx) where siny = sin y cosy = cos y sinhx = sinh x coshx = cosh x asin z@(x:+y) = y':+(-x') where (x':+y') = log (((-y):+x) + sqrt (1 - z*z)) acos z@(x:+y) = y'':+(-x'') where (x'':+y'') = log (z + ((-y'):+x')) (x':+y') = sqrt (1 - z*z) atan z@(x:+y) = y':+(-x') where (x':+y') = log (((1-y):+x) / sqrt (1+z*z)) asinh z = log (z + sqrt (1+z*z)) acosh z = log (z + (z+1) * sqrt ((z-1)/(z+1))) atanh z = log ((1+z) / sqrt (1-z*z))
forste/haReFork
tools/base/tests/HaskellLibraries/Complex.hs
Haskell
bsd-3-clause
3,383
{-# LANGUAGE GADTs #-} -- It's not clear whether this one should succeed or fail, -- Arguably it should succeed because the type refinement on -- T1 should make (y::Int). Currently, though, it fails. module ShouldFail where data T a where T1 :: Int -> T Int f :: (T a, a) -> Int f ~(T1 x, y) = x+y
olsner/ghc
testsuite/tests/gadt/lazypatok.hs
Haskell
bsd-3-clause
306
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.HTMLBaseFontElement (js_setColor, setColor, js_getColor, getColor, js_setFace, setFace, js_getFace, getFace, js_setSize, setSize, js_getSize, getSize, HTMLBaseFontElement, castToHTMLBaseFontElement, gTypeHTMLBaseFontElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"color\"] = $2;" js_setColor :: HTMLBaseFontElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLBaseFontElement.color Mozilla HTMLBaseFontElement.color documentation> setColor :: (MonadIO m, ToJSString val) => HTMLBaseFontElement -> val -> m () setColor self val = liftIO (js_setColor (self) (toJSString val)) foreign import javascript unsafe "$1[\"color\"]" js_getColor :: HTMLBaseFontElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLBaseFontElement.color Mozilla HTMLBaseFontElement.color documentation> getColor :: (MonadIO m, FromJSString result) => HTMLBaseFontElement -> m result getColor self = liftIO (fromJSString <$> (js_getColor (self))) foreign import javascript unsafe "$1[\"face\"] = $2;" js_setFace :: HTMLBaseFontElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLBaseFontElement.face Mozilla HTMLBaseFontElement.face documentation> setFace :: (MonadIO m, ToJSString val) => HTMLBaseFontElement -> val -> m () setFace self val = liftIO (js_setFace (self) (toJSString val)) foreign import javascript unsafe "$1[\"face\"]" js_getFace :: HTMLBaseFontElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLBaseFontElement.face Mozilla HTMLBaseFontElement.face documentation> getFace :: (MonadIO m, FromJSString result) => HTMLBaseFontElement -> m result getFace self = liftIO (fromJSString <$> (js_getFace (self))) foreign import javascript unsafe "$1[\"size\"] = $2;" js_setSize :: HTMLBaseFontElement -> Int -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLBaseFontElement.size Mozilla HTMLBaseFontElement.size documentation> setSize :: (MonadIO m) => HTMLBaseFontElement -> Int -> m () setSize self val = liftIO (js_setSize (self) val) foreign import javascript unsafe "$1[\"size\"]" js_getSize :: HTMLBaseFontElement -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLBaseFontElement.size Mozilla HTMLBaseFontElement.size documentation> getSize :: (MonadIO m) => HTMLBaseFontElement -> m Int getSize self = liftIO (js_getSize (self))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/HTMLBaseFontElement.hs
Haskell
mit
3,387
-- Word a9n (abbreviation) -- http://www.codewars.com/kata/5375f921003bf62192000746/ module A9n where import Data.Char (isLetter) import Data.List (groupBy) import Data.Function (on) abbreviate :: String -> String abbreviate = concatMap (\w -> if isLetter . head $ w then f w else w) . groupBy ((==) `on` isLetter) where f x | length x < 4 = x | otherwise = [head x] ++ show (length x -2) ++ [last x]
gafiatulin/codewars
src/6 kyu/A9n.hs
Haskell
mit
422
{-# LANGUAGE OverloadedStrings #-} import Data.Monoid import Web.Scotty import qualified Data.Text.Lazy as T import Data.Text.Lazy.Encoding (decodeUtf8) import qualified Views.Index import Text.Blaze.Html.Renderer.Text import Network.Wai.Middleware.RequestLogger import Network.Wai.Middleware.Static blaze = html . renderHtml main = scotty 9001 $ do -- Log requests middleware logStdoutDev -- Set up static folder middleware $ staticPolicy (noDots >-> addBase "static") get "/" $ do blaze Views.Index.render matchAny "api/:width/:height" $ do width <- param "width" height <- param "height" html $ mconcat ["Width: ", width, " Height: ", height]
Pholey/place-puppy
Placepuppy/Main.hs
Haskell
mit
680
{-# LANGUAGE BangPatterns, DeriveDataTypeable #-} import System.Console.CmdArgs import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString.Lazy as L import Data.NGH.Alignments import Data.NGH.Formats.Sam import Data.Void import Data.Conduit import Data.Maybe import Data.List (isSuffixOf) import Data.Conduit.Zlib (ungzip) import qualified Data.Conduit.List as CL import qualified Data.Conduit.Binary as CB -- bytes import Data.NGH.Trim import Control.Monad import Data.IORef import Utils data SamCmd = SamCmd { input :: String , output :: String } deriving (Eq, Show, Data, Typeable) samcmds = SamCmd { input = "-" &= argPos 0 &= typ "Input-file" , output = "-" &= argPos 1 &= typ "Output-file" } &= verbosity &= summary sumtext &= details ["Filter non-match queries from SAM files"] where sumtext = "sam-filter v0.1 (C) Luis Pedro Coelho 2012" main :: IO () main = do SamCmd finput foutput <- cmdArgs samcmds v <- getVerbosity let q = v == Quiet total <- newIORef (0.0 :: Double) good <- newIORef (0.0 :: Double) _ <- runResourceT $ readerC finput =$= mayunzip finput =$= CB.lines =$= CL.filter ((/='@').S8.head) =$= counter total =$= CL.filter (\ell -> (isAligned $ readSamLine $ L.fromChunks [ell])) =$= counter good =$= CL.map (\s -> S.concat [s,S8.pack "\n"]) $$ writerC foutput t <- readIORef total g <- readIORef good unless q (putStrLn $ concat ["Processed ", show $ round t, " lines."]) unless q (putStrLn $ concat ["There were matches in ", show $ round g, " (", take 4 $ show (100.0*g/t), "%) of them."])
luispedro/NGH
bin/sam-filter.hs
Haskell
mit
1,832
{-# LANGUAGE OverloadedStrings #-} -- | Data structures needed for interfacing with the Websocket -- Gateway module Network.Discord.Types.Gateway where import Control.Monad (mzero) import System.Info import Data.Aeson import Data.Aeson.Types import Network.WebSockets import Network.Discord.Types.Prelude -- |Represents all sorts of things that we can send to Discord. data Payload = Dispatch Object Integer String | Heartbeat Integer | Identify Auth Bool Integer (Int, Int) | StatusUpdate (Maybe Integer) (Maybe String) | VoiceStatusUpdate {-# UNPACK #-} !Snowflake !(Maybe Snowflake) Bool Bool | Resume String String Integer | Reconnect | RequestGuildMembers {-# UNPACK #-} !Snowflake String Integer | InvalidSession | Hello Int | HeartbeatAck | ParseError String deriving Show instance FromJSON Payload where parseJSON = withObject "payload" $ \o -> do op <- o .: "op" :: Parser Int case op of 0 -> Dispatch <$> o .: "d" <*> o .: "s" <*> o .: "t" 1 -> Heartbeat <$> o .: "d" 7 -> return Reconnect 9 -> return InvalidSession 10 -> (\od -> Hello <$> od .: "heartbeat_interval") =<< o .: "d" 11 -> return HeartbeatAck _ -> mzero instance ToJSON Payload where toJSON (Heartbeat i) = object [ "op" .= (1 :: Int), "d" .= i ] toJSON (Identify token compress large shard) = object [ "op" .= (2 :: Int) , "d" .= object [ "token" .= authToken token , "properties" .= object [ "$os" .= os , "$browser" .= ("discord.hs" :: String) , "$device" .= ("discord.hs" :: String) , "$referrer" .= ("" :: String) , "$referring_domain" .= ("" :: String) ] , "compress" .= compress , "large_threshold" .= large , "shard" .= shard ] ] toJSON (StatusUpdate idle game) = object [ "op" .= (3 :: Int) , "d" .= object [ "idle_since" .= idle , "game" .= object [ "name" .= game ] ] ] toJSON (VoiceStatusUpdate guild channel mute deaf) = object [ "op" .= (4 :: Int) , "d" .= object [ "guild_id" .= guild , "channel_id" .= channel , "self_mute" .= mute , "self_deaf" .= deaf ] ] toJSON (Resume token session seqId) = object [ "op" .= (6 :: Int) , "d" .= object [ "token" .= token , "session_id" .= session , "seq" .= seqId ] ] toJSON (RequestGuildMembers guild query limit) = object [ "op" .= (8 :: Int) , "d" .= object [ "guild_id" .= guild , "query" .= query , "limit" .= limit ] ] toJSON _ = object [] instance WebSocketsData Payload where fromLazyByteString bs = case eitherDecode bs of Right payload -> payload Left reason -> ParseError reason toLazyByteString = encode
jano017/Discord.hs
src/Network/Discord/Types/Gateway.hs
Haskell
mit
3,325
{-# LANGUAGE ViewPatterns #-} module Unison.Util.Set where import Data.Set symmetricDifference :: Ord a => Set a -> Set a -> Set a symmetricDifference a b = (a `difference` b) `union` (b `difference` a) mapMaybe :: (Ord a, Ord b) => (a -> Maybe b) -> Set a -> Set b mapMaybe f s = fromList [ r | (f -> Just r) <- toList s ]
unisonweb/platform
unison-core/src/Unison/Util/Set.hs
Haskell
mit
327
{-# LANGUAGE RecordWildCards #-} module Processor.Sprockell where {------------------------------------------------------------- | | SPROCKELL: Simple PROCessor in hasKELL :-) | | j.kuper@utwente.nl | October 14, 2012 | -------------------------------------------------------------} {------------------------------------------------------------- | Assembly language | Together with function to generate machine code -------------------------------------------------------------} data OpCode = Incr | Decr | Add | Sub | Mul | Div | Mod | Eq | NEq | Gt | Lt | And | Or | Not | NoOp deriving (Eq,Show) data Value = Addr Int | Imm Int deriving (Eq,Show) data Assembly = Load Value Int -- Load (Addr a) r : from "memory a" to "regbank r" -- Load (Imm v) r : put "Int v" in "regbank r" | Store Value Int -- Store (Addr r) a: from "regbank r" to "memory a" -- Store (Imm v) r: put "Int v" in "memory r" | Calc OpCode Int Int Int -- Calc opc r0 r1 r2: "regbank r0" and "regbank r1" go to "alu", -- do "opc", result to "regbank r2" | Jump Int -- JumpAbs n: set program counter to n | CJump Int -- JumpCond n: set program counter to n if bool b is 1 | RJump Int | RCJump Int | EndProg -- end of program, handled bij exec function deriving (Eq,Show) {------------------------------------------------------------- | Machine code -------------------------------------------------------------} data State = State { dmem :: [Int] -- main memory, data memory , regbank :: [Int] -- register bank , pc :: Int -- program counter , cnd :: Int -- condition register (whether condition was true) } deriving (Eq,Show) dmemsize = 8 -- sizes of memory may be extended regbanksize = 8 initstate = State { dmem = replicate dmemsize 0 , regbank = replicate regbanksize (0) , pc = 0 , cnd = 0 } data MachCode = MachCode { loadInstr :: Int -- 0/1: load from dmem to rbank? , imm :: Int -- 0/1: immediate , opc :: OpCode -- opcode , fromaddr :: Int -- address in dmem , toaddr :: Int -- address in dmem , fromreg0 :: Int -- ibid, first parameter of Calc , fromreg1 :: Int -- ibid, second parameter of Calc , toreg :: Int -- ibid, third parameter of Calc , value :: Int -- value from Immediate , jmp :: Int -- 0/1: indicates a jump , cjmp :: Int -- 0/1: indicates a conditional jump , rjmp :: Int -- 0/1: indicates a relative jump , rcjmp :: Int -- 0/1: indicates a relative, conditonal jump , instrnr :: Int -- which instruction to jump to } deriving (Eq,Show) nullcode = MachCode { loadInstr=0, imm=0, opc=NoOp, fromaddr=0, toaddr=0, fromreg0=0, fromreg1=0, toreg=0, value=0, jmp=0, cjmp=0, rjmp=0, rcjmp=0, instrnr=0} {------------------------------------------------------------- | The actual Sprockell -------------------------------------------------------------} tobit True = 1 tobit False = 0 xs <: (0,x) = 0 : tail xs xs <: (i,x) = take i xs ++ [x] ++ drop (i+1) xs op opc = case opc of Incr -> \x0 -> \x1 -> x0+1 -- increment first argument with 1 Decr -> \x0 -> \x1 -> x0-1 -- decrement first argument with 1 Add -> (+) -- goes without saying Sub -> (-) Mul -> (*) Div -> div Mod -> mod Eq -> (tobit.).(==) -- test for equality; result 0 or 1 NEq -> (tobit.).(/=) -- test for inequality Gt -> (tobit.).(>) Lt -> (tobit.).(<) And -> (*) Or -> max Not -> \x0 -> \x1 -> 1-x0 NoOp -> \x0 -> \x1 -> 0 -- result will always be 0 decode instr = case instr of Load (Addr a) r -> nullcode {loadInstr=1, imm=0, fromaddr=a, toreg=r} Load (Imm v) r -> nullcode {loadInstr=1, imm=1, value =v, toreg=r} Store (Addr r) a -> nullcode {imm=0, fromreg0=r, toaddr=a} Store (Imm v) a -> nullcode {imm=1, value =v, toaddr=a} Calc c r0 r1 r2 -> nullcode {loadInstr=0, opc=c, fromreg0=r0, fromreg1=r1, toreg=r2} Jump n -> nullcode {jmp=1, instrnr=n} CJump n -> nullcode {cjmp=1, instrnr=n} RJump n -> nullcode {rjmp=1, instrnr=n} RCJump n -> nullcode {rcjmp=1, instrnr=n} load (regbank,dmem) (loadInstr,fromaddr,toreg,imm,value,y) | loadInstr ==0 = regbank <: (toreg,y) | imm==1 = regbank <: (toreg,value) | imm==0 = regbank <: (toreg,dmem!!fromaddr) store (regbank,dmem) (toaddr,fromreg0,imm,value) | imm==1 = dmem <: (toaddr,value) | imm==0 = dmem <: (toaddr,regbank!!fromreg0) alu opc x0 x1 = (cnd,y) where y = op opc x0 x1 cnd = y `mod` 2 next (pc,jmp,cjmp,rjmp,rcjmp,instrnr,cnd) | jmp == 1 = instrnr | cjmp == 1 && cnd == 1 = instrnr | rjmp == 1 = pc + instrnr | rcjmp == 1 && cnd == 1 = pc + instrnr | otherwise = pc + 1 sprockell prog state tick = State {dmem=dmem',regbank=regbank',pc=pc',cnd=cnd'} where State{..} = state MachCode{..} = decode (prog!!pc) x0 = regbank!!fromreg0 x1 = regbank!!fromreg1 (cnd',y) = alu opc x0 x1 dmem' = store (regbank,dmem) (toaddr,fromreg0,imm,value) regbank' = load (regbank,dmem) (loadInstr,fromaddr,toreg,imm,value,y) pc' = next (pc,jmp,cjmp,rjmp,rcjmp,instrnr,cnd)
thomasbrus/imperia
src/Processor/Sprockell.hs
Haskell
mit
5,676
factors n = [x | x <- [1..n], n `mod` x == 0] perfects :: Int -> [Int] perfects n = [x | x <- [1..n], isPerfect x] where isPerfect n' = sum (factors n') - n' == n' -- using filter but not so good perfects' :: Int -> [Int] perfects' n = [x | x <- [1..n], isPerfect x] where isPerfect n' = sum (filter (/= n') (factors n')) == n' perfects'' :: Int -> [Int] perfects'' n = [x | x <- [1..n], isPerfect x] where isPerfect n' = sum (init (factors n')) == n' perfects''' :: Int -> [Int] perfects''' n = [x | x <- [1..n], isPerfect x] where isPerfect n' = sumFactors n' == n' sumFactors = sum . init . factors main = do print $ perfects 500 print $ perfects' 500 print $ perfects'' 500 print $ perfects''' 500
fabioyamate/programming-in-haskell
ch05/ex04.hs
Haskell
mit
749
module Session where import Data.IntMap (adjust) import PeaCoq isAlive :: SessionState -> Bool isAlive (SessionState alive _) = alive markStale :: SessionState -> SessionState markStale (SessionState _ hs) = SessionState False hs touchSession :: SessionState -> SessionState touchSession (SessionState _ hs) = SessionState True hs adjustSession :: (SessionState -> SessionState) -> Int -> GlobalState -> (GlobalState, ()) adjustSession f mapKey gs = (gs { gActiveSessions = adjust f mapKey (gActiveSessions gs) }, ())
Ptival/peacoq-server
lib/Session.hs
Haskell
mit
542
import Churro.Interpreter import System.Environment import System.IO {- Opens a file and interprets the Churro code. -} main :: IO () main = do{ args <- getArgs ; case args of x:xs -> do{ handle <- openFile x ReadMode ; code <- hGetContents handle ; parseAndInterpret code x } _ -> do{ putStrLn "Usage: churro <filename>.ch" } }
TheLastBanana/Churro
Main.hs
Haskell
mit
475
module Main where import Prelude () import Common import Blas import qualified C import qualified Fortran as F mapFst f (x, y) = (f x, y) convRet config (Just t) = (F.typeMap config t, F.returnConventionMap config t) convRet _ Nothing = (C.Void, F.ReturnValue) convIntent F.In = C.Const convIntent _ = id convParamF config (F.DeclType t a i) = (if a then C.Pointer else applyConvention) . convIntent i $ F.typeMap config t where applyConvention = F.applyParamConvention $ F.paramConventionMap config t convParamC config (F.DeclType t a i) = (if a then C.Pointer . convIntent i else id) $ F.typeMap config t convArg (F.DeclType _ a _, n) = (if a then "" else "&") <> n cWrap config (BFun varTypes func) = convert config . func <$> varTypes convert config (F.FunctionDecl name params ret) = (fDecl, wDecl, "{\n" <> wBody <> "}\n\n") where fDecl = F.applyReturnConvention cvn fName fParams wRet fName = F.mangle config name fParams = (mapFst $ convParamF config) <$> params args = intercalate ", " $ convArg <$> params call args = fName <> "(" <> args <> ");\n" (wRet, cvn) = convRet config ret wDecl = C.FunctionDecl wName wParams wRet wName = modifyName $ toLower <$> name wParams = (mapFst $ convParamC config) <$> params wBody = case cvn of F.ReturnValue -> (<> call args) $ case wRet of C.Void -> " " _ -> " return " F.FirstParamByPointer -> " " <> C.prettyType' wRet "return_value" <> ";\n" <> " " <> call ("&return_value, " <> args) <> " return return_value;\n" showDecl = (<> ";\n\n") . C.prettyFunctionDecl modifyName = ("bls_" <>) main = do let wraps = mconcat $ cWrap F.defaultConfig <$> blasFuns let fDecls = (<$> wraps) $ \ (x, _, _) -> x let wDecls = (<$> wraps) $ \ (_, x, _) -> x let wDefs = (<$> wraps) $ \ (_, decl, body) -> C.prettyFunctionDecl decl <> "\n" <> body let fnRoot = "blas" let headerFn = fnRoot <> ".h" let sourceFn = fnRoot <> ".c" let guardName = "SIINKPBGOYKIBQIVESTPJJLLJJRXQXDVBZSDSRYQ" -- header withFile ("dist/include/" <> headerFn) WriteMode $ \ h -> do hPutStrLn h `mapM_` [ "#ifndef " <> guardName , "#define " <> guardName , "#ifndef HAVE_COMPLEX_TYPEDEFS" , "#include \"complex_typedefs.h\"" , "#endif" , "#ifdef __cplusplus" , "extern \"C\" {" , "#endif" , "" ] hPutStr h `mapM_` (showDecl <$> wDecls) hPutStrLn h `mapM_` [ "#ifdef __cplusplus" , "}" , "#endif" , "#endif" ] -- source withFile ("dist/src/" <> sourceFn) WriteMode $ \ h -> do hPutStrLn h `mapM_` [ "#include \"" <> headerFn <> "\"" ] hPutStr h `mapM_` (showDecl <$> fDecls) hPutStr h `mapM_` wDefs
Rufflewind/blas-shim
Main.hs
Haskell
mit
2,975
xs <- get get >>= (\xs -> put (result : xs)) State (\s -> (s,s)) >>= (\xs -> put (result:xs)) State (\s -> (s,s)) >>= (\xs -> State (\_ -> ((), (result:xs)))) f = (\s -> (s,s)) g = (\xs -> State (\_ -> ((), (result:xs)))) State $ (\s -> let (a,s') = (\s -> (s,s)) s in runState (g a) s' a ~ s s' ~ s reduces to: State $ (\s -> runState (g s) s) (g s) ~ (\xs -> State (\_ -> ((), (result:xs))) (\s -> State (\_ -> ((), result:s))) State (\_ -> ((), result:s)) (\_ -> ((), result:s)) ((), result:s) runState (g a) s' runState ((\xs -> State (\_ -> ((), result:xs)) s) s
JustinUnger/haskell-book
ch23/foo.hs
Haskell
mit
585
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.SVGFEDisplacementMapElement (pattern SVG_CHANNEL_UNKNOWN, pattern SVG_CHANNEL_R, pattern SVG_CHANNEL_G, pattern SVG_CHANNEL_B, pattern SVG_CHANNEL_A, js_getIn1, getIn1, js_getIn2, getIn2, js_getScale, getScale, js_getXChannelSelector, getXChannelSelector, js_getYChannelSelector, getYChannelSelector, SVGFEDisplacementMapElement, castToSVGFEDisplacementMapElement, gTypeSVGFEDisplacementMapElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums pattern SVG_CHANNEL_UNKNOWN = 0 pattern SVG_CHANNEL_R = 1 pattern SVG_CHANNEL_G = 2 pattern SVG_CHANNEL_B = 3 pattern SVG_CHANNEL_A = 4 foreign import javascript unsafe "$1[\"in1\"]" js_getIn1 :: JSRef SVGFEDisplacementMapElement -> IO (JSRef SVGAnimatedString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEDisplacementMapElement.in1 Mozilla SVGFEDisplacementMapElement.in1 documentation> getIn1 :: (MonadIO m) => SVGFEDisplacementMapElement -> m (Maybe SVGAnimatedString) getIn1 self = liftIO ((js_getIn1 (unSVGFEDisplacementMapElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"in2\"]" js_getIn2 :: JSRef SVGFEDisplacementMapElement -> IO (JSRef SVGAnimatedString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEDisplacementMapElement.in2 Mozilla SVGFEDisplacementMapElement.in2 documentation> getIn2 :: (MonadIO m) => SVGFEDisplacementMapElement -> m (Maybe SVGAnimatedString) getIn2 self = liftIO ((js_getIn2 (unSVGFEDisplacementMapElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"scale\"]" js_getScale :: JSRef SVGFEDisplacementMapElement -> IO (JSRef SVGAnimatedNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEDisplacementMapElement.scale Mozilla SVGFEDisplacementMapElement.scale documentation> getScale :: (MonadIO m) => SVGFEDisplacementMapElement -> m (Maybe SVGAnimatedNumber) getScale self = liftIO ((js_getScale (unSVGFEDisplacementMapElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"xChannelSelector\"]" js_getXChannelSelector :: JSRef SVGFEDisplacementMapElement -> IO (JSRef SVGAnimatedEnumeration) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEDisplacementMapElement.xChannelSelector Mozilla SVGFEDisplacementMapElement.xChannelSelector documentation> getXChannelSelector :: (MonadIO m) => SVGFEDisplacementMapElement -> m (Maybe SVGAnimatedEnumeration) getXChannelSelector self = liftIO ((js_getXChannelSelector (unSVGFEDisplacementMapElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"yChannelSelector\"]" js_getYChannelSelector :: JSRef SVGFEDisplacementMapElement -> IO (JSRef SVGAnimatedEnumeration) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEDisplacementMapElement.yChannelSelector Mozilla SVGFEDisplacementMapElement.yChannelSelector documentation> getYChannelSelector :: (MonadIO m) => SVGFEDisplacementMapElement -> m (Maybe SVGAnimatedEnumeration) getYChannelSelector self = liftIO ((js_getYChannelSelector (unSVGFEDisplacementMapElement self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/SVGFEDisplacementMapElement.hs
Haskell
mit
4,146
module GrabBag where -- Question 3a addOneIfOdd n = case odd n of True -> f n False -> n where f = (\n -> n + 1) -- could also do (+1) and get rid of the function -- Question 3b addFive = \x -> \y -> (if x > y then y else x) + 5 -- Question 3c mflip f x y = f y x
rasheedja/HaskellFromFirstPrinciples
Chapter7/grabBag.hs
Haskell
mit
273