code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module TicTacToe (module TicTacToe) where import TicTacToe.Data.Board as TicTacToe import TicTacToe.Data.Cell as TicTacToe import TicTacToe.Data.Move as TicTacToe import TicTacToe.Data.Token as TicTacToe import TicTacToe.Game as TicTacToe
rodamber/haskell-tic-tac-toe
src/TicTacToe.hs
bsd-3-clause
298
0
4
84
49
36
13
6
0
{-# LANGUAGE ExtendedDefaultRules #-} {-# LANGUAGE OverloadedStrings #-} module Controllers.Routes ( routes ) where import Control.Applicative import Data.ByteString (ByteString) import Snap.Snaplet import Snap.Snaplet.Heist import Snap.Util.FileServe import Application import qualified Controllers.Exception as Ex import qualified Controllers.Feed as Feed import Controllers.Home import qualified Controllers.Reply as Reply import qualified Controllers.Tag as Tag import qualified Controllers.Topic as Topic import qualified Controllers.User as User routes :: [(ByteString, Handler App App ())] routes = [ ("/", index) , ("/index", index) ] <|> User.routes <|> Topic.routes <|> Reply.routes <|> Tag.routes <|> Feed.routes <|> [ ("", with heist heistServe) , ("", serveDirectory "static") ] <|> Ex.routes
HaskellCNOrg/snap-web
src/Controllers/Routes.hs
bsd-3-clause
1,089
0
13
381
213
133
80
34
1
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} module Tests ( tests , testsDbInit) where ------------------------------------------------------------------------------ import Control.Error import Control.Monad.State as S import qualified Data.Aeson as A import qualified Data.ByteString.Char8 as BL import qualified Data.HashMap.Lazy as HM import qualified Data.Map as M import Data.Maybe import qualified Data.Text as T import Database.SQLite.Simple import Test.Framework import Test.Framework.Providers.HUnit import Test.HUnit hiding (Test, path) ------------------------------------------------------------------------------ import App import Snap.Snaplet import Snap.Snaplet.Auth import qualified Snap.Snaplet.SqliteSimple as SQ import qualified Snap.Test as ST import Snap.Snaplet.Test ------------------------------------------------------------------------------ tests :: Test tests = mutuallyExclusive $ testGroup "Snap.Snaplet.SqliteSimple" [ testInitDbEmpty , testCreateUserGood , testUpdateUser ] ------------------------------------------------------------------------------ testsDbInit :: Test testsDbInit = mutuallyExclusive $ testGroup "Snap.Snaplet.SqliteSimple" [ -- Empty db testInitDbEmpty , testCreateUserGood , testUpdateUser -- Create empty db with old schema + one user , testInitDbSchema0 , testCreateUserGood , testUpdateUser -- Create empty db, add user in old schema, then access it , testInitDbSchema0WithUser , testUpdateUser -- Create empty db, add user in old schema, then access it, and delete it , testInitDbSchema0 , testCreateUserGood , testDeleteUser -- Create empty db, perform some basic queries , testInitDbSchema0 , testQueries -- Login tests, these use some otherwise uncovered DB backend -- functions. , testInitDbSchema0WithUser , testLoginByRememberTokenKO , testLoginByRememberTokenOK , testLogoutOK , testCurrentUserKO , testCurrentUserOK ] dropTables :: Connection -> IO () dropTables conn = do execute_ conn "DROP TABLE IF EXISTS snap_auth_user" execute_ conn "DROP TABLE IF EXISTS snap_auth_user_version" -- Must be the first on the test list for basic database -- initialization (schema creation for snap_auth_user, etc.) testInitDbEmpty :: Test testInitDbEmpty = testCase "snaplet database init" go where go = do conn <- open "test.db" dropTables conn close conn (_, _handler, _doCleanup) <- runSnaplet Nothing appInit assertBool "init ok" True initSchema0 :: Query initSchema0 = Query $ T.concat [ "CREATE TABLE snap_auth_user (uid INTEGER PRIMARY KEY," , "login text UNIQUE NOT NULL," , "password text," , "activated_at timestamp,suspended_at timestamp,remember_token text," , "login_count INTEGER NOT NULL,failed_login_count INTEGER NOT NULL," , "locked_out_until timestamp,current_login_at timestamp," , "last_login_at timestamp,current_login_ip text," , "last_login_ip text,created_at timestamp,updated_at timestamp);" ] addFooUserSchema0 :: Query addFooUserSchema0 = "INSERT INTO snap_auth_user VALUES(1,'foo',X'7368613235367C31327C39426E5255534356444B4E6A3553716345774E756E513D3D7C633534506C69614A42314E483562677143494651616732454C75444B684F37745A78655479456C4F6F356F3D',NULL,NULL,'2cc0caf41bd7387150cc1416ac38bccc36e64c11a8945f72298ea366ffa8fc97',0,0,NULL,'2012-11-28 21:59:15.150153','2012-11-28 21:59:15.109848',NULL, NULL, '2012-11-28 21:59:15.052817','2012-11-28 21:59:15.052817');" -- Must be the first on the test list for basic database -- initialization (schema creation for snap_auth_user, etc.) testInitDbSchema0 :: Test testInitDbSchema0 = testCase "init db with schema0" $ do conn <- open "test.db" dropTables conn execute_ conn initSchema0 close conn (_, _handler, _doCleanup) <- runSnaplet Nothing appInit assertBool "init ok" True -- Initialize db schema to an empty schema0 and add a user 'foo'. The -- expectation is that snaplet initialization needs to do schema -- migration for the tables and rows. testInitDbSchema0WithUser :: Test testInitDbSchema0WithUser = testCase "init + add foo user directly" $ do conn <- open "test.db" dropTables conn execute_ conn initSchema0 execute_ conn addFooUserSchema0 close conn (_, _handler, _doCleanup) <- runSnaplet Nothing appInit assertBool "init ok" True ------------------------------------------------------------------------------ testCreateUserGood :: Test testCreateUserGood = testCase "createUser good params" assertGoodUser where assertGoodUser :: Assertion assertGoodUser = do let hdl = with auth $ createUser "foo" "foo" res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit either (assertFailure . show) checkUserFields res checkUserFields (Left _) = assertBool "createUser failed: Couldn't create a new user." False checkUserFields (Right u) = do assertEqual "login match" "foo" (userLogin u) assertEqual "login count" 0 (userLoginCount u) assertEqual "fail count" 0 (userFailedLoginCount u) assertEqual "local host ip" Nothing (userCurrentLoginIp u) assertEqual "local host ip" Nothing (userLastLoginIp u) assertEqual "locked until" Nothing (userLockedOutUntil u) assertEqual "empty email" Nothing (userEmail u) assertEqual "roles" [] (userRoles u) assertEqual "meta" HM.empty (userMeta u) ------------------------------------------------------------------------------ -- Create a user, modify it, persist it and load again, check fields ok. -- Must run after testCreateUserGood testUpdateUser :: Test testUpdateUser = testCase "createUser + update good params" assertGoodUser where assertGoodUser :: Assertion assertGoodUser = do let loginHdl = with auth $ loginByUsername "foo" (ClearText "foo") True res <- evalHandler Nothing (ST.get "" M.empty) loginHdl appInit either (assertFailure . show) checkLoggedInUser res checkLoggedInUser (Left _) = assertBool "failed login" False checkLoggedInUser (Right u) = do assertEqual "login count" 1 (userLoginCount u) assertEqual "fail count" 0 (userFailedLoginCount u) assertEqual "locked until" Nothing (userLockedOutUntil u) assertEqual "local host ip" (Just "127.0.0.1") (userCurrentLoginIp u) assertEqual "no previous login" Nothing (userLastLoginIp u) let saveHdl = with auth $ saveUser (u { userLogin = "bar" , userRoles = roles , userMeta = meta }) res <- evalHandler Nothing (ST.get "" M.empty) saveHdl appInit either (assertFailure . show) checkUpdatedUser res roles = [Role $ BL.pack "Superman", Role $ BL.pack "Journalist"] meta = HM.fromList [ (T.pack "email-verified", A.toJSON $ T.pack "yes") , (T.pack "suppress-products", A.toJSON [T.pack "Kryptonite"]) ] checkUpdatedUser (Left _) = assertBool "failed saveUser" False checkUpdatedUser (Right u) = do assertEqual "login rename ok?" "bar" (userLogin u) assertEqual "login count" 1 (userLoginCount u) assertEqual "local host ip" (Just "127.0.0.1") (userCurrentLoginIp u) assertEqual "local host ip" Nothing (userLastLoginIp u) assertEqual "account roles" roles (userRoles u) assertEqual "account meta data" meta (userMeta u) let loginHdl = with auth $ loginByUsername "bar" (ClearText "foo") True res <- evalHandler Nothing (ST.get "" M.empty) loginHdl appInit either (assertFailure . show) (assertBool "login as 'bar' ok?" . isRight) res ------------------------------------------------------------------------------ -- Test that deleting a user works. testDeleteUser :: Test testDeleteUser = testCase "delete a user" assertGoodUser where loginHdl = with auth $ loginByUsername "foo" (ClearText "foo") True assertGoodUser :: Assertion assertGoodUser = do res <- evalHandler Nothing (ST.get "" M.empty) loginHdl appInit either (assertFailure . show) delUser res delUser (Left _) = assertBool "failed login" False delUser (Right u) = do let delHdl = with auth $ destroyUser u Right res <- evalHandler Nothing (ST.get "" M.empty) delHdl appInit res <- evalHandler Nothing (ST.get "" M.empty) loginHdl appInit either (assertFailure . show) (assertBool "login as 'foo' should fail now" . isLeft) res ------------------------------------------------------------------------------ -- Query tests testQueries :: Test testQueries = testCase "basic queries" runTest where queries = do SQ.execute_ "CREATE TABLE foo (id INTEGER PRIMARY KEY, t TEXT)" SQ.execute "INSERT INTO foo (t) VALUES (?)" (Only ("bar" :: String)) [(a :: Int,b :: String)] <- SQ.query_ "SELECT id,t FROM foo" [Only (s :: String)] <- SQ.query "SELECT t FROM foo WHERE id = ?" (Only (1 :: Int)) withTop db . SQ.withSqlite $ \conn -> do a @=? 1 b @=? "bar" s @=? "bar" [Only (v :: Int)] <- query_ conn "SELECT 1+1" v @=? 2 runTest :: Assertion runTest = do r <- evalHandler Nothing (ST.get "" M.empty) queries appInit return () ------------------------------------------------------------------------------ testLoginByRememberTokenKO :: Test testLoginByRememberTokenKO = testCase "loginByRememberToken no token" assertion where assertion :: Assertion assertion = do let hdl = with auth loginByRememberToken res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit either (assertFailure . show) (assertBool failMsg . isLeft) res failMsg = "loginByRememberToken: Expected to fail for the " ++ "absence of a token, but didn't." ------------------------------------------------------------------------------ testLoginByRememberTokenOK :: Test testLoginByRememberTokenOK = testCase "loginByRememberToken token" assertion where assertion :: Assertion assertion = do res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit case res of (Left e) -> assertFailure $ show e (Right res') -> assertBool failMsg $ isRight res' hdl :: Handler App App (Either AuthFailure AuthUser) hdl = with auth $ do res <- loginByUsername "foo" (ClearText "foo") True either (\e -> return (Left e)) (\_ -> loginByRememberToken) res failMsg = "loginByRememberToken: Expected to succeed but didn't." ------------------------------------------------------------------------------ assertLogout :: Handler App App (Maybe AuthUser) -> String -> Assertion assertLogout hdl failMsg = do res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit either (assertFailure . show) (assertBool failMsg . isNothing) res testLogoutOK :: Test testLogoutOK = testCase "logout user logged in." $ assertLogout hdl failMsg where hdl :: Handler App App (Maybe AuthUser) hdl = with auth $ do loginByUsername "foo" (ClearText "foo") True logout mgr <- get return (activeUser mgr) failMsg = "logout: Expected to get Nothing as the active user, " ++ " but didn't." ------------------------------------------------------------------------------ testCurrentUserKO :: Test testCurrentUserKO = testCase "currentUser unsuccesful call" assertion where assertion :: Assertion assertion = do let hdl = with auth currentUser res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit either (assertFailure . show) (assertBool failMsg . isNothing) res failMsg = "currentUser: Expected Nothing as the current user, " ++ " but didn't." ------------------------------------------------------------------------------ testCurrentUserOK :: Test testCurrentUserOK = testCase "successful currentUser call" assertion where assertion :: Assertion assertion = do res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit either (assertFailure . show) (assertBool failMsg . isJust) res hdl :: Handler App App (Maybe AuthUser) hdl = with auth $ do res <- loginByUsername "foo" (ClearText "foo") True either (\_ -> return Nothing) (\_ -> currentUser) res failMsg = "currentUser: Expected to get the current user, " ++ " but didn't."
nurpax/snaplet-sqlite-simple
test/Tests.hs
bsd-3-clause
12,756
0
17
2,811
2,734
1,375
1,359
232
3
{-# OPTIONS_GHC -Wall #-} module Load where import Data.Vector.Storable (Vector) import qualified Data.Vector.Storable as S import Foreign.Ptr (castPtr) import Foreign.ForeignPtr (newForeignPtr_) import qualified Data.ByteString as B import Data.ByteString.Unsafe as B (unsafeUseAsCString) import Data.Bits import Data.List (foldl') import Data.Word (Word8) import Text.Printf data ScanState = WaitingForCarrier Int | FirstEdge Float | BitRead Int Float [Bool] deriving (Eq, Ord, Show, Read) samplesPerBit :: Int samplesPerBit = 104 noDataThreshold :: Float noDataThreshold = 0.005 dataThreshold :: Float dataThreshold = 0.01 type Packet = [Bool] packetToString :: Packet -> String packetToString = map go where go False = '0' go True = '1' statemachine :: (ScanState, [Packet]) -> Float -> (ScanState, [Packet]) statemachine (WaitingForCarrier n, pkts) sample | n > 6 = (FirstEdge sample, pkts) | sample > dataThreshold = (WaitingForCarrier (n + 1), pkts) | otherwise = (WaitingForCarrier 0, pkts) statemachine (FirstEdge lastval, pkts) sample | signum sample /= signum lastval = (BitRead 1 sample [], pkts) | otherwise = (FirstEdge sample, pkts) statemachine (BitRead n acc pkt, pkts) sample | n == samplesPerBit = if abs acc / fromIntegral n < noDataThreshold then (WaitingForCarrier 0, (reverse pkt) : pkts) else (BitRead 1 sample ((signum acc > 0) : pkt), pkts) | otherwise = (BitRead (n + 1) (acc + sample) pkt, pkts) sync :: Word sync = 0xd391d391 toBytes :: [Bool] -> [Word8] toBytes bools | length top8 < 8 = [] | otherwise = conv : toBytes (drop 8 bools) where top8 = take 8 bools conv = foldl' (.|.) 0 $ map (\(b, i) -> if b then bit i else 0) $ zip top8 [7,6..] bitBools :: (FiniteBits a, Bits a) => a -> [Bool] bitBools x = reverse $ map (testBit x) [0..finiteBitSize x - 1] dropTillSync :: [Bool] -> [Bool] dropTillSync [] = [] dropTillSync pkt | take 32 pkt == s = drop 32 pkt | otherwise = dropTillSync $ tail pkt where s = bitBools sync process :: Vector Float -> IO () process vec = putStrLn . unlines . -- map (concat . map (printf "%02X ") . toBytes . dropTillSync) . reverse . snd $ map (concat . map (printf "%c") . toBytes . dropTillSync) . reverse . snd $ S.foldl' statemachine (WaitingForCarrier 0, []) vec load :: IO (Vector Float) load = do smpl <- B.readFile "samples.3" unsafeUseAsCString smpl $ \cstr -> do butts <- newForeignPtr_ $ castPtr cstr let len = B.length smpl `div` 4 return $ S.unsafeFromForeignPtr0 butts len
peddie/lstsdr
src/Load.hs
bsd-3-clause
2,680
0
16
638
1,012
533
479
70
2
{-# LANGUAGE TupleSections #-} module Deque (Deque, mkDeque, push, pop, shift, unshift) where import Control.Applicative ((<$>), (<*>)) import Control.Concurrent.STM ( STM, TMVar, takeTMVar, putTMVar, readTMVar , swapTMVar, atomically, newEmptyTMVar, newTMVar) import Control.Monad (void) data Node a = Node { nodeValue :: a , nodeNext :: TMVar (Node a) , nodePrev :: TMVar (Node a) } instance Eq (Node a) where (Node _ na pa) == (Node _ nb pb) = (na == nb) && (pa == pb) newtype Deque a = Deque { unDeque :: TMVar (Maybe (Node a)) } deriving (Eq) mkNode :: a -> STM (Node a) mkNode a = Node a <$> newEmptyTMVar <*> newEmptyTMVar mkDeque :: IO (Deque a) mkDeque = atomically $ Deque <$> newTMVar Nothing mkRoot :: a -> STM (Node a) mkRoot a = do n <- mkNode a putTMVar (nodeNext n) n putTMVar (nodePrev n) n return n deleteNode :: Node a -> STM (Maybe (Node a)) deleteNode n = do prev <- takeTMVar (nodePrev n) next <- takeTMVar (nodeNext n) if n == prev then return Nothing else do void $ swapTMVar (nodeNext prev) next void $ swapTMVar (nodePrev next) prev return $ Just next mkBefore :: Node a -> a -> STM (Node a) mkBefore front a = do n <- mkNode a back <- swapTMVar (nodePrev front) n void $ swapTMVar (nodeNext back) n putTMVar (nodeNext n) front putTMVar (nodePrev n) back return n withDeque :: STM (Maybe (Node a), b) -> (Node a -> STM (Maybe (Node a), b)) -> Deque a -> IO b withDeque def go d = atomically $ do let var = unDeque d (mFront, r) <- takeTMVar var >>= maybe def go putTMVar var mFront return r voidreturn :: STM a -> STM (a, ()) voidreturn = fmap (, ()) push :: Deque a -> a -> IO () push d a = withDeque (voidreturn $ Just <$> mkRoot a) (voidreturn . go) d where go front = mkBefore front a >> return (Just front) unshift :: Deque a -> a -> IO () unshift d a = withDeque (voidreturn $ Just <$> mkRoot a) (voidreturn . go) d where go front = Just <$> mkBefore front a pop :: Deque a -> IO (Maybe a) pop = withDeque (return (Nothing, Nothing)) go where go front = do back <- readTMVar (nodePrev front) (, Just (nodeValue back)) <$> deleteNode back shift :: Deque a -> IO (Maybe a) shift = withDeque (return (Nothing, Nothing)) go where go front = (, Just (nodeValue front)) <$> deleteNode front
pminten/xhaskell
linked-list/example.hs
mit
2,438
0
13
644
1,118
558
560
66
2
{- | Module : ./Common/SZSOntology.hs Description : The SZS ontology for TPTP prover results Copyright : (c) Christian Maeder DFKI GmbH 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : portable see <http://www.cs.miami.edu/~tptp/> under Documents and SZSOntology -} module Common.SZSOntology where import Data.Char successes :: [(String, String)] successes = [ ("Success", "SUC") -- The logical data has been processed successfully. , ("UnsatisfiabilityPreserving", "UNP") {- If there does not exist a model of Ax then there does not exist a model of C, i.e., if Ax is unsatisfiable then C is unsatisfiable. -} , ("SatisfiabilityPreserving", "SAP") {- If there exists a model of Ax then there exists a model of C, i.e., if Ax is satisfiable then C is satisfiable. - F is satisfiable. -} , ("EquiSatisfiable", "ESA") {- There exists a model of Ax iff there exists a model of C, i.e., Ax is (un)satisfiable iff C is (un)satisfiable. -} , ("Satisfiable", "SAT") {- Some interpretations are models of Ax, and some models of Ax are models of C. - F is satisfiable, and ~F is not valid. - Possible dataforms are Models of Ax | C. -} , ("FinitelySatisfiable", "FSA") {- Some finite interpretations are finite models of Ax, and some finite models of Ax are finite models of C. - F is satisfiable, and ~F is not valid. - Possible dataforms are FiniteModels of Ax | C. -} , ("Theorem", "THM") {- All models of Ax are models of C. - F is valid, and C is a theorem of Ax. - Possible dataforms are Proofs of C from Ax. -} , ("Equivalent", "EQV") {- Some interpretations are models of Ax, all models of Ax are models of C, and all models of C are models of Ax. - F is valid, C is a theorem of Ax, and Ax is a theorem of C. - Possible dataforms are Proofs of C from Ax and of Ax from C. -} , ("TautologousConclusion", "TAC") {- Some interpretations are models of Ax, and all interpretations are models of C. - F is valid, and C is a tautology. - Possible dataforms are Proofs of C. -} , ("WeakerConclusion", "WEC") {- Some interpretations are models of Ax, all models of Ax are models of C, and some models of C are not models of Ax. - See Theorem and Satisfiable. -} , ("EquivalentTheorem", "ETH") {- Some, but not all, interpretations are models of Ax, all models of Ax are models of C, and all models of C are models of Ax. - See Equivalent. -} , ("Tautology", "TAU") {- All interpretations are models of Ax, and all interpretations are models of C. - F is valid, ~F is unsatisfiable, and C is a tautology. - Possible dataforms are Proofs of Ax and of C. -} , ("WeakerTautologousConclusion", "WTC") {- Some, but not all, interpretations are models of Ax, and all interpretations are models of C. - F is valid, and C is a tautology. - See TautologousConclusion and WeakerConclusion. -} , ("WeakerTheorem", "WTH") {- Some interpretations are models of Ax, all models of Ax are models of C, some models of C are not models of Ax, and some interpretations are not models of C. - See Theorem and Satisfiable. -} , ("ContradictoryAxioms", "CAX") {- No interpretations are models of Ax. - F is valid, and anything is a theorem of Ax. - Possible dataforms are Refutations of Ax. -} , ("SatisfiableConclusionContradictoryAxioms", "SCA") {- No interpretations are models of Ax, and some interpretations are models of C. - See ContradictoryAxioms. -} , ("TautologousConclusionContradictoryAxioms", "TCA") {- No interpretations are models of Ax, and all interpretations are models of C. - See TautologousConclusion and SatisfiableConclusionContradictoryAxioms. -} , ("WeakerConclusionContradictoryAxioms", "WCA") {- No interpretations are models of Ax, and some, but not all, interpretations are models of C. - See SatisfiableConclusionContradictoryAxioms and SatisfiableCounterConclusionContradictoryAxioms. -} , ("CounterUnsatisfiabilityPreserving", "CUP") {- If there does not exist a model of Ax then there does not exist a model of ~C, i.e., if Ax is unsatisfiable then ~C is unsatisfiable. -} , ("CounterSatisfiabilityPreserving", "CSP") {- If there exists a model of Ax then there exists a model of ~C, i.e., if Ax is satisfiable then ~C is satisfiable. -} , ("EquiCounterSatisfiable", "ECS") {- There exists a model of Ax iff there exists a model of ~C, i.e., Ax is (un)satisfiable iff ~C is (un)satisfiable. -} , ("CounterSatisfiable", "CSA") {- Some interpretations are models of Ax, and some models of Ax are models of ~C. - F is not valid, ~F is satisfiable, and C is not a theorem of Ax. - Possible dataforms are Models of Ax | ~C. -} , ("CounterTheorem", "CTH") {- All models of Ax are models of ~C. - F is not valid, and ~C is a theorem of Ax. - Possible dataforms are Proofs of ~C from Ax. -} , ("CounterEquivalent", "CEQ") {- Some interpretations are models of Ax, all models of Ax are models of ~C, and all models of ~C are models of Ax (i.e., all interpretations are models of Ax xor of C). - F is not valid, and ~C is a theorem of Ax. - Possible dataforms are Proofs of ~C from Ax and of Ax from ~C. -} , ("UnsatisfiableConclusion", "UNC") {- Some interpretations are models of Ax, and all interpretations are models of ~C (i.e., no interpretations are models of C). - F is not valid, and ~C is a tautology. - Possible dataforms are Proofs of ~C. -} , ("WeakerCounterConclusion", "WCC") {- Some interpretations are models of Ax, and all models of Ax are models of ~C, and some models of ~C are not models of Ax. - See CounterTheorem and CounterSatisfiable. -} , ("EquivalentCounterTheorem", "ECT") {- Some, but not all, interpretations are models of Ax, all models of Ax are models of ~C, and all models of ~C are models of Ax. - See CounterEquivalent. -} , ("FinitelyUnsatisfiable", "FUN") {- All finite interpretations are finite models of Ax, and all finite interpretations are finite models of ~C (i.e., no finite interpretations are finite models of C). -} , ("Unsatisfiable", "UNS") {- All interpretations are models of Ax, and all interpretations are models of ~C. (i.e., no interpretations are models of C). - F is unsatisfiable, ~F is valid, and ~C is a tautology. - Possible dataforms are Proofs of Ax and of C, and Refutations of F. -} , ("WeakerUnsatisfiableConclusion", "WUC") {- Some, but not all, interpretations are models of Ax, and all interpretations are models of ~C. - See Unsatisfiable and WeakerCounterConclusion. -} , ("WeakerCounterTheorem", "WCT") {- Some interpretations are models of Ax, all models of Ax are models of ~C, some models of ~C are not models of Ax, and some interpretations are not models of ~C. - See CounterSatisfiable. -} , ("SatisfiableCounterConclusionContradictoryAxioms", "SCC") {- No interpretations are models of Ax, and some interpretations are models of ~C. - See ContradictoryAxioms. -} , ("UnsatisfiableConclusionContradictoryAxioms", "UCA") {- No interpretations are models of Ax, and all interpretations are models of ~C (i.e., no interpretations are models of C). - See UnsatisfiableConclusion and - SatisfiableCounterConclusionContradictoryAxioms. -} , ("NoConsequence", "NOC") ] {- Some interpretations are models of Ax, some models of Ax are models of C, and some models of Ax are models of ~C. - F is not valid, F is satisfiable, ~F is not valid, ~F is satisfiable, and C is not a theorem of Ax. - Possible dataforms are pairs of models, one Model of Ax | C and one Model of Ax | ~C. -} nosuccess :: [(String, String)] nosuccess = [ ("NoSuccess", "NOS") -- The logical data has not been processed successfully (yet). , ("Open", "OPN") -- A success value has never been established. , ("Unknown", "UNK") -- Success value unknown, and no assumption has been made. , ("Assumed", "ASS(U,S)") {- The success ontology value S has been assumed because the actual value is unknown for the no-success ontology reason U. U is taken from the subontology starting at Unknown in the no-success ontology. -} , ("Stopped", "STP") {- Software attempted to process the data, and stopped without a success status. -} , ("Error", "ERR") -- Software stopped due to an error. , ("OSError", "OSE") -- Software stopped due to an operating system error. , ("InputError", "INE") -- Software stopped due to an input error. , ("SyntaxError", "SYE") -- Software stopped due to an input syntax error. , ("SemanticError", "SEE") -- Software stopped due to an input semantic error. , ("TypeError", "TYE") -- Software stopped due to an input type error (for typed logical data). , ("Forced", "FOR") -- Software was forced to stop by an external force. , ("User", "USR") -- Software was forced to stop by the user. , ("ResourceOut", "RSO") -- Software stopped because some resource ran out. , ("Timeout", "TMO") -- Software stopped because the CPU time limit ran out. , ("MemoryOut", "MMO") -- Software stopped because the memory limit ran out. , ("GaveUp", "GUP") -- Software gave up of its own accord. , ("Incomplete", "INC") -- Software gave up because it's incomplete. , ("Inappropriate", "IAP") -- Software gave up because it cannot process this type of data. , ("InProgress", "INP") -- Software is still running. , ("NotTried", "NTT") -- Software has not tried to process the data. , ("NotTriedYet", "NTY") ] -- Software has not tried to process the data yet, but might in the future. szsCheck :: [(String, String)] -> [String] -> String -> Bool szsCheck pl l = maybe False (`elem` l) . (`lookup` map (\ (t, r) -> (map toLower t, r)) pl) . map toLower szsProved :: String -> Bool szsProved = szsCheck successes ["SAT", "THM"] szsDisproved :: String -> Bool szsDisproved = szsCheck successes ["CSA", "UNS"] szsTimeout :: String -> Bool szsTimeout = szsCheck nosuccess ["TMO", "RSO"] szsMemoryOut :: String -> Bool szsMemoryOut = szsCheck nosuccess ["MMO"] szsStopped :: String -> Bool szsStopped = szsCheck nosuccess ["STP"]
spechub/Hets
Common/SZSOntology.hs
gpl-2.0
10,338
0
12
2,158
826
546
280
75
1
{-# LANGUAGE DeriveDataTypeable #-} {- | Module : ./Modal/AS_Modal.der.hs Copyright : (c) T.Mossakowski, W.Herding, C.Maeder, Uni Bremen 2004-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : till@informatik.uni-bremen.de Stability : provisional Portability : portable Abstract syntax for modal logic extension of CASL Only the added syntax is specified -} module Modal.AS_Modal where import Common.Id import Common.AS_Annotation import CASL.AS_Basic_CASL import Data.Data -- DrIFT command {-! global: GetRange !-} type M_BASIC_SPEC = BASIC_SPEC M_BASIC_ITEM M_SIG_ITEM M_FORMULA type AnModFORM = Annoted (FORMULA M_FORMULA) data M_BASIC_ITEM = Simple_mod_decl [Annoted SIMPLE_ID] [AnModFORM] Range | Term_mod_decl [Annoted SORT] [AnModFORM] Range deriving (Show, Typeable, Data) data RIGOR = Rigid | Flexible deriving (Show, Typeable, Data) data M_SIG_ITEM = Rigid_op_items RIGOR [Annoted (OP_ITEM M_FORMULA)] Range -- pos: op, semi colons | Rigid_pred_items RIGOR [Annoted (PRED_ITEM M_FORMULA)] Range -- pos: pred, semi colons deriving (Show, Typeable, Data) data MODALITY = Simple_mod SIMPLE_ID | Term_mod (TERM M_FORMULA) deriving (Show, Eq, Ord, Typeable, Data) data M_FORMULA = BoxOrDiamond Bool MODALITY (FORMULA M_FORMULA) Range {- The identifier and the term specify the kind of the modality pos: "[]" or "<>", True if Box, False if Diamond -} deriving (Show, Eq, Ord, Typeable, Data)
spechub/Hets
Modal/AS_Modal.der.hs
gpl-2.0
1,601
0
10
386
289
160
129
20
0
{- - Copyright 2011-2014 Per Magnus Therning - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -} module Upgrades ( upgrades ) where import PkgDB import Util.Misc import Util.HackageIndex import Util.Cfg import Control.Applicative import Control.Arrow import Control.Monad.Reader import Data.Maybe import Distribution.Text import Distribution.Version hiding (thisVersion) upgrades :: Command () upgrades = do db <- asks (dbFile . fst) >>= liftIO . readDb aD <- asks $ appDir . fst aCS <- asks $ idxStyle .optsCmd . fst xrevsOnly <- asks $ xrevs . optsCmd . fst cfg <- asks snd availPkgsNVers <- liftIO $ buildPkgVersions <$> readIndexFile aD (getIndexFileName cfg) let nonBasePkgs = filter (not . isBasePkg) db pkgsNVers = map (pkgName &&& pkgVersion &&& pkgXRev) nonBasePkgs filterFunc = if xrevsOnly then (\ (p, (v, x)) -> maybe False (> x) (snd <$> thisVersion availPkgsNVers p v)) else (\ (p, vx) -> maybe False (> vx) (latestVersion availPkgsNVers p undefined)) outdated = filter filterFunc pkgsNVers printer = if aCS then printNewShort else printUpgrades if xrevsOnly then liftIO $ mapM_ (printer thisVersion availPkgsNVers) outdated else liftIO $ mapM_ (printer latestVersion availPkgsNVers) outdated printUpgrades verFunc avail (pkgName, (pkgVer, pkgXRev)) = putStrLn $ pkgName ++ ": " ++ display pkgVer ++ ":x" ++ show pkgXRev ++ " (" ++ display lv ++ ":x" ++ show lx ++ ")" where (lv, lx) = fromJust $ verFunc avail pkgName pkgVer printNewShort verFunc avail (pkgName, (pkgVer, _)) = putStrLn $ pkgName ++ "," ++ display l where l = fst $ fromJust $ verFunc avail pkgName pkgVer
mmhat/cblrepo
src/Upgrades.hs
apache-2.0
2,247
1
16
498
560
295
265
38
4
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} module SDL.Internal.Types ( WindowID(..) , Joystick(..) , Window(..) , Renderer(..) ) where import Data.Data (Data) import Data.Typeable import Foreign import GHC.Generics (Generic) import qualified SDL.Raw as Raw newtype WindowID = WindowID Word32 deriving (Data, Eq, Generic, Read, Ord, Show, Typeable) newtype Joystick = Joystick { joystickPtr :: Raw.Joystick } deriving (Data, Eq, Generic, Ord, Show, Typeable) newtype Window = Window (Raw.Window) deriving (Data, Eq, Generic, Ord, Show, Typeable) newtype Renderer = Renderer Raw.Renderer deriving (Data, Eq, Generic, Ord, Show, Typeable)
svenkeidel/sdl2
src/SDL/Internal/Types.hs
bsd-3-clause
684
0
7
112
233
138
95
20
0
{-# LANGUAGE TypeFamilies, Rank2Types, FlexibleContexts, DeriveGeneric, TemplateHaskell, UndecidableInstances, ConstraintKinds, DeriveDataTypeable , ScopedTypeVariables, DataKinds #-} {-# OPTIONS -W -ddump-splices #-} module Tests.Embed (allTests) where import Language.Hakaru.Syntax (Hakaru(..), Order(..), Base(..), ununit, and_, fst_, snd_, swap_, min_, Mochastic(..), Lambda(..), Integrate(..), bind_, liftM, factor, beta, bern, lam) import Language.Hakaru.Util.Pretty (Pretty (pretty), prettyPair) import Control.Monad (zipWithM_, replicateM) import Control.Applicative (Const(Const)) import Text.PrettyPrint (text, (<>), ($$), nest) import Data.Function(on) import Language.Hakaru.Sample import Language.Hakaru.Embed import Language.Hakaru.Maple import Language.Hakaru.Simplify import Control.Exception import Data.Typeable import Test.HUnit import Tests.TestTools import Language.Hakaru.Any (Any(unAny)) import Tests.EmbedDatatypes -- Variant of testSS for Embeddable a type TesteeEmbed a = forall repr. (Mochastic repr, Integrate repr, Lambda repr, Embed repr) => repr a testSE :: (Simplifiable a) => TesteeEmbed a -> Assertion testSE t = do p <- simplify t `catch` handleSimplify t let s = result (unAny p) assertResult (show s) testSSE :: (Simplifiable a) => [Maple a] -> TesteeEmbed a -> Assertion testSSE ts t' = mapM_ (\t -> do p <- simplify t --`catch` handleSimplify t (assertEqual "testSS" `on` result) t' (unAny p)) (t' : ts) -- YT: All of these tests should work now, but Maple seems to be broken as of -- writing this because the names of all the built-in identifies have changed -- (Measure to HMeasure) and Maple doesn't emit the new names yet, so they -- haven't been run. allTests :: Test allTests = test [ "pair-elim" ~: testSSE [t1] (uniform 1 2) , "P2-elim" ~: testSSE [t0] (uniform 1 2) , "P2-id" ~: testSSE [t3] t3 , "List-id" ~: testSSE [testList0] testList0 ] testList0 :: Embed r => r (List HInt) testList0 = fromL [1, 2, 3, 4] t0 :: forall repr . (Mochastic repr, Embed repr) => repr (HMeasure HReal) t0 = case_ (p2 1 2) (NFn (\x y -> uniform (unKonst x) (unKonst y)) :* Nil) t1 :: forall repr . (Mochastic repr) => repr (HMeasure HReal) t1 = unpair (pair 1 2) uniform t3 :: (Mochastic repr, Embed repr) => repr (HMeasure (P2 HInt HReal)) t3 = dirac (p2 1 2) norm :: (Embed repr, Mochastic repr) => repr (HMeasure (P2 HReal HReal)) norm = normal 0 1 `bind` \x -> normal x 1 `bind` \y -> dirac (p2 x y)
bitemyapp/hakaru
Tests/Embed.hs
bsd-3-clause
2,549
0
13
483
868
487
381
53
1
{-# LANGUAGE NoImplicitPrelude #-} -- | -- Module: $HEADER$ -- Description: Test cases for Data.DHT.DKS.Type.StateMachine module. -- Copyright: (c) 2015, Jan Šipr, Matej Kollár, Peter Trško -- License: BSD3 -- -- Stability: stable -- Portability: NoImplicitPrelude -- -- Test cases for "Data.DHT.DKS.Type.StateMachine" module. module TestCase.Data.DHT.DKS.StateMachine (tests) where --import Test.HUnit (Assertion, assertBool, assertFailure) import Test.Framework (Test) --import Test.Framework.Providers.HUnit (testCase) --import Data.DHT.DKS.StateMachine tests :: [Test] tests = []
FPBrno/dht-dks
test/TestCase/Data/DHT/DKS/StateMachine.hs
bsd-3-clause
612
0
5
91
53
39
14
5
1
----------------------------------------------------------------------------- -- | -- Module : Language.Python.Common.ParseError -- Copyright : (c) 2009 Bernie Pope -- License : BSD-style -- Maintainer : bjpop@csse.unimelb.edu.au -- Stability : experimental -- Portability : ghc -- -- Error values for the lexer and parser. ----------------------------------------------------------------------------- module Language.Python.Common.ParseError ( ParseError (..) ) where import Language.Python.Common.Pretty import Language.Python.Common.SrcLocation (SrcLocation) import Language.Python.Common.Token (Token) import Control.Monad.Error.Class data ParseError = UnexpectedToken Token -- ^ An error from the parser. Token found where it should not be. Note: tokens contain their own source span. | UnexpectedChar Char SrcLocation -- ^ An error from the lexer. Character found where it should not be. | StrError String -- ^ A generic error containing a string message. No source location. deriving (Eq, Ord, Show) instance Error ParseError where noMsg = StrError "" strMsg = StrError
jml/language-python
src/Language/Python/Common/ParseError.hs
bsd-3-clause
1,144
0
6
198
126
83
43
13
0
module Scene ( Scene , Intersection(..) , mkScene , sceneIntersection , pointLightSources ) where import Data.List ( minimumBy ) import Data.Maybe ( mapMaybe ) import Data.Ord ( comparing ) import Core ( Ray, RayPosition, Point, at ) import Light ( PointLightSource ) import Surface ( Surface, intersection ) data Scene = Scene [Surface] [PointLightSource] data Intersection = Intersection { rayTested :: Ray , surface :: Surface , rayPosition :: RayPosition , worldPosition :: Point } mkScene :: [Surface] -> [PointLightSource] -> Scene mkScene = Scene sceneIntersection :: Scene -> Ray -> Maybe Intersection sceneIntersection (Scene surfaces _) ray = minimumBy (comparing rayPosition) <$> maybeIntersections where allIntersections = mapMaybe (renderableIntersection ray) surfaces maybeIntersections = maybeList allIntersections maybeList [] = Nothing maybeList xs@(_:_) = Just xs renderableIntersection :: Ray -> Surface -> Maybe Intersection renderableIntersection ray sfc = toIntersection <$> intersection sfc ray where toIntersection t = Intersection { rayTested = ray , surface = sfc , rayPosition = t , worldPosition = ray `at` t } pointLightSources :: Scene -> [PointLightSource] pointLightSources (Scene _ !pls) = pls
stu-smith/rendering-in-haskell
src/experiment04/Scene.hs
mit
1,491
0
10
440
375
213
162
-1
-1
module Main where fib :: Int -> Int fib n = if n < 2 then 1 else fib (n-1) + fib (n-2) main :: IO () main = putStrLn $ "fib 30 = " ++ show (fib 30)
conal/hermit
examples/Talks/hermit-machine/Fib.hs
bsd-2-clause
168
0
9
59
89
47
42
7
2
module List (listModules) where import Control.Applicative import Data.List import GHC import GHCApi import Packages import Types import UniqFM ---------------------------------------------------------------- listModules :: Options -> IO String listModules opt = convert opt . nub . sort <$> list opt list :: Options -> IO [String] list opt = withGHC $ do _ <- initSession0 opt getExposedModules <$> getSessionDynFlags where getExposedModules = map moduleNameString . concatMap exposedModules . eltsUFM . pkgIdMap . pkgState
syohex/ghc-mod
List.hs
bsd-3-clause
587
0
11
132
146
76
70
17
1
{-| Ganeti query daemon -} {- Copyright (C) 2009, 2011, 2012, 2013 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Main (main) where import qualified Ganeti.Query.Server import Ganeti.Daemon import Ganeti.Runtime -- | Options list and functions. options :: [OptType] options = [ oNoDaemonize , oNoUserChecks , oDebug , oSyslogUsage ] -- | Main function. main :: IO () main = genericMain GanetiLuxid options Ganeti.Query.Server.checkMain Ganeti.Query.Server.prepMain Ganeti.Query.Server.main
vladimir-ipatov/ganeti
src/hluxid.hs
gpl-2.0
1,179
0
6
211
93
59
34
16
1
module WhereIn2 where f = (case (x, y, z) of (1, y, z) -> y + z (x, y, z) -> z) where (x, y, z) = g 42 g x = (1, 2, x) f_1 = (case (x, y, z) of (1, y, z) -> return 0 (x, y, z) -> return 1) where (x, y, z) = g 42 g x = (1, 2, x)
mpickering/HaRe
old/testing/simplifyExpr/WhereIn2AST.hs
bsd-3-clause
317
0
9
156
190
111
79
11
2
{-# LANGUAGE TypeOperators, GADTs #-} -- Enable -Werror to fail in case we get this warning: -- -- UNPACK pragma lacks '!' on the first argument of ‘A’ -- -- In this test case we expect to get this warning and fail, -- see T14761c for the opposite. {-# OPTIONS -Werror #-} module T14761a where data A = A { a :: {-# UNPACK #-} Maybe Int } data x && y = Pair x y data B = B { b :: {-# UNPACK #-} Maybe Int && [] Char && Int } data G where MkG2 :: {-# UNPACK #-} Maybe Int && [] Char && Int -> G
sdiehl/ghc
testsuite/tests/typecheck/should_fail/T14761a.hs
bsd-3-clause
508
0
12
121
107
63
44
14
0
-- $Id: SVCOps.hs,v 1.1 2001/07/19 22:36:04 wlh Exp $ module SVCOps (getHOLTyCon, getSVCOp) where --- Now the first bit in "(tf, string)" means: is it an --- *interpreted* function symbol? N.b., all operators are --- prefix in SVC. svcOps = [ ("True", (True, "true")), ("False", (True, "false")), ("+", (True, "+")), ("*", (True, "*")), ("not", (False, "not")), ("&&&", (False, "and")), ("|||", (False, "or")), ("==>", (False, "=>")), ("===", (False, "=")) ] -- lookup n db = filter ((== n) . fst) db getSVCOp :: String -> Maybe (Bool, String) getSVCOp n = lookup n svcOps --- Probably not needed for SVC: getHOLTyCon :: String -> Maybe String getHOLTyCon con = lookup con holTyCons holTyCons = [ ("[]", "list"), ("()", "unit"), ("Int", "int"), ("Nat", "num") ]
forste/haReFork
tools/pg2svc/SVCOps.hs
bsd-3-clause
935
2
7
296
257
163
94
18
1
module T13604 where
shlevy/ghc
testsuite/tests/driver/T13604.hs
bsd-3-clause
20
0
2
3
4
3
1
1
0
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Text.Read -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : provisional -- Portability : non-portable (uses Text.ParserCombinators.ReadP) -- -- Converting strings to values. -- -- The "Text.Read" library is the canonical library to import for -- 'Read'-class facilities. For GHC only, it offers an extended and much -- improved 'Read' class, which constitutes a proposed alternative to the -- Haskell 2010 'Read'. In particular, writing parsers is easier, and -- the parsers are much more efficient. -- ----------------------------------------------------------------------------- module Text.Read ( -- * The 'Read' class Read(..), ReadS, -- * Haskell 2010 functions reads, read, readParen, lex, -- * New parsing functions module Text.ParserCombinators.ReadPrec, L.Lexeme(..), lexP, parens, readListDefault, readListPrecDefault, readEither, readMaybe ) where import GHC.Base import GHC.Read import Data.Either import Text.ParserCombinators.ReadP as P import Text.ParserCombinators.ReadPrec import qualified Text.Read.Lex as L ------------------------------------------------------------------------ -- utility functions -- | equivalent to 'readsPrec' with a precedence of 0. reads :: Read a => ReadS a reads = readsPrec minPrec -- | Parse a string using the 'Read' instance. -- Succeeds if there is exactly one valid result. -- A 'Left' value indicates a parse error. -- -- @since 4.6.0.0 readEither :: Read a => String -> Either String a readEither s = case [ x | (x,"") <- readPrec_to_S read' minPrec s ] of [x] -> Right x [] -> Left "Prelude.read: no parse" _ -> Left "Prelude.read: ambiguous parse" where read' = do x <- readPrec lift P.skipSpaces return x -- | Parse a string using the 'Read' instance. -- Succeeds if there is exactly one valid result. -- -- @since 4.6.0.0 readMaybe :: Read a => String -> Maybe a readMaybe s = case readEither s of Left _ -> Nothing Right a -> Just a -- | The 'read' function reads input from a string, which must be -- completely consumed by the input process. read :: Read a => String -> a read s = either errorWithoutStackTrace id (readEither s)
tolysz/prepare-ghcjs
spec-lts8/base/Text/Read.hs
bsd-3-clause
2,521
0
10
506
372
217
155
41
3
{-# LANGUAGE QuasiQuotes #-} module Futhark.CodeGen.OpenCL.Kernels ( SizeHeuristic (..) , DeviceType (..) , WhichSize (..) , HeuristicValue (..) , sizeHeuristicsTable , mapTranspose , TransposeType(..) ) where import qualified Language.C.Syntax as C import qualified Language.C.Quote.OpenCL as C -- Some OpenCL platforms have a SIMD/warp/wavefront-based execution -- model that execute groups of threads in lockstep, permitting us to -- perform cross-thread synchronisation within each such group without -- the use of barriers. Unfortunately, there seems to be no reliable -- way to query these sizes at runtime. Instead, we use this table to -- figure out which size we should use for a specific platform and -- device. If nothing matches here, the wave size should be set to -- one. -- -- We also use this to select reasonable default group sizes and group -- counts. -- | The type of OpenCL device that this heuristic applies to. data DeviceType = DeviceCPU | DeviceGPU -- | The value supplies by a heuristic can be a constant, or inferred -- from some device information. data HeuristicValue = HeuristicConst Int | HeuristicDeviceInfo String -- | A size that can be assigned a default. data WhichSize = LockstepWidth | NumGroups | GroupSize -- | A heuristic for setting the default value for something. data SizeHeuristic = SizeHeuristic { platformName :: String , deviceType :: DeviceType , heuristicSize :: WhichSize , heuristicValue :: HeuristicValue } -- | All of our heuristics. sizeHeuristicsTable :: [SizeHeuristic] sizeHeuristicsTable = [ SizeHeuristic "NVIDIA CUDA" DeviceGPU LockstepWidth $ HeuristicConst 32 , SizeHeuristic "AMD Accelerated Parallel Processing" DeviceGPU LockstepWidth $ HeuristicConst 64 , SizeHeuristic "" DeviceGPU LockstepWidth $ HeuristicConst 1 , SizeHeuristic "" DeviceGPU NumGroups $ HeuristicConst 128 , SizeHeuristic "" DeviceGPU GroupSize $ HeuristicConst 256 , SizeHeuristic "" DeviceCPU LockstepWidth $ HeuristicConst 1 , SizeHeuristic "" DeviceCPU NumGroups $ HeuristicDeviceInfo "MAX_COMPUTE_UNITS" , SizeHeuristic "" DeviceCPU GroupSize $ HeuristicConst 32 ] data TransposeType = TransposeNormal | TransposeLowWidth | TransposeLowHeight deriving (Eq, Ord, Show) -- | @mapTranspose name elem_type transpose_type@ Generate a transpose kernel -- with requested @name@ for elements of type @elem_type@. There are special -- support to handle input arrays with low width or low height, which can be -- indicated by @transpose_type@. -- -- Normally when transposing a @[2][n]@ array we would use a @FUT_BLOCK_DIM x -- FUT_BLOCK_DIM@ group to process a @[2][FUT_BLOCK_DIM]@ slice of the input -- array. This would mean that many of the threads in a group would be inactive. -- We try to remedy this by using a special kernel that will process a larger -- part of the input, by using more complex indexing. In our example, we could -- use all threads in a group if we are processing @(2/FUT_BLOCK_DIM)@ as large -- a slice of each rows per group. The variable 'mulx' contains this factor for -- the kernel to handle input arrays with low height. -- -- See issue #308 on GitHub for more details. mapTranspose :: C.ToIdent a => a -> C.Type -> TransposeType -> C.Func mapTranspose kernel_name elem_type transpose_type = [C.cfun| // This kernel is optimized to ensure all global reads and writes are coalesced, // and to avoid bank conflicts in shared memory. The shared memory array is sized // to (BLOCK_DIM+1)*BLOCK_DIM. This pads each row of the 2D block in shared memory // so that bank conflicts do not occur when threads address the array column-wise. // // Note that input_size/output_size may not equal width*height if we are dealing with // a truncated array - this happens sometimes for coalescing optimisations. __kernel void $id:kernel_name($params:params) { uint x_index; uint y_index; uint our_array_offset; // Adjust the input and output arrays with the basic offset. odata += odata_offset/sizeof($ty:elem_type); idata += idata_offset/sizeof($ty:elem_type); // Adjust the input and output arrays for the third dimension. our_array_offset = get_global_id(2) * width * height; odata += our_array_offset; idata += our_array_offset; // read the matrix tile into shared memory x_index = $exp:x_in_index; y_index = $exp:y_in_index; uint index_in = y_index * width + x_index; if(x_index < width && y_index < height && index_in < input_size) { block[get_local_id(1)*(FUT_BLOCK_DIM+1)+get_local_id(0)] = idata[index_in]; } barrier(CLK_LOCAL_MEM_FENCE); // Scatter the transposed matrix tile to global memory. x_index = $exp:x_out_index; y_index = $exp:y_out_index; uint index_out = y_index * height + x_index; if(x_index < height && y_index < width && index_out < output_size) { odata[index_out] = block[get_local_id(0)*(FUT_BLOCK_DIM+1)+get_local_id(1)]; } }|] where extraparams = case transpose_type of TransposeNormal -> [] TransposeLowWidth -> [C.cparams|uint muly|] TransposeLowHeight -> [C.cparams|uint mulx|] params = [C.cparams|__global $ty:elem_type *odata, uint odata_offset, __global $ty:elem_type *idata, uint idata_offset, uint width, uint height, uint input_size, uint output_size|] ++ extraparams ++ [C.cparams|__local $ty:elem_type* block|] x_in_index = case transpose_type of TransposeNormal -> [C.cexp|get_global_id(0)|] TransposeLowWidth -> [C.cexp|get_group_id(0) * FUT_BLOCK_DIM + (get_local_id(0) / muly)|] TransposeLowHeight -> [C.cexp|get_group_id(0) * FUT_BLOCK_DIM * mulx + get_local_id(0) + (get_local_id(1) % mulx) * FUT_BLOCK_DIM |] y_in_index = case transpose_type of TransposeNormal -> [C.cexp|get_global_id(1)|] TransposeLowWidth -> [C.cexp|get_group_id(1) * FUT_BLOCK_DIM * muly + get_local_id(1) + (get_local_id(0) % muly) * FUT_BLOCK_DIM |] TransposeLowHeight -> [C.cexp|get_group_id(1) * FUT_BLOCK_DIM + (get_local_id(1) / mulx)|] x_out_index = case transpose_type of TransposeNormal -> [C.cexp|get_group_id(1) * FUT_BLOCK_DIM + get_local_id(0)|] TransposeLowWidth -> [C.cexp|get_group_id(1) * FUT_BLOCK_DIM * muly + get_local_id(0) + (get_local_id(1) % muly) * FUT_BLOCK_DIM|] TransposeLowHeight -> [C.cexp|get_group_id(1) * FUT_BLOCK_DIM + (get_local_id(0) / mulx)|] y_out_index = case transpose_type of TransposeNormal -> [C.cexp|get_group_id(0) * FUT_BLOCK_DIM + get_local_id(1)|] TransposeLowWidth -> [C.cexp|get_group_id(0) * FUT_BLOCK_DIM + (get_local_id(1) / muly)|] TransposeLowHeight -> [C.cexp|get_group_id(0) * FUT_BLOCK_DIM * mulx + get_local_id(1) + (get_local_id(0) % mulx) * FUT_BLOCK_DIM |]
ihc/futhark
src/Futhark/CodeGen/OpenCL/Kernels.hs
isc
7,519
0
10
1,927
646
400
246
75
11
import CCNxPacketGenerator import Generator import Writer import System.Environment import System.Random import Data.Bits import Data.Word import Data.ByteString import Data.ByteString.Char8 import Data.List.Split usage :: IO () usage = do Prelude.putStrLn "" Prelude.putStrLn "usage: runhaskell InterestBuilder.hs <name> <keyid> <hash>" Prelude.putStrLn "" Prelude.putStrLn " name = data name" Prelude.putStrLn " keyid = data key ID" Prelude.putStrLn " hash = data hash" Prelude.putStrLn "" main :: IO () main = do args <- getArgs case args of nameString:keyIdString:hashString:rest -> do let interest = createInterest (Prelude.drop 1 (splitOn "/" nameString)) keyIdString hashString in case preparePacket interest of Nothing -> Prelude.putStrLn "" Just wireFormat -> Data.ByteString.Char8.putStrLn wireFormat _ -> usage
chris-wood/ccnx-pktgen
src/InterestBuilder.hs
mit
1,004
0
20
285
244
118
126
30
3
{-# htermination showsPrec :: Int -> Ordering -> String -> String #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_showsPrec_12.hs
mit
70
0
2
12
3
2
1
1
0
{-# LANGUAGE OverloadedStrings #-} module Bot.NetHack.Messages ( consumeMessages ) where import Bot.NetHack.MonadAI import Bot.NetHack.ScreenPattern import Control.Monad import qualified Data.IntMap.Strict as IM import Data.Monoid import qualified Data.Text as T -- | Presses space until all messages have been consumed. -- -- Returns all the messages saw on the screen. consumeMessages :: MonadAI m => IM.IntMap (T.Text, m ()) -> m [T.Text] consumeMessages answermap = do skipThingsThatAreHere msgs <- pluckMessages answerQuestions answermap return $ filter (not . T.null) msgs answerQuestions :: MonadAI m => IM.IntMap (T.Text, m ()) -> m () answerQuestions answermap = do (_, _, cy) <- currentScreen more <- matchf (limitRows [0,1,2] "--More--") -- Some kind of question on the screen? when (cy == 0 && more == False) $ do line <- getScreenLine 0 let looper [] = return () looper ((_, (text, action)):rest) = if T.isInfixOf text line then action else looper rest looper (IM.toDescList answermap) skipThingsThatAreHere :: MonadAI m => m () skipThingsThatAreHere = do topline <- getScreenLine 0 -- Skip "Things that are here:" item listing when (T.isInfixOf "Things that are here:" topline || T.isInfixOf "Things that you feel here:" topline || T.isInfixOf "Something is written" topline || T.isInfixOf "Something is engraved" topline || T.isInfixOf "There's some graffiti on the floor here." topline || T.isInfixOf "You read: " topline) $ do has_more <- matchf "--More--" when has_more $ do send " " skipThingsThatAreHere pluckMessages :: MonadAI m => m [T.Text] pluckMessages = do topline <- getScreenLine 0 -- Break the top line from places where double spaces occur. -- Not 100% watertight but it should keep most relevant messages properly -- separated. let msgs = fmap T.strip $ filter (not . T.null) $ T.splitOn " " topline -- Is there a "--More--" on the screen? Press space is yes has_more <- matchf "--More--" if has_more then send " " >> (msgs <>) <$> pluckMessages else return msgs
Noeda/adeonbot
bot/src/Bot/NetHack/Messages.hs
mit
2,220
0
17
537
602
302
300
47
3
-- | Flexible, type-safe open unions. module Data.OpenUnion ( Union , (@>) , liftUnion , reUnion , flattenUnion , restrict , typesExhausted ) where import Data.OpenUnion.Internal
bfops/open-union
Data/OpenUnion.hs
mit
212
0
4
59
38
26
12
9
0
{-# LANGUAGE OverloadedStrings #-} module AyaScript.GenES where import AyaScript.Types import Data.List import Data.Aeson import Data.ByteString.Lazy.Char8 (unpack) s :: String -> String s = id n :: Num a => a -> a n = id me :: Maybe Expr -> Maybe Expr me = id le :: [Expr] -> [Expr] le = id genES :: Program -> String genES stmts = unpack $ encode $ object [ "type" .= s "Program" , "body" .= stmts , "sourceType" .= s "script"] instance ToJSON Expr where toJSON (Natural x) = object [ "type" .= s "Literal" , "value" .= n x , "raw" .= show x] toJSON (Str x) = object [ "type" .= s "Literal" , "value" .= x , "raw" .= s ("'" ++ x ++ "'")] toJSON (UnaryOp op e) = object [ "type" .= s "UnaryExpression" , "operator" .= op , "argument" .= e , "prefix" .= True] toJSON (BinOp "." e1 e2@(Var _)) = object [ "type" .= s "MemberExpression" , "computed" .= False , "object" .= e1 , "property" .= e2] toJSON (BinOp "." e1 e2) = object [ "type" .= s "MemberExpression" , "computed" .= True , "object" .= e1 , "property" .= e2] toJSON (BinOp "**" e1 e2) = toJSON $ BinOp "" (BinOp "." (Var "Math") (Var "pow")) (Tuple [e1, e2]) toJSON (BinOp "|>" x f) = toJSON $ BinOp "" f x toJSON (BinOp "<$>" f xs) = toJSON $ BinOp "" (BinOp "." xs (Var "map")) f toJSON (BinOp "==" e1 e2) = toJSON $ BinOp "===" e1 e2 toJSON (BinOp "/=" e1 e2) = toJSON $ BinOp "!==" e1 e2 toJSON (BinOp "" e1 (Tuple es)) = object [ "type" .= s "CallExpression" , "callee" .= e1 , "arguments" .= es] toJSON (BinOp "" e1 e2) = object [ "type" .= s "CallExpression" , "callee" .= e1 , "arguments" .= [e2]] toJSON (BinOp op e1 e2) = object [ "type" .= s "BinaryExpression" , "operator" .= op , "left" .= e1 , "right" .= e2] toJSON (Var var) = object [ "type" .= s "Identifier" , "name" .= var] toJSON (Fun param e) = object [ "type" .= s "ArrowFunctionExpression" , "id" .= me Nothing , "params" .= [Var param] , "defaults" .= le [] , "body" .= e , "generator" .= False , "expression" .= True] toJSON (If e1 e2 e3) = object [ "type" .= s "ConditionalExpression" , "test" .= e1 , "consequent" .= e2 , "alternate" .= e3] toJSON (Tuple es) = toJSON $ List es toJSON (List es) = object [ "type" .= s "ArrayExpression" , "elements" .= es] instance ToJSON Stmt where toJSON (Expr e) = object [ "type" .= s "ExpressionStatement" , "expression" .= e] toJSON (Decl e1 e2) = object [ "type" .= s "VariableDeclaration" , "declarations" .= [object [ "type" .= s "VariableDeclarator" , "id" .= e1 , "init" .= e2]] , "kind" .= s "var"] toJSON (Assign e1 e2) = object [ "type" .= s "ExpressionStatement" , "expression" .= object [ "type" .= s "AssignmentExpression" , "operator" .= s "=" , "left" .= e1 , "right" .= e2]]
AyaMorisawa/aya-script
src/AyaScript/GenES.hs
mit
4,275
0
13
2,127
1,200
617
583
81
1
module HW3 where import Data.List (findIndices) advancedFilter :: ((a, a, a) -> Bool) -> [a] -> [Int] advancedFilter _ [] = [] advancedFilter _ [x] = [] advancedFilter _ [x, y] = [] advancedFilter pred (x:y:xs) = map (+ 1) $ findIndices pred $ zip3 (x:y:xs) (y:xs) xs prodIndices :: [Integer] -> [Int] prodIndices list = map (+ negate 1) $ advancedFilter (\(p, c, n) -> c == p * n) ([1] ++ list ++ [1]) neighbours :: [Integer] -> [Int] neighbours = advancedFilter (\(p, c, n) -> c == n - p) maximums :: [Integer] -> [Integer] maximums [] = [] maximums [x] = [] maximums [x, y] = [] maximums (x:y:xs) = map (\(f, s, t) -> s) $ filter (\(p, c, n) -> p < c && c > n) $ zip3 (x:y:xs) (y:xs) xs preHigher :: Ord a => [a] -> [Int] preHigher [] = [] preHigher (x:xs) = map (+ 1) $ findIndices (uncurry (>)) $ zip (x:xs) xs life = 228 memes = 9001 wealth = 322 happiness = 1488 theAnswerToLifeTheUniverseAndEverything = 42 main = [ prodIndices [1,1,2,2,1,0,0] == [0,2,3,5,6] , prodIndices [1] == [0] , prodIndices [2] == [] , prodIndices [] == [] , neighbours [1,1,2,2,1,0,0] == [1] , neighbours [1,2,3,4,5,6,7] == [1] , neighbours [] == [] , neighbours [1] == [] , neighbours [1,2] == [] , neighbours [1,2,3] == [1] , maximums [] == [] , maximums [1,2,1] == [2] , maximums [228,322,1488] == [] , maximums [1] == [] -- what should i choose, haskell? , maximums [life, memes, wealth, happiness, theAnswerToLifeTheUniverseAndEverything] == [memes, happiness] -- thanks, haskell) , preHigher [1,2,3] == [] , preHigher [3,2,1] == [1,2] , preHigher ['a','c','b'] == [2] ]
GrandArchTemplar/FunctionalProgramming
src/HW3.hs
mit
1,653
0
12
380
970
549
421
43
1
{-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} module Main (main) where import Test.HUnit hiding (Test) import Test.Framework (Test) import Test.Framework (defaultMain, testGroup) import Test.Framework.Providers.HUnit import MicroKanren import MicroKanren.Plain (LVar(LVar, LVal)) unifyWith ∷ Int → Int → Logic (LVar Int) unifyWith a b = do q ← fresh q === LVal a LVal b === q test_unify = [([(LVar 0, LVal 5)], 1)] @=? (run' $ unifyWith 5 5) test_notUnify = [] @=? (run' $ unifyWith 5 4) test_reify = [LVal 5, LVal 6] @=? (run $ do q ← fresh conde [q === LVal 5 ,q === LVal (6 ∷ Int)]) test_reify2vars = [LVal 5] @=? (run $ do q ← fresh t ← fresh q === LVal (5 ∷ Int) q === t return t) main ∷ IO () main = defaultMain tests tests ∷ [Test] tests = [ testGroup "Unification" [ testCase "not unifies" test_notUnify , testCase "unifies" test_unify ] , testGroup "Reification" [ testCase "reify" test_reify , testCase "reify two vars" test_reify2vars ] ]
Oregu/featherweight
tests/Main.hs
mit
1,364
0
14
512
409
217
192
-1
-1
{- arch-tag: HVIO main file Copyright (c) 2004-2011 John Goerzen <jgoerzen@complete.org> All rights reserved. For license and copyright information, see the file LICENSE -} {- | Module : System.IO.HVIO Copyright : Copyright (C) 2004-2011 John Goerzen License : BSD3 Maintainer : John Goerzen <jgoerzen@complete.org> Stability : provisional Portability: portable Haskell Virtual I\/O -- a system to increase the flexibility of input and output in Haskell Copyright (c) 2004-2005 John Goerzen, jgoerzen\@complete.org HVIO provides the following general features: * The ability to use a single set of functions on various different types of objects, including standard Handles, in-memory buffers, compressed files, network data streams, etc. * The ability to transparently add filters to the I\/O process. These filters could include things such as character set conversions, compression or decompression of a data stream, and more. * The ability to define new objects that have the properties of I\/O objects and can be used interchangably with them. * Specification compatibility with, and complete support for, existing I\/O on Handles. * Provide easier unit testing capabilities for I\/O actions HVIO defines several basic type classes that you can use. You will mostly be interested in 'HVIO'. It's trivial to adapt old code to work with HVIO. For instance, consider this example of old and new code: >printMsg :: Handle -> String -> IO () >printMsg h msg = hPutStr h ("msg: " ++ msg) And now, the new way: >printMsg :: HVIO h => h -> String -> IO () >printMsg h msg = vPutStr h ("msg: " ++ msg) There are several points to note about this conversion: * The new method can still accept a Handle in exactly the same way as the old method. Changing your functions to use HVIO will require no changes from functions that call them with Handles. * Most \"h\" functions have equivolent \"v\" functions that operate on HVIO classes instead of the more specific Handle. The \"v\" functions behave identically to the \"h\" functions whenever possible. * There is no equivolent of \"openFile\" in any HVIO class. You must create your Handle (or other HVIO object) using normal means. This is because the creation is so different that it cannot be standardized. In addition to Handle, there are several pre-defined classes for your use. 'StreamReader' is a particularly interesting one. At creation time, you pass it a String. Its contents are read lazily whenever a read call is made. It can be used, therefore, to implement filters (simply initialize it with the result from, say, a map over hGetContents from another HVIO object), codecs, and simple I\/O testing. Because it is lazy, it need not hold the entire string in memory. You can create a 'StreamReader' with a call to 'newStreamReader'. 'MemoryBuffer' is a similar class, but with a different purpose. It provides a full interface like Handle (it implements 'HVIOReader', 'HVIOWriter', and 'HVIOSeeker'). However, it maintains an in-memory buffer with the contents of the file, rather than an actual on-disk file. You can access the entire contents of this buffer at any time. This can be quite useful for testing I\/O code, or for cases where existing APIs use I\/O, but you prefer a String representation. You can create a 'MemoryBuffer' with a call to 'newMemoryBuffer'. Finally, there are pipes. These pipes are analogous to the Unix pipes that are available from System.Posix, but don't require Unix and work only in Haskell. When you create a pipe, you actually get two HVIO objects: a 'PipeReader' and a 'PipeWriter'. You must use the 'PipeWriter' in one thread and the 'PipeReader' in another thread. Data that's written to the 'PipeWriter' will then be available for reading with the 'PipeReader'. The pipes are implemented completely with existing Haskell threading primitives, and require no special operating system support. Unlike Unix pipes, these pipes cannot be used across a fork(). Also unlike Unix pipes, these pipes are portable and interact well with Haskell threads. A new pipe can be created with a call to 'newHVIOPipe'. Together with "System.IO.HVFS", this module is part of a complete virtual filesystem solution. -} module System.IO.HVIO(-- * Implementation Classes HVIO(..), -- * Standard HVIO Implementations -- ** Handle -- | Handle is a member of 'HVIO'. -- ** Stream Reader StreamReader, newStreamReader, -- ** Memory Buffer MemoryBuffer, newMemoryBuffer, mbDefaultCloseFunc, getMemoryBuffer, -- ** Haskell Pipe PipeReader, PipeWriter, newHVIOPipe ) where import System.IO import System.IO.Error import qualified Control.Exception (catch, IOException) import Control.Concurrent.MVar import Data.IORef import Foreign.Ptr import Foreign.C import Foreign.Storable {- | This is the generic I\/O support class. All objects that are to be used in the HVIO system must provide an instance of 'HVIO'. Functions in this class provide an interface with the same specification as the similar functions in System.IO. Please refer to that documentation for a more complete specification than is provided here. Instances of 'HVIO' must provide 'vClose', 'vIsEOF', and either 'vIsOpen' or 'vIsClosed'. Implementators of readable objects must provide at least 'vGetChar' and 'vIsReadable'. An implementation of 'vGetContents' is also highly suggested, since the default cannot implement proper partial closing semantics. Implementators of writable objects must provide at least 'vPutChar' and 'vIsWritable'. Implementators of seekable objects must provide at least 'vIsSeekable', 'vTell', and 'vSeek'. -} class (Show a) => HVIO a where -- | Close a file vClose :: a -> IO () -- | Test if a file is open vIsOpen :: a -> IO Bool -- | Test if a file is closed vIsClosed :: a -> IO Bool -- | Raise an error if the file is not open. -- This is a new HVIO function and is implemented in terms of -- 'vIsOpen'. vTestOpen :: a -> IO () -- | Whether or not we're at EOF. This may raise on exception -- on some items, most notably write-only Handles such as stdout. -- In general, this is most reliable on items opened for reading. -- vIsEOF implementations must implicitly call vTestOpen. vIsEOF :: a -> IO Bool -- | Detailed show output. vShow :: a -> IO String -- | Make an IOError. vMkIOError :: a -> IOErrorType -> String -> Maybe FilePath -> IOError -- | Throw an IOError. vThrow :: a -> IOErrorType -> IO b -- | Get the filename\/object\/whatever that this corresponds to. -- May be Nothing. vGetFP :: a -> IO (Maybe FilePath) -- | Throw an isEOFError if we're at EOF; returns nothing otherwise. -- If an implementation overrides the default, make sure that it -- calls vTestOpen at some point. The default implementation is -- a wrapper around a call to 'vIsEOF'. vTestEOF :: a -> IO () -- | Read one character vGetChar :: a -> IO Char -- | Read one line vGetLine :: a -> IO String {- | Get the remaining contents. Please note that as a user of this function, the same partial-closing semantics as are used in the standard 'hGetContents' are /encouraged/ from implementators, but are not /required/. That means that, for instance, a 'vGetChar' after a 'vGetContents' may return some undefined result instead of the error you would normally get. You should use caution to make sure your code doesn't fall into that trap, or make sure to test your code with Handle or one of the default instances defined in this module. Also, some implementations may essentially provide a complete close after a call to 'vGetContents'. The bottom line: after a call to 'vGetContents', you should do nothing else with the object save closing it with 'vClose'. For implementators, you are highly encouraged to provide a correct implementation. -} vGetContents :: a -> IO String -- | Indicate whether at least one item is ready for reading. -- This will always be True for a great many implementations. vReady :: a -> IO Bool -- | Indicate whether a particular item is available for reading. vIsReadable :: a -> IO Bool -- | Write one character vPutChar :: a -> Char -> IO () -- | Write a string vPutStr :: a -> String -> IO () -- | Write a string with newline character after it vPutStrLn :: a -> String -> IO () -- | Write a string representation of the argument, plus a newline. vPrint :: Show b => a -> b -> IO () -- | Flush any output buffers. -- Note: implementations should assure that a vFlush is automatically -- performed -- on file close, if necessary to ensure all data sent is written. vFlush :: a -> IO () -- | Indicate whether or not this particular object supports writing. vIsWritable :: a -> IO Bool -- | Seek to a specific location. vSeek :: a -> SeekMode -> Integer -> IO () -- | Get the current position. vTell :: a -> IO Integer -- | Convenience function to reset the file pointer to the beginning -- of the file. A call to @vRewind h@ is the -- same as @'vSeek' h AbsoluteSeek 0@. vRewind :: a -> IO () -- | Indicate whether this instance supports seeking. vIsSeekable :: a -> IO Bool -- | Set buffering; the default action is a no-op. vSetBuffering :: a -> BufferMode -> IO () -- | Get buffering; the default action always returns NoBuffering. vGetBuffering :: a -> IO BufferMode -- | Binary output: write the specified number of octets from the specified -- buffer location. vPutBuf :: a -> Ptr b -> Int -> IO () -- | Binary input: read the specified number of octets from the -- specified buffer location, continuing to read -- until it either consumes that much data or EOF is encountered. -- Returns the number of octets actually read. EOF errors are never -- raised; fewer bytes than requested are returned on EOF. vGetBuf :: a -> Ptr b -> Int -> IO Int vSetBuffering _ _ = return () vGetBuffering _ = return NoBuffering vShow x = return (show x) vMkIOError _ et desc mfp = mkIOError et desc Nothing mfp vGetFP _ = return Nothing vThrow h et = do fp <- vGetFP h ioError (vMkIOError h et "" fp) vTestEOF h = do e <- vIsEOF h if e then vThrow h eofErrorType else return () vIsOpen h = vIsClosed h >>= return . not vIsClosed h = vIsOpen h >>= return . not vTestOpen h = do e <- vIsClosed h if e then vThrow h illegalOperationErrorType else return () vIsReadable _ = return False vGetLine h = let loop accum = let func = do c <- vGetChar h case c of '\n' -> return accum x -> accum `seq` loop (accum ++ [x]) handler e = if isEOFError e then return accum else ioError e in Control.Exception.catch func handler in do firstchar <- vGetChar h case firstchar of '\n' -> return [] x -> loop [x] vGetContents h = let loop = let func = do c <- vGetChar h next <- loop c `seq` return (c : next) handler e = if isEOFError e then return [] else ioError e in Control.Exception.catch func handler in do loop vReady h = do vTestEOF h return True vIsWritable _ = return False vPutStr _ [] = return () vPutStr h (x:xs) = do vPutChar h x vPutStr h xs vPutStrLn h s = vPutStr h (s ++ "\n") vPrint h s = vPutStrLn h (show s) vFlush = vTestOpen vIsSeekable _ = return False vRewind h = vSeek h AbsoluteSeek 0 vPutChar h _ = vThrow h illegalOperationErrorType vSeek h _ _ = vThrow h illegalOperationErrorType vTell h = vThrow h illegalOperationErrorType vGetChar h = vThrow h illegalOperationErrorType vPutBuf h buf len = do str <- peekCStringLen (castPtr buf, len) vPutStr h str vGetBuf h b l = worker b l 0 where worker _ 0 accum = return accum worker buf len accum = do iseof <- vIsEOF h if iseof then return accum else do c <- vGetChar h let cc = castCharToCChar c poke (castPtr buf) cc let newptr = plusPtr buf 1 worker newptr (len - 1) (accum + 1) ---------------------------------------------------------------------- -- Handle instances ---------------------------------------------------------------------- instance HVIO Handle where vClose = hClose vIsEOF = hIsEOF #ifdef __GLASGOW_HASKELL__ vShow = hShow #endif vMkIOError h et desc mfp = mkIOError et desc (Just h) mfp vGetChar = hGetChar vGetLine = hGetLine vGetContents = hGetContents vReady = hReady vIsReadable = hIsReadable vPutChar = hPutChar vPutStr = hPutStr vPutStrLn = hPutStrLn vPrint = hPrint vFlush = hFlush vIsWritable = hIsWritable vSeek = hSeek vTell = hTell vIsSeekable = hIsSeekable vSetBuffering = hSetBuffering vGetBuffering = hGetBuffering vGetBuf = hGetBuf vPutBuf = hPutBuf vIsOpen = hIsOpen vIsClosed = hIsClosed ---------------------------------------------------------------------- -- VIO Support ---------------------------------------------------------------------- type VIOCloseSupport a = IORef (Bool, a) vioc_isopen :: VIOCloseSupport a -> IO Bool vioc_isopen x = readIORef x >>= return . fst vioc_get :: VIOCloseSupport a -> IO a vioc_get x = readIORef x >>= return . snd vioc_close :: VIOCloseSupport a -> IO () vioc_close x = modifyIORef x (\ (_, dat) -> (False, dat)) vioc_set :: VIOCloseSupport a -> a -> IO () vioc_set x newdat = modifyIORef x (\ (stat, _) -> (stat, newdat)) ---------------------------------------------------------------------- -- Stream Readers ---------------------------------------------------------------------- {- | Simulate I\/O based on a string buffer. When a 'StreamReader' is created, it is initialized based on the contents of a 'String'. Its contents are read lazily whenever a request is made to read something from the 'StreamReader'. It can be used, therefore, to implement filters (simply initialize it with the result from, say, a map over hGetContents from another HVIO object), codecs, and simple I\/O testing. Because it is lazy, it need not hold the entire string in memory. You can create a 'StreamReader' with a call to 'newStreamReader'. -} newtype StreamReader = StreamReader (VIOCloseSupport String) {- | Create a new 'StreamReader' object. -} newStreamReader :: String -- ^ Initial contents of the 'StreamReader' -> IO StreamReader newStreamReader s = do ref <- newIORef (True, s) return (StreamReader ref) srv :: StreamReader -> VIOCloseSupport String srv (StreamReader x) = x instance Show StreamReader where show _ = "<StreamReader>" instance HVIO StreamReader where vClose = vioc_close . srv vIsEOF h = do vTestOpen h d <- vioc_get (srv h) return $ case d of [] -> True _ -> False vIsOpen = vioc_isopen . srv vGetChar h = do vTestEOF h c <- vioc_get (srv h) let retval = head c vioc_set (srv h) (tail c) return retval vGetContents h = do vTestEOF h c <- vioc_get (srv h) vClose h return c vIsReadable _ = return True ---------------------------------------------------------------------- -- Buffers ---------------------------------------------------------------------- {- | A 'MemoryBuffer' simulates true I\/O, but uses an in-memory buffer instead of on-disk storage. It provides a full interface like Handle (it implements 'HVIOReader', 'HVIOWriter', and 'HVIOSeeker'). However, it maintains an in-memory buffer with the contents of the file, rather than an actual on-disk file. You can access the entire contents of this buffer at any time. This can be quite useful for testing I\/O code, or for cases where existing APIs use I\/O, but you prefer a String representation. You can create a 'MemoryBuffer' with a call to 'newMemoryBuffer'. The present 'MemoryBuffer' implementation is rather inefficient, particularly when reading towards the end of large files. It's best used for smallish data storage. This problem will be fixed eventually. -} data MemoryBuffer = MemoryBuffer (String -> IO ()) (VIOCloseSupport (Int, String)) {- | Create a new 'MemoryBuffer' instance. The buffer is initialized to the value passed, and the pointer is placed at the beginning of the file. You can put things in it by using the normal 'vPutStr' calls, and reset to the beginning by using the normal 'vRewind' call. The function is called when 'vClose' is called, and is passed the contents of the buffer at close time. You can use 'mbDefaultCloseFunc' if you don't want to do anything. To create an empty buffer, pass the initial value @\"\"@. -} newMemoryBuffer :: String -- ^ Initial Contents -> (String -> IO ()) -- ^ close func -> IO MemoryBuffer newMemoryBuffer initval closefunc = do ref <- newIORef (True, (0, initval)) return (MemoryBuffer closefunc ref) {- | Default (no-op) memory buf close function. -} mbDefaultCloseFunc :: String -> IO () mbDefaultCloseFunc _ = return () vrv :: MemoryBuffer -> VIOCloseSupport (Int, String) vrv (MemoryBuffer _ x) = x {- | Grab the entire contents of the buffer as a string. Unlike 'vGetContents', this has no effect on the open status of the item, the EOF status, or the current position of the file pointer. -} getMemoryBuffer :: MemoryBuffer -> IO String getMemoryBuffer h = do c <- vioc_get (vrv h) return (snd c) instance Show MemoryBuffer where show _ = "<MemoryBuffer>" instance HVIO MemoryBuffer where vClose x = do wasopen <- vIsOpen x vioc_close (vrv x) if wasopen then do c <- getMemoryBuffer x case x of MemoryBuffer cf _ -> cf c else return () vIsEOF h = do vTestOpen h c <- vioc_get (vrv h) return ((length (snd c)) == (fst c)) vIsOpen = vioc_isopen . vrv vGetChar h = do vTestEOF h c <- vioc_get (vrv h) let retval = (snd c) !! (fst c) vioc_set (vrv h) (succ (fst c), snd c) return retval vGetContents h = do vTestEOF h v <- vioc_get (vrv h) let retval = drop (fst v) (snd v) vioc_set (vrv h) (-1, "") vClose h return retval vIsReadable _ = return True vPutStr h s = do (pos, buf) <- vioc_get (vrv h) let (pre, post) = splitAt pos buf let newbuf = pre ++ s ++ (drop (length s) post) vioc_set (vrv h) (pos + (length s), newbuf) vPutChar h c = vPutStr h [c] vIsWritable _ = return True vTell h = do v <- vioc_get (vrv h) return . fromIntegral $ (fst v) vSeek h seekmode seekposp = do (pos, buf) <- vioc_get (vrv h) let seekpos = fromInteger seekposp let newpos = case seekmode of AbsoluteSeek -> seekpos RelativeSeek -> pos + seekpos SeekFromEnd -> (length buf) + seekpos let buf2 = buf ++ if newpos > (length buf) then replicate (newpos - (length buf)) '\0' else [] vioc_set (vrv h) (newpos, buf2) vIsSeekable _ = return True ---------------------------------------------------------------------- -- Pipes ---------------------------------------------------------------------- {- | Create a Haskell pipe. These pipes are analogous to the Unix pipes that are available from System.Posix, but don't require Unix and work only in Haskell. When you create a pipe, you actually get two HVIO objects: a 'PipeReader' and a 'PipeWriter'. You must use the 'PipeWriter' in one thread and the 'PipeReader' in another thread. Data that's written to the 'PipeWriter' will then be available for reading with the 'PipeReader'. The pipes are implemented completely with existing Haskell threading primitives, and require no special operating system support. Unlike Unix pipes, these pipes cannot be used across a fork(). Also unlike Unix pipes, these pipes are portable and interact well with Haskell threads. -} newHVIOPipe :: IO (PipeReader, PipeWriter) newHVIOPipe = do mv <- newEmptyMVar readerref <- newIORef (True, mv) let reader = PipeReader readerref writerref <- newIORef (True, reader) return (reader, PipeWriter writerref) data PipeBit = PipeBit Char | PipeEOF deriving (Eq, Show) {- | The reading side of a Haskell pipe. Please see 'newHVIOPipe' for more details. -} newtype PipeReader = PipeReader (VIOCloseSupport (MVar PipeBit)) {- | The writing side of a Haskell pipe. Please see 'newHVIOPipe' for more details. -} newtype PipeWriter = PipeWriter (VIOCloseSupport PipeReader) ------------------------------ -- Pipe Reader ------------------------------ prv :: PipeReader -> VIOCloseSupport (MVar PipeBit) prv (PipeReader x) = x instance Show PipeReader where show _ = "<PipeReader>" pr_getc :: PipeReader -> IO PipeBit pr_getc h = do mv <- vioc_get (prv h) takeMVar mv instance HVIO PipeReader where vClose = vioc_close . prv vIsOpen = vioc_isopen . prv vIsEOF h = do vTestOpen h mv <- vioc_get (prv h) dat <- readMVar mv return (dat == PipeEOF) vGetChar h = do vTestEOF h c <- pr_getc h case c of PipeBit x -> return x -- vTestEOF should eliminate this case _ -> fail "Internal error in HVIOReader vGetChar" vGetContents h = let loop = do c <- pr_getc h case c of PipeEOF -> return [] PipeBit x -> do next <- loop return (x : next) in do vTestEOF h loop vIsReadable _ = return True ------------------------------ -- Pipe Writer ------------------------------ pwv :: PipeWriter -> VIOCloseSupport PipeReader pwv (PipeWriter x) = x pwmv :: PipeWriter -> IO (MVar PipeBit) pwmv (PipeWriter x) = do mv1 <- vioc_get x vioc_get (prv mv1) instance Show PipeWriter where show _ = "<PipeWriter>" instance HVIO PipeWriter where vClose h = do o <- vIsOpen h if o then do mv <- pwmv h putMVar mv PipeEOF vioc_close (pwv h) else return () vIsOpen = vioc_isopen . pwv vIsEOF h = do vTestOpen h return False -- FIXME: race condition below (could be closed after testing) vPutChar h c = do vTestOpen h child <- vioc_get (pwv h) copen <- vIsOpen child if copen then do mv <- pwmv h putMVar mv (PipeBit c) else fail "PipeWriter: Couldn't write to pipe because child end is closed" vIsWritable _ = return True
haskellbr/missingh
missingh-all/src/System/IO/HVIO.hs
mit
24,901
0
24
7,478
3,895
1,935
1,960
298
1
{-# LANGUAGE OverloadedStrings #-} module TestImport ( module Yesod.Test , module Model , module Foundation , module Database.Persist , runDB , getMessageRender , Specs ) where import Yesod.Test import Database.Persist hiding (get) import Database.Persist.Sql (runSqlPool, SqlPersist, Connection) import Control.Monad.Trans.Resource (ResourceT, runResourceT) import Control.Monad.Logger (NoLoggingT, runNoLoggingT) import Control.Monad.IO.Class (liftIO) import Text.Shakespeare.I18N (RenderMessage (..)) import Data.Text (Text, unpack) import Foundation import Model type Specs = YesodSpec App getMessageRender :: YesodExample App (AppMessage -> String) getMessageRender = do y <- getTestYesod return $ unpack . (renderMessage y ["en"]) runDB :: SqlPersist (NoLoggingT (ResourceT IO)) a -> YesodExample App a runDB query = do pool <- fmap connPool getTestYesod liftIO $ runResourceT $ runNoLoggingT $ runSqlPool query pool
lulf/wishsys
tests/TestImport.hs
mit
1,005
0
10
196
275
159
116
28
1
{-# LANGUAGE ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Database ( module Generated , js_changeVersion , changeVersion' , changeVersion , js_transaction , transaction' , transaction , js_readTransaction , readTransaction' , readTransaction ) where import Data.Maybe (fromJust, maybe) import Control.Monad.IO.Class (MonadIO(..)) import Control.Exception (Exception, bracket) import GHCJS.Types (JSRef, JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (OnBlocked(..)) import GHCJS.Marshal (fromJSRef) import GHCJS.Marshal.Pure (pToJSRef) import GHCJS.Foreign.Callback (releaseCallback) import GHCJS.DOM.Types import GHCJS.DOM.JSFFI.SQLError (throwSQLException) import GHCJS.DOM.JSFFI.Generated.SQLTransactionCallback (newSQLTransactionCallbackSync) import GHCJS.DOM.JSFFI.Generated.Database as Generated hiding (js_changeVersion, changeVersion, js_transaction, transaction, js_readTransaction, readTransaction) withSQLTransactionCallback :: (SQLTransaction -> IO ()) -> (SQLTransactionCallback -> IO a) -> IO a withSQLTransactionCallback f = bracket (newSQLTransactionCallbackSync (f . fromJust)) releaseCallback foreign import javascript interruptible "$1[\"changeVersion\"]($2, $3, $4, $c, function() { $c(null); });" js_changeVersion :: JSRef Database -> JSString -> JSString -> JSRef SQLTransactionCallback -> IO (JSRef SQLError) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Database.changeVersion Mozilla Database.changeVersion documentation> changeVersion' :: (MonadIO m, ToJSString oldVersion, ToJSString newVersion) => Database -> oldVersion -> newVersion -> Maybe (SQLTransaction -> IO ()) -> m (Maybe SQLError) changeVersion' self oldVersion newVersion Nothing = liftIO $ js_changeVersion (unDatabase self) (toJSString oldVersion) (toJSString newVersion) jsNull >>= fromJSRef changeVersion' self oldVersion newVersion (Just callback) = liftIO $ withSQLTransactionCallback callback (js_changeVersion (unDatabase self) (toJSString oldVersion) (toJSString newVersion) . pToJSRef) >>= fromJSRef changeVersion :: (MonadIO m, ToJSString oldVersion, ToJSString newVersion) => Database -> oldVersion -> newVersion -> Maybe (SQLTransaction -> IO ()) -> m () changeVersion self oldVersion newVersion callback = changeVersion' self oldVersion newVersion callback >>= maybe (return ()) throwSQLException foreign import javascript interruptible "$1[\"transaction\"]($2, $c, function() { $c(null); });" js_transaction :: JSRef Database -> JSRef SQLTransactionCallback -> IO (JSRef SQLError) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Database.transaction Mozilla Database.transaction documentation> transaction' :: (MonadIO m) => Database -> (SQLTransaction -> IO ()) -> m (Maybe SQLError) transaction' self callback = liftIO $ withSQLTransactionCallback callback (js_transaction (unDatabase self) . pToJSRef) >>= fromJSRef transaction :: (MonadIO m) => Database -> (SQLTransaction -> IO ()) -> m () transaction self callback = transaction' self callback >>= maybe (return ()) throwSQLException foreign import javascript interruptible "$1[\"readTransaction\"]($2, $c, function() { $c(null); });" js_readTransaction :: JSRef Database -> JSRef SQLTransactionCallback -> IO (JSRef SQLError) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Database.readTransaction Mozilla Database.readTransaction documentation> readTransaction' :: (MonadIO m) => Database -> (SQLTransaction -> IO ()) -> m (Maybe SQLError) readTransaction' self callback = liftIO $ withSQLTransactionCallback callback (js_readTransaction (unDatabase self) . pToJSRef) >>= fromJSRef readTransaction :: (MonadIO m) => Database -> (SQLTransaction -> IO ()) -> m () readTransaction self callback = readTransaction' self callback >>= maybe (return ()) throwSQLException
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Database.hs
mit
3,930
28
14
537
986
527
459
-1
-1
module Irg.Lab4.Fractal.Initialize (initialize) where --import qualified Graphics.GL.Compatibility33 as GL import qualified Graphics.UI.GLUT as GLUT import Graphics.UI.GLUT (($=)) --import Data.IORef import Irg.Lab4.Fractal.Utility initialize :: GameState -> ReshapeCallback -> DisplayCallback -> KeyboardCallback -> MouseCallback -> IO () initialize gameState reshapeCallback displayCallback keyboardCallback mouseCallback = do _ <- GLUT.initialize "irg" [] GLUT.initialWindowPosition $= GLUT.Position 100 100 GLUT.initialWindowSize $= GLUT.Size 800 600 GLUT.initialDisplayMode $= [GLUT.RGBAMode, GLUT.DoubleBuffered] GLUT.actionOnWindowClose $= GLUT.MainLoopReturns _ <- GLUT.createWindow "irg" GLUT.reshapeCallback $= Just (reshapeCallback gameState) GLUT.displayCallback $= (displayCallback gameState 0.0) GLUT.keyboardCallback $= Just (keyboardCallback gameState) GLUT.mouseCallback $= Just (mouseCallback gameState) print "Start end" GLUT.get GLUT.initState >>= print GLUT.get GLUT.glVersion >>= print GLUT.mainLoop
DominikDitoIvosevic/Uni
IRG/src/Irg/Lab4/Fractal/Initialize.hs
mit
1,056
0
11
135
290
144
146
20
1
{-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} module TX ( Persistable(..) -- * Managing the database , Database , openDatabase , closeDatabase , withUserData -- * The TX monad , TX , persistently , record , getData , liftSTM , throwTX , unsafeIOToTX -- * Utility functions , (<?>) ) where import Control.Applicative import Control.Concurrent import Control.Concurrent.STM import Control.Exception import Control.Monad import Control.Monad.Trans.Class import Control.Monad.Trans.Reader import qualified Data.ByteString as B import Data.Maybe import Data.SafeCopy import Data.Serialize import GHC.Conc import System.IO ------------------------------------------------------------------------------ -- | The type family at the heart of TX. -- -- You make any data type you want to use with the TX monad an instance of -- 'Persistable' and define 'Update' constructors for each of the methods -- acting on this type that you want to be able to record during a transaction. -- Then you implement 'replay' in such a way that for each of the Update -- constructors, the appropiate method is called. -- -- Example: -- -- > data MyDB = MyDB { posts :: TVar [String] } -- > -- > instance Persistable MyDB where -- > data Update MyDB = CreatePost String -- > | ModifyPost Int String -- > -- > replay (CreatePost p) = void $ createPost p -- > replay (ModifyPost n p) = modifyPost n p -- -- where @createPost@ and @modifyPost@ are functions in the TX monad: -- -- > createPost :: String -> TX MyDB Int -- > createPost p = do -- > record (CreatePost p) -- > (MyDB posts) <- getData -- > liftSTM $ do -- > ps <- readTVar posts -- > writeTVar posts (ps ++ [p]) -- > return $ length ps -- > -- > modifyPost :: Int -> String -> TX MyDB () -- > modifyPost n p = do -- > record (ModifyPost n p) -- > (MyDB posts) <- getData -- > liftSTM $ do -- > ps <- readTVar posts -- > let (xs,ys) = splitAt n ps -- > ps' = xs ++ p : (tail ys) -- > writeTVar posts ps' -- -- Note that @Update@ also needs to be an instance of 'SafeCopy'. Currently, -- it's not possible to derive SafeCopy instances for associated types -- automatically, so you have to do it by hand: -- -- > instance SafeCopy (Update MyDB) where -- > putCopy (CreatePost p) = contain $ putWord8 0 >> safePut p -- > putCopy (ModifyPost n p) = contain $ putWord8 1 >> safePut n >> safePut p -- > getCopy = contain $ do -- > tag <- getWord8 -- > case tag of -- > 0 -> CreatePost <$> safeGet -- > 1 -> ModifyPost <$> safeGet <*> safeGet -- > _ -> fail $ "unknown tag: " ++ show tag class SafeCopy (Update d) => Persistable d where data Update d replay :: Update d -> TX d () -- TODO: provide automatic derivation using TH ------------------------------------------------------------------------------ -- | An opaque type wrapping any kind of user data for use in the 'TX' monad. data Database d = Database { userData :: d , logHandle :: Handle , logQueue :: TQueue (Update d) , _record :: TQueue (Update d) -> (Update d) -> STM () , serializerTid :: MVar ThreadId } -- | Opens the database at the given path or creates a new one. openDatabase :: Persistable d => FilePath -- ^ Location of the log file. -> d -- ^ Base data. Any existing log is replayed on top of this. -> IO (Database d) openDatabase logPath userData = do putStr ("Opening " ++ logPath ++ " database... ") logHandle <- openBinaryFile logPath ReadWriteMode logQueue <- newTQueueIO serializerTid <- newEmptyMVar let _db = Database { _record = const $ const $ return (), .. } hIsEOF logHandle >>= flip unless (replayUpdates _db) putMVar serializerTid =<< forkIO (serializer _db) let db = _db { _record = writeTQueue } putStrLn ("DONE") return db -- TODO: throw actual error when operating on a closed database -- | Close a database. Blocks until all pending recordings been serialized. -- Using a database after it has been closed is an error. closeDatabase :: Database d -> IO () closeDatabase Database {..} = do atomically $ check =<< isEmptyTQueue logQueue killThread =<< takeMVar serializerTid hClose logHandle replayUpdates :: Persistable d => Database d -> IO () replayUpdates db = mapDecode (persistently db . replay) (B.hGetSome (logHandle db) 1024) -- | @mapDecode f nextChunk@ repeatedly calls @nextChunk@ to get a -- 'B.ByteString', (partially) decodes this string using 'safeGet' and -- and then applies @f@ to the (final) result. This continues until -- @nextChunk@ returns an empty ByteString. mapDecode :: SafeCopy a => (a -> IO ()) -> IO B.ByteString -> IO () mapDecode f nextChunk = go run =<< nextChunk where run = runGetPartial safeGet go k c = case k c of Fail err -> error ("TX.mapDecode: " ++ err) Partial k' -> go k' =<< nextChunk Done u c' -> f u >> if B.null c' then do c'' <- nextChunk if B.null c'' then return () else go run c'' else go run c' -- | Operate non-persistently on the user data contained in the database. withUserData :: Database d -> (d -> a) -> a withUserData db act = act (userData db) ------------------------------------------------------------------------------ serializer :: Persistable d => Database d -> IO () serializer Database {..} = forever $ do u <- atomically $ readTQueue logQueue let str = runPut (safePut u) B.hPut logHandle str ------------------------------------------------------------------------------ -- | A thin wrapper around STM. The main feature is the ability to 'record' -- updates of the underlying data. newtype TX d a = TX (ReaderT (Database d) STM a) deriving (Functor, Applicative, Monad) -- | Perform a series of TX actions persistently. -- -- Note that there is no guarantee that all recorded updates have been serialized -- when the functions returns. As such, durability is only partially guaranteed. -- -- Since this calls 'atomically' on the underlying STM actions, -- the same caveats apply (e.g. you can't use it inside 'unsafePerformIO'). persistently :: Database d -> TX d a -> IO a persistently db (TX action) = atomically $ runReaderT action db -- | Record an 'Update' to be serialized to disk when the transaction commits. -- If the transaction retries, the update is still only recorded once. -- If the transaction aborts, the update is not recorded at all. record :: Update d -> TX d () record u = do Database {..} <- TX ask liftSTM $ _record logQueue u {-# INLINE record #-} -- | Get the user data from the database. getData :: TX d d getData = userData <$> TX ask {-# INLINE getData #-} -- | Run STM actions inside TX. liftSTM :: STM a -> TX d a liftSTM = TX . lift {-# INLINE liftSTM #-} -- | Throw an exception in TX, which will abort the transaction. -- -- @throwTX = liftSTM . throwSTM@ throwTX :: Exception e => e -> TX d a throwTX = liftSTM . throwSTM {-# INLINE throwTX #-} -- | Unsafely performs IO in the TX monad. Highly dangerous! -- The same caveats as with 'unsafeIOToSTM' apply. -- -- @unsafeIOToTX = liftSTM . unsafeIOToSTM@ unsafeIOToTX :: IO a -> TX d a unsafeIOToTX = liftSTM . unsafeIOToSTM {-# INLINE unsafeIOToTX #-} ------------------------------------------------------------------------------ -- | @act \<?\> err = maybe (throwTX err) return =<< act@ (<?>) :: Exception e => TX d (Maybe a) -> e -> TX d a act <?> err = maybe (throwTX err) return =<< act
mcschroeder/tx
TX.hs
mit
8,171
0
16
2,151
1,295
700
595
105
5
{-# LANGUAGE RecursiveDo #-} module Spaceships.Assets ( Assets(..), Message(..), loadAssets, bgColor, messageColor ) where import Common.AniTimer import Common.Assets import Common.Counters import Common.Graphics import Common.Util import Control.Applicative import Control.Monad import Graphics.UI.SDL import Graphics.UI.SDL.Mixer import Graphics.UI.SDL.TTF import qualified Data.Map as M import Spaceships.GameState bgColor = Pixel 0x323232 messageColor = Color 0 64 255 data Assets = Assets { gfx :: M.Map Tile Sprite, font :: Font, getMessage :: Message -> Surface } data Message = MessageIntro1 | MessageIntro2 | MessageHighScores deriving Show -- Load all assets loadAssets :: IO Assets loadAssets = do gfx <- loadSprites font <- loadFont messageData <- mapM (\(m, s) -> do surface <- renderUTF8Solid font s messageColor return surface ) [ (MessageIntro1, "Press F2 to start, Esc to quit"), (MessageIntro2, "High scores:"), (MessageHighScores, "New high score! Enter your name") ] let messageMap MessageIntro1 = messageData !! 0 messageMap MessageIntro2 = messageData !! 1 messageMap MessageHighScores = messageData !! 2 return Assets { gfx = gfx, font = font, getMessage = messageMap } loadSprites :: IO (M.Map Tile Sprite) loadSprites = do sheet1 <- loadBMP$ getAssetPath "gfx/hideandseek.bmp" let sheet1Sprite = makeSprite sheet1 (26, 26) boxTile <- loadBMP$ getAssetPath "gfx/blueblock.bmp" panel <- loadBMP$ getAssetPath "gfx/spaceshipsPanel.bmp" paused <- loadBMP$ getAssetPath "gfx/Paused.bmp" gameOver <- loadBMP$ getAssetPath "gfx/gameOver.bmp" digits <- loadBMP$ getAssetPath "gfx/Digits.bmp" forM_ [sheet1, paused, gameOver, panel, digits]$ \surface -> setColorKey surface [SrcColorKey] (Pixel 0x00FF00FF) let sbox = makeSprite boxTile (26, 26) (0, 0) frameV <- makeVFrame sbox frameH <- makeHFrame sbox let sFrameV = makeSprite frameV (26, 546) (0, 0) let sFrameH = makeSprite frameH (494, 26) (0, 0) bg <- makeBackground sbox sFrameH sFrameV let spriteFor Background = makeSprite bg (572, 546) (0, 0) spriteFor FrameV = sFrameV spriteFor FrameH = sFrameH spriteFor Digits = makeSprite digits (20, 180) (0, 0) spriteFor Paused = makeSprite paused (234, 160) (0, 0) spriteFor GameOverTile = makeSprite gameOver (200, 64) (0, 0) spriteFor SidePanel = makeSprite panel (208, 546) (0, 0) spriteFor BoxTile = makeSprite boxTile (26, 26) (0, 0) spriteFor PlayerR = sheet1Sprite (0, 0) spriteFor PlayerD = sheet1Sprite (1, 0) spriteFor PlayerL = sheet1Sprite (2, 0) spriteFor PlayerU = sheet1Sprite (3, 0) spriteFor AiR = sheet1Sprite (0, 1) spriteFor AiD = sheet1Sprite (1, 1) spriteFor AiL = sheet1Sprite (2, 1) spriteFor AiU = sheet1Sprite (3, 1) spriteFor EngineR = sheet1Sprite (0, 3) spriteFor EngineD = sheet1Sprite (1, 3) spriteFor EngineL = sheet1Sprite (2, 3) spriteFor EngineU = sheet1Sprite (3, 3) spriteFor LaserR = sheet1Sprite (0, 2) spriteFor LaserD = sheet1Sprite (1, 2) spriteFor LaserL = sheet1Sprite (2, 2) spriteFor LaserU = sheet1Sprite (3, 2) return$ M.fromList$ map (\tile -> (tile, spriteFor tile)) allTiles makeVFrame :: Sprite -> IO Surface makeVFrame boxSprite = do surface <- createRGBSurface [HWSurface] 26 546 32 0x000000FF 0x0000FF00 0x00FF0000 0xFF000000 >>= displayFormat forM_ (vBorderPos <$> [1..21])$ \pos -> do renderSprite surface 0 pos boxSprite return surface where vBorderPos n = (0, (n - 1) * 26) makeHFrame :: Sprite -> IO Surface makeHFrame boxSprite = do surface <- createRGBSurface [HWSurface] 494 26 32 0x000000FF 0x0000FF00 0x00FF0000 0xFF000000 >>= displayFormat forM_ (hBorderPos <$> [1..19])$ \pos -> do renderSprite surface 0 pos boxSprite return surface where hBorderPos n = ((n - 1) * 26, 0) makeBackground :: Sprite -> Sprite -> Sprite -> IO Surface makeBackground boxSprite hBorder vBorder = do surface <- createRGBSurface [HWSurface] 572 598 32 0x000000FF 0x0000FF00 0x00FF0000 0xFF000000 >>= displayFormat fillRect surface Nothing bgColor renderSprite surface 0 (0, 0) vBorder renderSprite surface 0 (26, 0) hBorder renderSprite surface 0 (26, 520) hBorder forM_ (boxPos <$> [1..9] <*> [1..9])$ \pos -> do renderSprite surface 0 pos boxSprite return surface where boxPos n m = (n * 52, m * 52) loadFont :: IO Font loadFont = openFont (getAssetPath "fonts/titillium/TitilliumText22L004.otf") 28
CLowcay/CC_Clones
src/Spaceships/Assets.hs
gpl-3.0
4,446
56
14
797
1,654
865
789
120
24
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} -- | Code taken from: -- -- http://mpickering.github.io/posts/2014-12-20-closed-type-family-data-types.html -- -- Calculating where an element (functor) should be injected at the type level. module Injection where import Data.Proxy -- | Co-product. data (f :+: g) e = Inl (f e) | Inr (g e) data Crumbs = Here | L Crumbs | R Crumbs data Res = Found Crumbs | NotFound -- Is @e@ an element of @f@? type family Elem e f :: Res where Elem e e = Found Here Elem e (l :+: r) = Choose (Elem e l) (Elem e r) type family Choose e f :: Res where Choose (Found a) b = Found (L a) Choose a (Found b) = Found (R b) Choose a b = NotFound class MakeInj (res :: Res) f g where mkInj :: Proxy res -> f a -> g a instance MakeInj (Found Here) f f where mkInj _ = id instance MakeInj (Found p) f l => MakeInj (Found (L p)) f (l :+: r) where mkInj _ = Inl . mkInj (Proxy :: Proxy (Found p)) instance MakeInj (Found p) f r => MakeInj (Found (R p)) f (l :+: r) where mkInj _ = Inr . mkInj (Proxy :: Proxy (Found p)) type f :<: g = MakeInj (Elem f g) f g -- This won't compile: -- -- > instance MakeInj (MakeInj (Found p) f l) => MakeInj (Found (L p)) f (l :+: r) where -- > mkInj _ = Inl . mkInj (Proxy :: Proxy (Found p)) -- -- > • Expected kind ‘Res’, -- > but ‘MakeInj ('Found p) f gl’ has kind ‘Constraint’ -- > • In the first argument of ‘MakeInj’, namely -- > ‘MakeInj (Found p) f gl’ -- > In the instance declaration for -- > ‘MakeInj (Found (L p)) f (gl :+: gr)’
capitanbatata/sandbox
typelevel-computations/src/Injection.hs
gpl-3.0
1,927
18
11
490
415
241
174
30
0
sum [x | x <- [1..999], x `mod` 3 == 0 || x `mod` 5 == 0]
Daphron/project-euler
p1.hs
gpl-3.0
59
0
12
18
51
27
24
-1
-1
module HEP.Automation.MadGraph.Dataset.Set20110715set3 where import HEP.Storage.WebDAV.Type import HEP.Automation.MadGraph.Model import HEP.Automation.MadGraph.Machine import HEP.Automation.MadGraph.UserCut import HEP.Automation.MadGraph.SetupType import HEP.Automation.MadGraph.Model.SChanC8V import HEP.Automation.MadGraph.Dataset.Processes import HEP.Automation.JobQueue.JobType processSetup :: ProcessSetup SChanC8V processSetup = PS { model = SChanC8V , process = preDefProcess TTBar0or1J , processBrief = "TTBar0or1J" , workname = "715_SChanC8V_TTBar0or1J_LHC" } paramSet :: [ModelParam SChanC8V] paramSet = [ SChanC8VParam { mnp = m, gnpqR = g1, gnpqL = 0, gnpbR = g1, gnpbL = 0, gnptR = g2, gnptL = 0 } | (m,g1,g2) <- (map (\x->(700,-0.05,x)) [2.0,2.5..6.0] ) ++ (map (\x->(850,-0.08,x)) [2.0,2.5..8.0] ) ++ [ (1000, -0.15, 3) , (1000, -0.125, 5) , (1000,-0.1,8) ] ++ [ (1500, -0.4,5.5) , (1500, -0.3, 8) ] ] sets :: [Int] sets = [1] ucut :: UserCut ucut = UserCut { uc_metcut = 15.0 , uc_etacutlep = 2.7 , uc_etcutlep = 18.0 , uc_etacutjet = 2.7 , uc_etcutjet = 15.0 } eventsets :: [EventSet] eventsets = [ EventSet processSetup (RS { param = p , numevent = 100000 , machine = LHC7 ATLAS , rgrun = Fixed , rgscale = 200.0 , match = MLM , cut = DefCut , pythia = RunPYTHIA , usercut = UserCutDef ucut -- NoUserCutDef -- , pgs = RunPGS , jetalgo = AntiKTJet 0.4 , uploadhep = NoUploadHEP , setnum = num }) | p <- paramSet , num <- sets ] webdavdir :: WebDAVRemoteDir webdavdir = WebDAVRemoteDir "paper3/ttbar_LHC_alvarez_pgsscan"
wavewave/madgraph-auto-dataset
src/HEP/Automation/MadGraph/Dataset/Set20110715set3.hs
gpl-3.0
2,023
0
16
712
542
340
202
51
1
{-# LANGUAGE OverloadedStrings #-} module Api (startApp) where import Users import Auth import Network.Wai import Network.Wai.Handler.Warp import Servant import Config type API = "user" :> Header "Authorization" AuthHeader :> Capture "username" String :> ReqBody '[JSON] User :> Put '[JSON] () api :: Proxy API api = Proxy startApp :: IO () startApp = run 3001 . app =<< loadConfig "web.cfg" app :: AuthConfig -> Application app cfg = serve api server where authenticate = authentication cfg authenticated e h x y = authenticate h >>= e x y server = authenticated register
patrickboe/wheel
src/lib/hs/Api.hs
gpl-3.0
620
0
11
139
196
103
93
-1
-1
{-# LANGUAGE ExtendedDefaultRules #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} -- Module : Khan.Model.IAM.Role -- Copyright : (c) 2013 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) module Khan.Model.IAM.Role ( Paths (..) , paths , find , findPolicy , update ) where import Data.Aeson import qualified Data.Text.Lazy as LText import qualified Filesystem.Path.CurrentOS as Path import Khan.Internal hiding (Role) import Khan.Prelude hiding (find) import Network.AWS.IAM default (Text) data Paths = Paths { pTrustPath :: !TrustPath , pPolicyPath :: !PolicyPath } paths :: Naming a => a -> ConfigDir -> TrustPath -- ^ Trust template path -> PolicyPath -- ^ Policy template path -> Paths paths (names -> Names{..}) (ConfigDir root) t p = Paths { pTrustPath = TrustPath $ defaultPath (_trust t) tpath , pPolicyPath = PolicyPath $ defaultPath (_policy p) ppath } where tpath = root </> Path.fromText "trust.ede" ppath = root </> "policies" </> Path.fromText roleName <.> "ede" find :: Naming a => a -> AWS Role find (names -> Names{..}) = do say "Finding IAM Role {}" [profileName] grrRole . grrGetRoleResult <$> send (GetRole profileName) findPolicy :: Naming a => a -> AWS GetRolePolicyResult findPolicy (names -> Names{..}) = do say "Finding IAM Policy for Role {}" [profileName] grprGetRolePolicyResult <$> send (GetRolePolicy profileName profileName) update :: Naming a => a -> TrustPath -> PolicyPath -> AWS Role update (names -> n@Names{..}) tpath ppath = do (t, p) <- (,) <$> renderTemplate o (_trust tpath) <*> renderTemplate o (_policy ppath) i <- sendAsync $ CreateInstanceProfile profileName Nothing r <- sendAsync $ CreateRole (LText.toStrict t) Nothing profileName b <- wait i >>= created _ <- wait r >>= created ar <- sendAsync $ AddRoleToInstanceProfile profileName profileName pr <- sendAsync $ PutRolePolicy (LText.toStrict p) profileName profileName wait ar >>= verifyIAM "LimitExceeded" waitAsync_ pr <* say "Updated policy for Role {}" [profileName] when b $ do say "Waiting {} seconds for IAM Role replication..." [B delay] delaySeconds delay find n where Object o = toJSON n created (Right _) = return True created e = verifyIAM "EntityAlreadyExists" e >> return False delay = 5
brendanhay/khan
khan/Khan/Model/IAM/Role.hs
mpl-2.0
3,072
0
12
817
745
383
362
66
2
{-# LANGUAGE OverloadedStrings #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.EC2.Types -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.AWS.EC2.Types ( -- * Service Configuration eC2 -- * Errors -- * AccountAttributeName , AccountAttributeName (..) -- * AddressStatus , AddressStatus (..) -- * ArchitectureValues , ArchitectureValues (..) -- * AttachmentStatus , AttachmentStatus (..) -- * AvailabilityZoneState , AvailabilityZoneState (..) -- * BatchState , BatchState (..) -- * BundleTaskState , BundleTaskState (..) -- * CancelBatchErrorCode , CancelBatchErrorCode (..) -- * CancelSpotInstanceRequestState , CancelSpotInstanceRequestState (..) -- * ContainerFormat , ContainerFormat (..) -- * ConversionTaskState , ConversionTaskState (..) -- * CurrencyCodeValues , CurrencyCodeValues (..) -- * DatafeedSubscriptionState , DatafeedSubscriptionState (..) -- * DeviceType , DeviceType (..) -- * DiskImageFormat , DiskImageFormat (..) -- * DomainType , DomainType (..) -- * EventCode , EventCode (..) -- * EventType , EventType (..) -- * ExportEnvironment , ExportEnvironment (..) -- * ExportTaskState , ExportTaskState (..) -- * FlowLogsResourceType , FlowLogsResourceType (..) -- * GatewayType , GatewayType (..) -- * HypervisorType , HypervisorType (..) -- * ImageAttributeName , ImageAttributeName (..) -- * ImageState , ImageState (..) -- * ImageTypeValues , ImageTypeValues (..) -- * InstanceAttributeName , InstanceAttributeName (..) -- * InstanceLifecycleType , InstanceLifecycleType (..) -- * InstanceStateName , InstanceStateName (..) -- * InstanceType , InstanceType (..) -- * ListingState , ListingState (..) -- * ListingStatus , ListingStatus (..) -- * MonitoringState , MonitoringState (..) -- * MoveStatus , MoveStatus (..) -- * NetworkInterfaceAttribute , NetworkInterfaceAttribute (..) -- * NetworkInterfaceStatus , NetworkInterfaceStatus (..) -- * OfferingTypeValues , OfferingTypeValues (..) -- * OperationType , OperationType (..) -- * PermissionGroup , PermissionGroup (..) -- * PlacementGroupState , PlacementGroupState (..) -- * PlacementStrategy , PlacementStrategy (..) -- * PlatformValues , PlatformValues (..) -- * ProductCodeValues , ProductCodeValues (..) -- * RIProductDescription , RIProductDescription (..) -- * RecurringChargeFrequency , RecurringChargeFrequency (..) -- * ReportInstanceReasonCodes , ReportInstanceReasonCodes (..) -- * ReportStatusType , ReportStatusType (..) -- * ReservedInstanceState , ReservedInstanceState (..) -- * ResetImageAttributeName , ResetImageAttributeName (..) -- * ResourceType , ResourceType (..) -- * RouteOrigin , RouteOrigin (..) -- * RouteState , RouteState (..) -- * RuleAction , RuleAction (..) -- * ShutdownBehavior , ShutdownBehavior (..) -- * SnapshotAttributeName , SnapshotAttributeName (..) -- * SnapshotState , SnapshotState (..) -- * SpotInstanceState , SpotInstanceState (..) -- * SpotInstanceType , SpotInstanceType (..) -- * State , State (..) -- * StatusName , StatusName (..) -- * StatusType , StatusType (..) -- * SubnetState , SubnetState (..) -- * SummaryStatus , SummaryStatus (..) -- * TelemetryStatus , TelemetryStatus (..) -- * Tenancy , Tenancy (..) -- * TrafficType , TrafficType (..) -- * VPCAttributeName , VPCAttributeName (..) -- * VPCPeeringConnectionStateReasonCode , VPCPeeringConnectionStateReasonCode (..) -- * VPCState , VPCState (..) -- * VPNState , VPNState (..) -- * VPNStaticRouteSource , VPNStaticRouteSource (..) -- * VirtualizationType , VirtualizationType (..) -- * VolumeAttachmentState , VolumeAttachmentState (..) -- * VolumeAttributeName , VolumeAttributeName (..) -- * VolumeState , VolumeState (..) -- * VolumeStatusInfoStatus , VolumeStatusInfoStatus (..) -- * VolumeStatusName , VolumeStatusName (..) -- * VolumeType , VolumeType (..) -- * AccountAttribute , AccountAttribute , accountAttribute , aaAttributeValues , aaAttributeName -- * AccountAttributeValue , AccountAttributeValue , accountAttributeValue , aavAttributeValue -- * ActiveInstance , ActiveInstance , activeInstance , aiInstanceId , aiInstanceType , aiSpotInstanceRequestId -- * Address , Address , address , aAssociationId , aInstanceId , aNetworkInterfaceOwnerId , aAllocationId , aDomain , aNetworkInterfaceId , aPrivateIPAddress , aPublicIP -- * AttributeBooleanValue , AttributeBooleanValue , attributeBooleanValue , abvValue -- * AttributeValue , AttributeValue , attributeValue , avValue -- * AvailabilityZone , AvailabilityZone , availabilityZone , azState , azRegionName , azZoneName , azMessages -- * AvailabilityZoneMessage , AvailabilityZoneMessage , availabilityZoneMessage , azmMessage -- * BlobAttributeValue , BlobAttributeValue , blobAttributeValue , bavValue -- * BlockDeviceMapping , BlockDeviceMapping , blockDeviceMapping , bdmVirtualName , bdmNoDevice , bdmEBS , bdmDeviceName -- * BundleTask , BundleTask , bundleTask , btBundleTaskError , btBundleId , btInstanceId , btProgress , btStartTime , btState , btStorage , btUpdateTime -- * BundleTaskError , BundleTaskError , bundleTaskError , bteCode , bteMessage -- * CancelSpotFleetRequestsError , CancelSpotFleetRequestsError , cancelSpotFleetRequestsError , csfreCode , csfreMessage -- * CancelSpotFleetRequestsErrorItem , CancelSpotFleetRequestsErrorItem , cancelSpotFleetRequestsErrorItem , csfreiSpotFleetRequestId , csfreiError -- * CancelSpotFleetRequestsSuccessItem , CancelSpotFleetRequestsSuccessItem , cancelSpotFleetRequestsSuccessItem , csfrsiSpotFleetRequestId , csfrsiCurrentSpotFleetRequestState , csfrsiPreviousSpotFleetRequestState -- * CancelledSpotInstanceRequest , CancelledSpotInstanceRequest , cancelledSpotInstanceRequest , csirState , csirSpotInstanceRequestId -- * ClassicLinkInstance , ClassicLinkInstance , classicLinkInstance , cliInstanceId , cliGroups , cliVPCId , cliTags -- * ClientData , ClientData , clientData , cdUploadStart , cdUploadSize , cdUploadEnd , cdComment -- * ConversionTask , ConversionTask , conversionTask , ctImportInstance , ctStatusMessage , ctImportVolume , ctExpirationTime , ctTags , ctConversionTaskId , ctState -- * CreateVolumePermission , CreateVolumePermission , createVolumePermission , cvpGroup , cvpUserId -- * CreateVolumePermissionModifications , CreateVolumePermissionModifications , createVolumePermissionModifications , cvpmRemove , cvpmAdd -- * CustomerGateway , CustomerGateway , customerGateway , cgTags , cgBGPASN , cgCustomerGatewayId , cgIPAddress , cgState , cgType -- * DHCPConfiguration , DHCPConfiguration , dhcpConfiguration , dcValues , dcKey -- * DHCPOptions , DHCPOptions , dhcpOptions , doDHCPConfigurations , doDHCPOptionsId , doTags -- * DiskImage , DiskImage , diskImage , diImage , diVolume , diDescription -- * DiskImageDescription , DiskImageDescription , diskImageDescription , dChecksum , dFormat , dSize , dImportManifestURL -- * DiskImageDetail , DiskImageDetail , diskImageDetail , didFormat , didBytes , didImportManifestURL -- * DiskImageVolumeDescription , DiskImageVolumeDescription , diskImageVolumeDescription , divdSize , divdId -- * EBSBlockDevice , EBSBlockDevice , ebsBlockDevice , ebdDeleteOnTermination , ebdVolumeSize , ebdIOPS , ebdEncrypted , ebdVolumeType , ebdSnapshotId -- * EBSInstanceBlockDevice , EBSInstanceBlockDevice , ebsInstanceBlockDevice , eibdStatus , eibdDeleteOnTermination , eibdVolumeId , eibdAttachTime -- * EBSInstanceBlockDeviceSpecification , EBSInstanceBlockDeviceSpecification , ebsInstanceBlockDeviceSpecification , eibdsDeleteOnTermination , eibdsVolumeId -- * EventInformation , EventInformation , eventInformation , eiInstanceId , eiEventDescription , eiEventSubType -- * ExportTask , ExportTask , exportTask , etDescription , etExportTaskId , etExportToS3Task , etInstanceExportDetails , etState , etStatusMessage -- * ExportToS3Task , ExportToS3Task , exportToS3Task , etstS3Key , etstContainerFormat , etstS3Bucket , etstDiskImageFormat -- * ExportToS3TaskSpecification , ExportToS3TaskSpecification , exportToS3TaskSpecification , etstsContainerFormat , etstsS3Prefix , etstsS3Bucket , etstsDiskImageFormat -- * Filter , Filter , filter' , fValues , fName -- * FlowLog , FlowLog , flowLog , flCreationTime , flResourceId , flFlowLogStatus , flTrafficType , flDeliverLogsStatus , flDeliverLogsErrorMessage , flLogGroupName , flDeliverLogsPermissionARN , flFlowLogId -- * GroupIdentifier , GroupIdentifier , groupIdentifier , giGroupId , giGroupName -- * HistoryRecord , HistoryRecord , historyRecord , hrTimestamp , hrEventType , hrEventInformation -- * IAMInstanceProfile , IAMInstanceProfile , iamInstanceProfile , iapARN , iapId -- * IAMInstanceProfileSpecification , IAMInstanceProfileSpecification , iamInstanceProfileSpecification , iapsARN , iapsName -- * ICMPTypeCode , ICMPTypeCode , icmpTypeCode , itcCode , itcType -- * IPPermission , IPPermission , ipPermission , ipFromPort , ipUserIdGroupPairs , ipPrefixListIds , ipToPort , ipIPRanges , ipIPProtocol -- * IPRange , IPRange , ipRange , irCIdRIP -- * Image , Image , image , iPlatform , iImageOwnerAlias , iRAMDiskId , iKernelId , iRootDeviceName , iSRIOVNetSupport , iName , iCreationDate , iProductCodes , iStateReason , iDescription , iBlockDeviceMappings , iTags , iImageId , iImageLocation , iState , iOwnerId , iPublic , iArchitecture , iImageType , iRootDeviceType , iVirtualizationType , iHypervisor -- * ImageDiskContainer , ImageDiskContainer , imageDiskContainer , idcFormat , idcURL , idcDeviceName , idcUserBucket , idcDescription , idcSnapshotId -- * ImportImageTask , ImportImageTask , importImageTask , iitStatus , iitHypervisor , iitPlatform , iitProgress , iitLicenseType , iitSnapshotDetails , iitStatusMessage , iitImageId , iitImportTaskId , iitArchitecture , iitDescription -- * ImportInstanceLaunchSpecification , ImportInstanceLaunchSpecification , importInstanceLaunchSpecification , iilsAdditionalInfo , iilsGroupNames , iilsSubnetId , iilsInstanceType , iilsGroupIds , iilsUserData , iilsMonitoring , iilsPrivateIPAddress , iilsInstanceInitiatedShutdownBehavior , iilsArchitecture , iilsPlacement -- * ImportInstanceTaskDetails , ImportInstanceTaskDetails , importInstanceTaskDetails , iitdInstanceId , iitdPlatform , iitdDescription , iitdVolumes -- * ImportInstanceVolumeDetailItem , ImportInstanceVolumeDetailItem , importInstanceVolumeDetailItem , iivdiStatusMessage , iivdiDescription , iivdiBytesConverted , iivdiAvailabilityZone , iivdiImage , iivdiVolume , iivdiStatus -- * ImportSnapshotTask , ImportSnapshotTask , importSnapshotTask , istSnapshotTaskDetail , istImportTaskId , istDescription -- * ImportVolumeTaskDetails , ImportVolumeTaskDetails , importVolumeTaskDetails , ivtdDescription , ivtdBytesConverted , ivtdAvailabilityZone , ivtdImage , ivtdVolume -- * Instance , Instance , instance' , insPublicDNSName , insPlatform , insSecurityGroups , insClientToken , insSourceDestCheck , insVPCId , insKeyName , insNetworkInterfaces , insRAMDiskId , insSubnetId , insKernelId , insRootDeviceName , insSRIOVNetSupport , insEBSOptimized , insStateTransitionReason , insInstanceLifecycle , insIAMInstanceProfile , insPrivateIPAddress , insProductCodes , insSpotInstanceRequestId , insPrivateDNSName , insStateReason , insBlockDeviceMappings , insPublicIPAddress , insTags , insInstanceId , insImageId , insAMILaunchIndex , insInstanceType , insLaunchTime , insPlacement , insMonitoring , insArchitecture , insRootDeviceType , insVirtualizationType , insHypervisor , insState -- * InstanceBlockDeviceMapping , InstanceBlockDeviceMapping , instanceBlockDeviceMapping , ibdmEBS , ibdmDeviceName -- * InstanceBlockDeviceMappingSpecification , InstanceBlockDeviceMappingSpecification , instanceBlockDeviceMappingSpecification , ibdmsVirtualName , ibdmsNoDevice , ibdmsEBS , ibdmsDeviceName -- * InstanceCount , InstanceCount , instanceCount , icState , icInstanceCount -- * InstanceExportDetails , InstanceExportDetails , instanceExportDetails , iedTargetEnvironment , iedInstanceId -- * InstanceMonitoring , InstanceMonitoring , instanceMonitoring , imInstanceId , imMonitoring -- * InstanceNetworkInterface , InstanceNetworkInterface , instanceNetworkInterface , iniGroups , iniStatus , iniPrivateIPAddresses , iniSourceDestCheck , iniVPCId , iniNetworkInterfaceId , iniSubnetId , iniMACAddress , iniAttachment , iniOwnerId , iniPrivateIPAddress , iniPrivateDNSName , iniDescription , iniAssociation -- * InstanceNetworkInterfaceAssociation , InstanceNetworkInterfaceAssociation , instanceNetworkInterfaceAssociation , iniaPublicDNSName , iniaIPOwnerId , iniaPublicIP -- * InstanceNetworkInterfaceAttachment , InstanceNetworkInterfaceAttachment , instanceNetworkInterfaceAttachment , iniaStatus , iniaDeleteOnTermination , iniaAttachmentId , iniaAttachTime , iniaDeviceIndex -- * InstanceNetworkInterfaceSpecification , InstanceNetworkInterfaceSpecification , instanceNetworkInterfaceSpecification , inisGroups , inisPrivateIPAddresses , inisDeleteOnTermination , inisAssociatePublicIPAddress , inisNetworkInterfaceId , inisSubnetId , inisPrivateIPAddress , inisSecondaryPrivateIPAddressCount , inisDescription , inisDeviceIndex -- * InstancePrivateIPAddress , InstancePrivateIPAddress , instancePrivateIPAddress , ipiaPrimary , ipiaPrivateIPAddress , ipiaPrivateDNSName , ipiaAssociation -- * InstanceState , InstanceState , instanceState , isName , isCode -- * InstanceStateChange , InstanceStateChange , instanceStateChange , iscInstanceId , iscCurrentState , iscPreviousState -- * InstanceStatus , InstanceStatus , instanceStatus , isInstanceId , isSystemStatus , isEvents , isAvailabilityZone , isInstanceStatus , isInstanceState -- * InstanceStatusDetails , InstanceStatusDetails , instanceStatusDetails , isdStatus , isdImpairedSince , isdName -- * InstanceStatusEvent , InstanceStatusEvent , instanceStatusEvent , iseNotBefore , iseCode , iseDescription , iseNotAfter -- * InstanceStatusSummary , InstanceStatusSummary , instanceStatusSummary , issDetails , issStatus -- * InternetGateway , InternetGateway , internetGateway , igAttachments , igTags , igInternetGatewayId -- * InternetGatewayAttachment , InternetGatewayAttachment , internetGatewayAttachment , igaState , igaVPCId -- * KeyPairInfo , KeyPairInfo , keyPairInfo , kpiKeyFingerprint , kpiKeyName -- * LaunchPermission , LaunchPermission , launchPermission , lpGroup , lpUserId -- * LaunchPermissionModifications , LaunchPermissionModifications , launchPermissionModifications , lpmRemove , lpmAdd -- * LaunchSpecification , LaunchSpecification , launchSpecification , lsSecurityGroups , lsKeyName , lsNetworkInterfaces , lsRAMDiskId , lsSubnetId , lsKernelId , lsInstanceType , lsEBSOptimized , lsUserData , lsMonitoring , lsIAMInstanceProfile , lsImageId , lsAddressingType , lsBlockDeviceMappings , lsPlacement -- * Monitoring , Monitoring , monitoring , mState -- * MovingAddressStatus , MovingAddressStatus , movingAddressStatus , masMoveStatus , masPublicIP -- * NetworkACL , NetworkACL , networkACL , naEntries , naNetworkACLId , naVPCId , naAssociations , naTags , naIsDefault -- * NetworkACLAssociation , NetworkACLAssociation , networkACLAssociation , naaNetworkACLId , naaSubnetId , naaNetworkACLAssociationId -- * NetworkACLEntry , NetworkACLEntry , networkACLEntry , naeICMPTypeCode , naeRuleNumber , naeRuleAction , naeProtocol , naePortRange , naeCIdRBlock , naeEgress -- * NetworkInterface , NetworkInterface , networkInterface , niGroups , niStatus , niPrivateIPAddresses , niSourceDestCheck , niVPCId , niTagSet , niRequesterManaged , niNetworkInterfaceId , niSubnetId , niMACAddress , niAttachment , niOwnerId , niAvailabilityZone , niPrivateIPAddress , niPrivateDNSName , niRequesterId , niDescription , niAssociation -- * NetworkInterfaceAssociation , NetworkInterfaceAssociation , networkInterfaceAssociation , niaAssociationId , niaPublicDNSName , niaAllocationId , niaIPOwnerId , niaPublicIP -- * NetworkInterfaceAttachment , NetworkInterfaceAttachment , networkInterfaceAttachment , niaInstanceId , niaStatus , niaDeleteOnTermination , niaAttachmentId , niaInstanceOwnerId , niaAttachTime , niaDeviceIndex -- * NetworkInterfaceAttachmentChanges , NetworkInterfaceAttachmentChanges , networkInterfaceAttachmentChanges , niacDeleteOnTermination , niacAttachmentId -- * NetworkInterfacePrivateIPAddress , NetworkInterfacePrivateIPAddress , networkInterfacePrivateIPAddress , nipiaPrimary , nipiaPrivateIPAddress , nipiaPrivateDNSName , nipiaAssociation -- * NewDHCPConfiguration , NewDHCPConfiguration , newDHCPConfiguration , ndcValues , ndcKey -- * Placement , Placement , placement , pAvailabilityZone , pTenancy , pGroupName -- * PlacementGroup , PlacementGroup , placementGroup , pgState , pgStrategy , pgGroupName -- * PortRange , PortRange , portRange , prTo , prFrom -- * PrefixList , PrefixList , prefixList , plCIdRs , plPrefixListId , plPrefixListName -- * PrefixListId , PrefixListId , prefixListId , pliPrefixListId -- * PriceSchedule , PriceSchedule , priceSchedule , psCurrencyCode , psTerm , psActive , psPrice -- * PriceScheduleSpecification , PriceScheduleSpecification , priceScheduleSpecification , pssCurrencyCode , pssTerm , pssPrice -- * PricingDetail , PricingDetail , pricingDetail , pdCount , pdPrice -- * PrivateIPAddressSpecification , PrivateIPAddressSpecification , privateIPAddressSpecification , piasPrimary , piasPrivateIPAddress -- * ProductCode , ProductCode , productCode , pcProductCodeType , pcProductCodeId -- * PropagatingVGW , PropagatingVGW , propagatingVGW , pvGatewayId -- * RecurringCharge , RecurringCharge , recurringCharge , rcAmount , rcFrequency -- * RegionInfo , RegionInfo , regionInfo , riRegionName , riEndpoint -- * RequestSpotLaunchSpecification , RequestSpotLaunchSpecification , requestSpotLaunchSpecification , rslsSecurityGroupIds , rslsSecurityGroups , rslsKeyName , rslsNetworkInterfaces , rslsRAMDiskId , rslsSubnetId , rslsKernelId , rslsInstanceType , rslsEBSOptimized , rslsUserData , rslsMonitoring , rslsIAMInstanceProfile , rslsImageId , rslsAddressingType , rslsBlockDeviceMappings , rslsPlacement -- * Reservation , Reservation , reservation , rGroups , rInstances , rRequesterId , rReservationId , rOwnerId -- * ReservedInstanceLimitPrice , ReservedInstanceLimitPrice , reservedInstanceLimitPrice , rilpAmount , rilpCurrencyCode -- * ReservedInstances , ReservedInstances , reservedInstances , riState , riCurrencyCode , riInstanceCount , riProductDescription , riStart , riInstanceType , riEnd , riAvailabilityZone , riRecurringCharges , riOfferingType , riUsagePrice , riFixedPrice , riReservedInstancesId , riInstanceTenancy , riDuration , riTags -- * ReservedInstancesConfiguration , ReservedInstancesConfiguration , reservedInstancesConfiguration , ricPlatform , ricInstanceCount , ricInstanceType , ricAvailabilityZone -- * ReservedInstancesId , ReservedInstancesId , reservedInstancesId , riiReservedInstancesId -- * ReservedInstancesListing , ReservedInstancesListing , reservedInstancesListing , rilStatus , rilClientToken , rilUpdateDate , rilCreateDate , rilPriceSchedules , rilStatusMessage , rilReservedInstancesId , rilTags , rilInstanceCounts , rilReservedInstancesListingId -- * ReservedInstancesModification , ReservedInstancesModification , reservedInstancesModification , rimModificationResults , rimStatus , rimClientToken , rimUpdateDate , rimCreateDate , rimEffectiveDate , rimStatusMessage , rimReservedInstancesModificationId , rimReservedInstancesIds -- * ReservedInstancesModificationResult , ReservedInstancesModificationResult , reservedInstancesModificationResult , rimrReservedInstancesId , rimrTargetConfiguration -- * ReservedInstancesOffering , ReservedInstancesOffering , reservedInstancesOffering , rioMarketplace , rioCurrencyCode , rioProductDescription , rioInstanceType , rioAvailabilityZone , rioPricingDetails , rioRecurringCharges , rioOfferingType , rioUsagePrice , rioFixedPrice , rioInstanceTenancy , rioReservedInstancesOfferingId , rioDuration -- * Route , Route , route , rVPCPeeringConnectionId , rInstanceId , rOrigin , rState , rNetworkInterfaceId , rGatewayId , rInstanceOwnerId , rDestinationPrefixListId , rDestinationCIdRBlock -- * RouteTable , RouteTable , routeTable , rtRouteTableId , rtRoutes , rtVPCId , rtPropagatingVGWs , rtAssociations , rtTags -- * RouteTableAssociation , RouteTableAssociation , routeTableAssociation , rtaRouteTableId , rtaRouteTableAssociationId , rtaMain , rtaSubnetId -- * RunInstancesMonitoringEnabled , RunInstancesMonitoringEnabled , runInstancesMonitoringEnabled , rimeEnabled -- * S3Storage , S3Storage , s3Storage , ssPrefix , ssUploadPolicy , ssBucket , ssUploadPolicySignature , ssAWSAccessKeyId -- * SecurityGroup , SecurityGroup , securityGroup , sgVPCId , sgIPPermissions , sgIPPermissionsEgress , sgTags , sgOwnerId , sgGroupId , sgGroupName , sgDescription -- * Snapshot , Snapshot , snapshot , sOwnerAlias , sKMSKeyId , sTags , sSnapshotId , sOwnerId , sVolumeId , sVolumeSize , sDescription , sStartTime , sProgress , sState , sEncrypted -- * SnapshotDetail , SnapshotDetail , snapshotDetail , sdStatus , sdProgress , sdFormat , sdURL , sdDeviceName , sdStatusMessage , sdUserBucket , sdDiskImageSize , sdDescription , sdSnapshotId -- * SnapshotDiskContainer , SnapshotDiskContainer , snapshotDiskContainer , sdcFormat , sdcURL , sdcUserBucket , sdcDescription -- * SnapshotTaskDetail , SnapshotTaskDetail , snapshotTaskDetail , stdStatus , stdProgress , stdFormat , stdURL , stdStatusMessage , stdUserBucket , stdDiskImageSize , stdDescription , stdSnapshotId -- * SpotDatafeedSubscription , SpotDatafeedSubscription , spotDatafeedSubscription , sdsState , sdsPrefix , sdsBucket , sdsOwnerId , sdsFault -- * SpotFleetLaunchSpecification , SpotFleetLaunchSpecification , spotFleetLaunchSpecification , sflsSecurityGroups , sflsSpotPrice , sflsWeightedCapacity , sflsKeyName , sflsNetworkInterfaces , sflsRAMDiskId , sflsSubnetId , sflsKernelId , sflsInstanceType , sflsEBSOptimized , sflsUserData , sflsMonitoring , sflsIAMInstanceProfile , sflsImageId , sflsAddressingType , sflsBlockDeviceMappings , sflsPlacement -- * SpotFleetMonitoring , SpotFleetMonitoring , spotFleetMonitoring , sfmEnabled -- * SpotFleetRequestConfig , SpotFleetRequestConfig , spotFleetRequestConfig , sfrcSpotFleetRequestId , sfrcSpotFleetRequestState , sfrcSpotFleetRequestConfig -- * SpotFleetRequestConfigData , SpotFleetRequestConfigData , spotFleetRequestConfigData , sfrcdClientToken , sfrcdValidUntil , sfrcdTerminateInstancesWithExpiration , sfrcdValidFrom , sfrcdSpotPrice , sfrcdTargetCapacity , sfrcdIAMFleetRole , sfrcdLaunchSpecifications -- * SpotInstanceRequest , SpotInstanceRequest , spotInstanceRequest , sirInstanceId , sirStatus , sirState , sirProductDescription , sirSpotPrice , sirLaunchSpecification , sirAvailabilityZoneGroup , sirLaunchedAvailabilityZone , sirValidUntil , sirLaunchGroup , sirFault , sirSpotInstanceRequestId , sirType , sirValidFrom , sirCreateTime , sirTags -- * SpotInstanceStateFault , SpotInstanceStateFault , spotInstanceStateFault , sisfCode , sisfMessage -- * SpotInstanceStatus , SpotInstanceStatus , spotInstanceStatus , sisUpdateTime , sisCode , sisMessage -- * SpotPlacement , SpotPlacement , spotPlacement , spAvailabilityZone , spGroupName -- * SpotPrice , SpotPrice , spotPrice , sProductDescription , sSpotPrice , sInstanceType , sAvailabilityZone , sTimestamp -- * StateReason , StateReason , stateReason , srCode , srMessage -- * Storage , Storage , storage , sS3 -- * Subnet , Subnet , subnet , subTags , subAvailabilityZone , subAvailableIPAddressCount , subCIdRBlock , subDefaultForAz , subMapPublicIPOnLaunch , subState , subSubnetId , subVPCId -- * Tag , Tag , tag , tagKey , tagValue -- * TagDescription , TagDescription , tagDescription , tdResourceId , tdResourceType , tdKey , tdValue -- * UnsuccessfulItem , UnsuccessfulItem , unsuccessfulItem , uiResourceId , uiError -- * UnsuccessfulItemError , UnsuccessfulItemError , unsuccessfulItemError , uieCode , uieMessage -- * UserBucket , UserBucket , userBucket , ubS3Key , ubS3Bucket -- * UserBucketDetails , UserBucketDetails , userBucketDetails , ubdS3Key , ubdS3Bucket -- * UserData , UserData , userData , udData -- * UserIdGroupPair , UserIdGroupPair , userIdGroupPair , uigpUserId , uigpGroupId , uigpGroupName -- * VGWTelemetry , VGWTelemetry , vgwTelemetry , vtStatus , vtOutsideIPAddress , vtLastStatusChange , vtAcceptedRouteCount , vtStatusMessage -- * VPC , VPC , vpc , vpcTags , vpcCIdRBlock , vpcDHCPOptionsId , vpcInstanceTenancy , vpcIsDefault , vpcState , vpcVPCId -- * VPCAttachment , VPCAttachment , vpcAttachment , vaState , vaVPCId -- * VPCClassicLink , VPCClassicLink , vpcClassicLink , vclVPCId , vclTags , vclClassicLinkEnabled -- * VPCEndpoint , VPCEndpoint , vpcEndpoint , veState , vePolicyDocument , veVPCId , veCreationTimestamp , veServiceName , veVPCEndpointId , veRouteTableIds -- * VPCPeeringConnection , VPCPeeringConnection , vpcPeeringConnection , vpcpcVPCPeeringConnectionId , vpcpcStatus , vpcpcAccepterVPCInfo , vpcpcRequesterVPCInfo , vpcpcExpirationTime , vpcpcTags -- * VPCPeeringConnectionStateReason , VPCPeeringConnectionStateReason , vpcPeeringConnectionStateReason , vpcsrCode , vpcsrMessage -- * VPCPeeringConnectionVPCInfo , VPCPeeringConnectionVPCInfo , vpcPeeringConnectionVPCInfo , vpcviVPCId , vpcviOwnerId , vpcviCIdRBlock -- * VPNConnection , VPNConnection , vpnConnection , vcCustomerGatewayConfiguration , vcRoutes , vcVPNGatewayId , vcOptions , vcTags , vcVGWTelemetry , vcVPNConnectionId , vcCustomerGatewayId , vcState , vcType -- * VPNConnectionOptions , VPNConnectionOptions , vpnConnectionOptions , vcoStaticRoutesOnly -- * VPNConnectionOptionsSpecification , VPNConnectionOptionsSpecification , vpnConnectionOptionsSpecification , vcosStaticRoutesOnly -- * VPNGateway , VPNGateway , vpnGateway , vgState , vgVPCAttachments , vgVPNGatewayId , vgAvailabilityZone , vgType , vgTags -- * VPNStaticRoute , VPNStaticRoute , vpnStaticRoute , vsrState , vsrSource , vsrDestinationCIdRBlock -- * Volume , Volume , volume , vAttachments , vIOPS , vKMSKeyId , vTags , vAvailabilityZone , vCreateTime , vEncrypted , vSize , vSnapshotId , vState , vVolumeId , vVolumeType -- * VolumeAttachment , VolumeAttachment , volumeAttachment , volInstanceId , volDeleteOnTermination , volState , volDevice , volVolumeId , volAttachTime -- * VolumeDetail , VolumeDetail , volumeDetail , vdSize -- * VolumeStatusAction , VolumeStatusAction , volumeStatusAction , vsaEventType , vsaCode , vsaDescription , vsaEventId -- * VolumeStatusDetails , VolumeStatusDetails , volumeStatusDetails , vsdStatus , vsdName -- * VolumeStatusEvent , VolumeStatusEvent , volumeStatusEvent , vseNotBefore , vseEventType , vseDescription , vseNotAfter , vseEventId -- * VolumeStatusInfo , VolumeStatusInfo , volumeStatusInfo , vsiStatus , vsiDetails -- * VolumeStatusItem , VolumeStatusItem , volumeStatusItem , vsiVolumeStatus , vsiActions , vsiEvents , vsiAvailabilityZone , vsiVolumeId ) where import Network.AWS.EC2.Types.Product import Network.AWS.EC2.Types.Sum import Network.AWS.Prelude import Network.AWS.Sign.V4 -- | API version '2015-04-15' of the Amazon Elastic Compute Cloud SDK configuration. eC2 :: Service eC2 = Service { _svcAbbrev = "EC2" , _svcSigner = v4 , _svcPrefix = "ec2" , _svcVersion = "2015-04-15" , _svcEndpoint = defaultEndpoint eC2 , _svcTimeout = Just 70 , _svcCheck = statusSuccess , _svcError = parseXMLError , _svcRetry = retry } where retry = Exponential { _retryBase = 5.0e-2 , _retryGrowth = 2 , _retryAttempts = 5 , _retryCheck = check } check e | has (hasCode "RequestLimitExceeded" . hasStatus 503) e = Just "request_limit_exceeded" | has (hasCode "ThrottlingException" . hasStatus 400) e = Just "throttling_exception" | has (hasCode "Throttling" . hasStatus 400) e = Just "throttling" | has (hasStatus 503) e = Just "service_unavailable" | has (hasStatus 500) e = Just "general_server_error" | has (hasStatus 509) e = Just "limit_exceeded" | otherwise = Nothing
fmapfmapfmap/amazonka
amazonka-ec2/gen/Network/AWS/EC2/Types.hs
mpl-2.0
34,216
0
13
9,434
4,376
2,985
1,391
1,200
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.RegionInstanceGroupManagers.SetTargetPools -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Modifies the target pools to which all new instances in this group are -- assigned. Existing instances in the group are not affected. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionInstanceGroupManagers.setTargetPools@. module Network.Google.Resource.Compute.RegionInstanceGroupManagers.SetTargetPools ( -- * REST Resource RegionInstanceGroupManagersSetTargetPoolsResource -- * Creating a Request , regionInstanceGroupManagersSetTargetPools , RegionInstanceGroupManagersSetTargetPools -- * Request Lenses , rigmstpRequestId , rigmstpProject , rigmstpInstanceGroupManager , rigmstpPayload , rigmstpRegion ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.regionInstanceGroupManagers.setTargetPools@ method which the -- 'RegionInstanceGroupManagersSetTargetPools' request conforms to. type RegionInstanceGroupManagersSetTargetPoolsResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "instanceGroupManagers" :> Capture "instanceGroupManager" Text :> "setTargetPools" :> QueryParam "requestId" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] RegionInstanceGroupManagersSetTargetPoolsRequest :> Post '[JSON] Operation -- | Modifies the target pools to which all new instances in this group are -- assigned. Existing instances in the group are not affected. -- -- /See:/ 'regionInstanceGroupManagersSetTargetPools' smart constructor. data RegionInstanceGroupManagersSetTargetPools = RegionInstanceGroupManagersSetTargetPools' { _rigmstpRequestId :: !(Maybe Text) , _rigmstpProject :: !Text , _rigmstpInstanceGroupManager :: !Text , _rigmstpPayload :: !RegionInstanceGroupManagersSetTargetPoolsRequest , _rigmstpRegion :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RegionInstanceGroupManagersSetTargetPools' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rigmstpRequestId' -- -- * 'rigmstpProject' -- -- * 'rigmstpInstanceGroupManager' -- -- * 'rigmstpPayload' -- -- * 'rigmstpRegion' regionInstanceGroupManagersSetTargetPools :: Text -- ^ 'rigmstpProject' -> Text -- ^ 'rigmstpInstanceGroupManager' -> RegionInstanceGroupManagersSetTargetPoolsRequest -- ^ 'rigmstpPayload' -> Text -- ^ 'rigmstpRegion' -> RegionInstanceGroupManagersSetTargetPools regionInstanceGroupManagersSetTargetPools pRigmstpProject_ pRigmstpInstanceGroupManager_ pRigmstpPayload_ pRigmstpRegion_ = RegionInstanceGroupManagersSetTargetPools' { _rigmstpRequestId = Nothing , _rigmstpProject = pRigmstpProject_ , _rigmstpInstanceGroupManager = pRigmstpInstanceGroupManager_ , _rigmstpPayload = pRigmstpPayload_ , _rigmstpRegion = pRigmstpRegion_ } -- | An optional request ID to identify requests. Specify a unique request ID -- so that if you must retry your request, the server will know to ignore -- the request if it has already been completed. For example, consider a -- situation where you make an initial request and the request times out. -- If you make the request again with the same request ID, the server can -- check if original operation with the same request ID was received, and -- if so, will ignore the second request. This prevents clients from -- accidentally creating duplicate commitments. The request ID must be a -- valid UUID with the exception that zero UUID is not supported -- (00000000-0000-0000-0000-000000000000). rigmstpRequestId :: Lens' RegionInstanceGroupManagersSetTargetPools (Maybe Text) rigmstpRequestId = lens _rigmstpRequestId (\ s a -> s{_rigmstpRequestId = a}) -- | Project ID for this request. rigmstpProject :: Lens' RegionInstanceGroupManagersSetTargetPools Text rigmstpProject = lens _rigmstpProject (\ s a -> s{_rigmstpProject = a}) -- | Name of the managed instance group. rigmstpInstanceGroupManager :: Lens' RegionInstanceGroupManagersSetTargetPools Text rigmstpInstanceGroupManager = lens _rigmstpInstanceGroupManager (\ s a -> s{_rigmstpInstanceGroupManager = a}) -- | Multipart request metadata. rigmstpPayload :: Lens' RegionInstanceGroupManagersSetTargetPools RegionInstanceGroupManagersSetTargetPoolsRequest rigmstpPayload = lens _rigmstpPayload (\ s a -> s{_rigmstpPayload = a}) -- | Name of the region scoping this request. rigmstpRegion :: Lens' RegionInstanceGroupManagersSetTargetPools Text rigmstpRegion = lens _rigmstpRegion (\ s a -> s{_rigmstpRegion = a}) instance GoogleRequest RegionInstanceGroupManagersSetTargetPools where type Rs RegionInstanceGroupManagersSetTargetPools = Operation type Scopes RegionInstanceGroupManagersSetTargetPools = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient RegionInstanceGroupManagersSetTargetPools'{..} = go _rigmstpProject _rigmstpRegion _rigmstpInstanceGroupManager _rigmstpRequestId (Just AltJSON) _rigmstpPayload computeService where go = buildClient (Proxy :: Proxy RegionInstanceGroupManagersSetTargetPoolsResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/RegionInstanceGroupManagers/SetTargetPools.hs
mpl-2.0
6,625
0
19
1,448
638
380
258
111
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Directory.Groups.Patch -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates a group\'s properties. This method supports [patch -- semantics](\/admin-sdk\/directory\/v1\/guides\/performance#patch). -- -- /See:/ <https://developers.google.com/admin-sdk/ Admin SDK API Reference> for @directory.groups.patch@. module Network.Google.Resource.Directory.Groups.Patch ( -- * REST Resource GroupsPatchResource -- * Creating a Request , groupsPatch , GroupsPatch -- * Request Lenses , gpXgafv , gpUploadProtocol , gpAccessToken , gpGroupKey , gpUploadType , gpPayload , gpCallback ) where import Network.Google.Directory.Types import Network.Google.Prelude -- | A resource alias for @directory.groups.patch@ method which the -- 'GroupsPatch' request conforms to. type GroupsPatchResource = "admin" :> "directory" :> "v1" :> "groups" :> Capture "groupKey" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Group :> Patch '[JSON] Group -- | Updates a group\'s properties. This method supports [patch -- semantics](\/admin-sdk\/directory\/v1\/guides\/performance#patch). -- -- /See:/ 'groupsPatch' smart constructor. data GroupsPatch = GroupsPatch' { _gpXgafv :: !(Maybe Xgafv) , _gpUploadProtocol :: !(Maybe Text) , _gpAccessToken :: !(Maybe Text) , _gpGroupKey :: !Text , _gpUploadType :: !(Maybe Text) , _gpPayload :: !Group , _gpCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GroupsPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gpXgafv' -- -- * 'gpUploadProtocol' -- -- * 'gpAccessToken' -- -- * 'gpGroupKey' -- -- * 'gpUploadType' -- -- * 'gpPayload' -- -- * 'gpCallback' groupsPatch :: Text -- ^ 'gpGroupKey' -> Group -- ^ 'gpPayload' -> GroupsPatch groupsPatch pGpGroupKey_ pGpPayload_ = GroupsPatch' { _gpXgafv = Nothing , _gpUploadProtocol = Nothing , _gpAccessToken = Nothing , _gpGroupKey = pGpGroupKey_ , _gpUploadType = Nothing , _gpPayload = pGpPayload_ , _gpCallback = Nothing } -- | V1 error format. gpXgafv :: Lens' GroupsPatch (Maybe Xgafv) gpXgafv = lens _gpXgafv (\ s a -> s{_gpXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). gpUploadProtocol :: Lens' GroupsPatch (Maybe Text) gpUploadProtocol = lens _gpUploadProtocol (\ s a -> s{_gpUploadProtocol = a}) -- | OAuth access token. gpAccessToken :: Lens' GroupsPatch (Maybe Text) gpAccessToken = lens _gpAccessToken (\ s a -> s{_gpAccessToken = a}) -- | Identifies the group in the API request. The value can be the group\'s -- email address, group alias, or the unique group ID. gpGroupKey :: Lens' GroupsPatch Text gpGroupKey = lens _gpGroupKey (\ s a -> s{_gpGroupKey = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). gpUploadType :: Lens' GroupsPatch (Maybe Text) gpUploadType = lens _gpUploadType (\ s a -> s{_gpUploadType = a}) -- | Multipart request metadata. gpPayload :: Lens' GroupsPatch Group gpPayload = lens _gpPayload (\ s a -> s{_gpPayload = a}) -- | JSONP gpCallback :: Lens' GroupsPatch (Maybe Text) gpCallback = lens _gpCallback (\ s a -> s{_gpCallback = a}) instance GoogleRequest GroupsPatch where type Rs GroupsPatch = Group type Scopes GroupsPatch = '["https://www.googleapis.com/auth/admin.directory.group"] requestClient GroupsPatch'{..} = go _gpGroupKey _gpXgafv _gpUploadProtocol _gpAccessToken _gpUploadType _gpCallback (Just AltJSON) _gpPayload directoryService where go = buildClient (Proxy :: Proxy GroupsPatchResource) mempty
brendanhay/gogol
gogol-admin-directory/gen/Network/Google/Resource/Directory/Groups/Patch.hs
mpl-2.0
4,937
0
19
1,204
789
460
329
113
1
data Heap = Heap {value :: Int, left :: Heap, right :: Heap} | Empty deriving (Eq, Show) heapWith value = Heap value Empty Empty add :: Int -> Heap -> Heap add value Empty = Heap value Empty Empty add value (Heap x Empty Empty) = if value < x then Heap value (heapWith x) Empty else Heap x (heapWith value) Empty add value (Heap x leftHeap Empty) = if value < x then Heap value leftHeap (heapWith x) else Heap x leftHeap (heapWith value) add value (Heap x Empty rightHeap) = if value < x then Heap value (heapWith x) rightHeap else Heap x (heapWith value) rightHeap --add value (Heap x (Heap leftX _ _) (Hep rightX _ _)) = -- if value < x then -- if value < leftX Heap value (heapWith x) rightHeap -- else -- else Heap x (heapWith value) rightHeap main = do putStrLn $ show $ Empty putStrLn $ show $ Heap 123 Empty Empty putStrLn $ show $ add 2 Empty putStrLn $ show $ add 1 $ add 2 Empty putStrLn $ show $ add 0 $ add 1 $ add 2 Empty putStrLn $ show $ add 3 $ add 1 $ add 2 Empty putStrLn $ show $ add 4 $ add 3 $ add 1 $ add 2 Empty
dkandalov/katas
haskell/sort/heap-sort/heap-sort.hs
unlicense
1,109
0
11
296
436
214
222
21
4
module Ch16 where import Test.HUnit (Counts, Test (TestList), runTestTT) import qualified Test.HUnit.Util as U (t) ------------------------------------------------------------------------------ -- ch 16 {- 2nd : composition of two functors which are related via an adjoint relation - e.g., newtype State s a = State { runState :: s -> (a, s) } - instead of monolithic block, see State as composition of - functor (, s) : pairs any value a with an output value of type s - functor (s ->) : adds an input of type s - since two functors are adjoint, their composition is a monad adjointness : topic of Chapter 18 - introduce notion decoupled from monads - then describe construction which builds monad out of adjunction - then comonads : also built from an adjunction by similar mechanism Part IV : concept of free monad : build a monad "for free" - can sharpen concept via adjoint functor - construction of free monad is adjoint to forgetful functor Category Theory for Programmers [Milewski, 2014] Categories for the Working Mathematician [Mac Lane, 1998] Category Theory in Context [Riehl, 2016] -} ts16 :: [Test] ts16 = U.t "t05" 'a' 'a' ------------------------------------------------------------------------------ t16 :: IO Counts t16 = runTestTT $ TestList {-$-} ts16
haroldcarr/learn-haskell-coq-ml-etc
haskell/topic/category-theory/alejandro-serrano-bom/src/Ch16.hs
unlicense
1,305
0
6
235
85
53
32
9
1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# OPTIONS_HADDOCK hide #-} -- | -- Module : DNA.Logging -- Copyright : (C) 2014-2015 Braam Research, LLC. -- License : Apache-2.0 -- -- Logging and profiling facilities. Log messages are written to GHC's -- eventlog in the following format: -- -- > TAG [ATTR]* message -- -- The tag is a sequence of alphanumeric characters, usually in all -- caps. The tag can be: -- -- * MSG: for simple log messages -- * PANIC: internal error. Should only be triggered by implementation bug -- * FATAL: fatal error from which actor could not recover -- * ERROR: ordinary error -- * DEBUG: debug messages -- * SYNC: for synchronising time between nodes -- * START x/END x: sample of a performance metric (for profiling) -- -- Attributes can be used to add (possibly optional) extra data to the -- message. They are enclosed in square brackets and must precede the -- message. Possible attributes are -- -- * [pid=PID]: for the Cloud Haskell process ID. For messages -- concerning the whole program, this may not be set. -- -- * [SAMPLER:METRIC=VAL/TIME]: records the value of a performance -- metric. When a time is given, it is the time that the counter -- has been running. -- -- * [hint:METRIC=VAL]: A performance hint by the program, such as -- expected number of floating point operations. module DNA.Logging ( -- * Options and basic API MonadLog(..) , LoggerOpt(..) , DebugPrint(..) , initLogging , processAttributes -- * Logging API , taggedMessage , eventMessage , message -- ** Actor operations , logSpawn , logConnect -- ** Error logging , panicMsg , fatalMsg , errorMsg , warningMsg , debugMsg -- * Profiling API , synchronizationPoint , logDuration , logProfile -- * Profiling hints , ProfileHint(..) , floatHint, memHint, ioHint, haskellHint, cudaHint ) where import Control.Concurrent import Control.Distributed.Process (getSelfPid,Process,ProcessId) import Control.Exception (evaluate) import Control.Monad import Control.Monad.IO.Class import Control.Monad.Except (ExceptT) import Control.Monad.Trans.Class import Data.Time import Data.Maybe (fromMaybe) import Data.IORef import Data.Tuple (swap) import Data.Typeable (Typeable) import Data.List (unfoldr) import Data.Binary (Binary) import qualified Data.Map.Strict as Map import Data.Word (Word64) import GHC.Stats import GHC.Generics (Generic) import Debug.Trace (traceEventIO) #ifdef USE_CUDA import Profiling.CUDA.Activity import Profiling.CUDA.Metrics #endif import Profiling.Linux.Perf.Stat import System.IO import System.IO.Unsafe (unsafePerformIO) import System.Mem (performGC) import DNA.Types (AID,VirtualCAD) ---------------------------------------------------------------- -- Basic logging API ---------------------------------------------------------------- -- | Type class for monad from which we can write messages to the -- log. This API only covers getting current settings and doesn't -- describe how to change them. Note than not all monads support -- changing settings class MonadIO m => MonadLog m where -- | Who created log message. It could be process ID, actor name etc. logSource :: m String -- | Logger options -- -- Verbosity of logging: -- -- * -2 - only fatal errors logged -- * -1 - error and more severe events logged -- * 0 - warnings and more severe events logged -- * 1 - everything is logged logLoggerOpt :: m LoggerOpt instance MonadLog Process where logSource = show <$> getSelfPid logLoggerOpt = return $ LoggerOpt 0 NoDebugPrint "" instance MonadLog m => MonadLog (ExceptT e m) where logSource = lift logSource logLoggerOpt = lift logLoggerOpt -- | Is debug printing enabled data DebugPrint = NoDebugPrint -- ^ Debug printing disabled (default). | DebugPrintEnabled -- ^ Debug printing enabled but will NOT be inherited by child processes | DebugPrintInherited -- ^ Debug printing enabled but will be inherited by child processes deriving (Show,Eq,Typeable,Generic) instance Binary DebugPrint -- | Modes of operation for the logger. Most additional attributes -- cost performance, therefore default state is to run without any of -- these modifiers. data LoggerOpt = LoggerOpt { logOptVerbose :: Int -- ^ The higher, the more additional information we output about -- what we are doing. , logOptDebugPrint :: DebugPrint -- ^ Whether debug printing is enabled , logOptMeasure :: String -- ^ Gather detailed statistics about the given group of -- performance metrics, at the possible expense of performance. } deriving (Show,Typeable,Generic) instance Binary LoggerOpt -- Sequence number for splitting messages when writing them to -- eventlog. We need global per-program supply of unique numbers. loggerMsgId :: IORef Int loggerMsgId = unsafePerformIO $ newIORef 0 {-# NOINLINE loggerMsgId #-} loggerFloatCounters :: IORef (Map.Map ThreadId PerfStatGroup) loggerFloatCounters = unsafePerformIO $ newIORef Map.empty {-# NOINLINE loggerFloatCounters #-} loggerCacheCounters :: IORef (Map.Map ThreadId PerfStatGroup) loggerCacheCounters = unsafePerformIO $ newIORef Map.empty {-# NOINLINE loggerCacheCounters #-} #ifdef USE_CUDA -- Whether CUDA CUPTI is enabled loggerCuptiEnabled :: MVar Bool loggerCuptiEnabled = unsafePerformIO $ newMVar False {-# NOINLINE loggerCuptiEnabled #-} #endif -- | Initialise logging facilities. This must be called once at -- program start, before the first messages are being created. initLogging :: LoggerOpt -> IO () initLogging _opt = do -- Initialise profiling sub-modules #ifdef USE_CUDA cudaInit _opt #endif -- Set console output to be line-buffered. We want it for -- diagnostics, no reason to buffer. hSetBuffering stdout LineBuffering hSetBuffering stderr LineBuffering -- Should be default ---------------------------------------------------------------- -- Primitives for logging ---------------------------------------------------------------- type Attr = (String, String) -- | Generate the specified eventlog message rawMessage :: String -- ^ Message tag -> [Attr] -- ^ Message attributes -> String -- ^ Message body -> Bool -- ^ If True then message is written to stdout too -> IO () rawMessage tag attrs msg logStdout = do -- Make message text let formatAttr (attr, val) = ' ':'[':attr ++ '=': val ++ "]" text = concat (tag : map formatAttr attrs) ++ ' ':msg -- Check whether it's too long for the RTS to output in one -- piece. This is rare, but we don't want to lose information. when logStdout $ putStrLn text let splitThreshold = 512 if length text < splitThreshold then traceEventIO text else do -- Determine marker. We need this because the message chunks -- might get split up. msgId <- atomicModifyIORef' loggerMsgId (\x -> (x+1,x)) let mark = "[[" ++ show msgId ++ "]]" -- Now split message up and output it. Every message but the -- last gets the continuation marker at the end, and every -- message but the first is a continuation. let split "" = Nothing split str = Just $ splitAt (splitThreshold - 20) str pieces = unfoldr split text start = head pieces; (mid, end:_) = splitAt (length pieces-2) (tail pieces) traceEventIO (start ++ mark) forM_ mid $ \m -> traceEventIO (mark ++ m ++ mark) traceEventIO (mark ++ end) -- | Generate identification attributes it uses 'logSource' method for -- getting name of PID processAttributes :: MonadLog m => m [Attr] processAttributes = do pid <- logSource case pid of "" -> return [] _ -> return [("pid", pid)] ---------------------------------------------------------------- -- Logging API ---------------------------------------------------------------- -- | Output a custom-tag process message into the eventlog. taggedMessage :: MonadLog m => String -- ^ Message tag -> String -- ^ Message -> m () taggedMessage tag msg = do attrs <- processAttributes liftIO $ rawMessage tag attrs msg True -- | Put a global message into eventlog, (verbosity = 0). eventMessage :: MonadLog m => String -> m () eventMessage = message 0 -- | Put a message at the given verbosity level message :: MonadLog m => Int -> String -> m () message v msg = do verbosity <- logOptVerbose `liftM` logLoggerOpt attrs <- processAttributes when (verbosity >= v) $ liftIO $ rawMessage "MSG" (("v", show v) : attrs) msg True -- | Log fact that actor with given PID was spawned logSpawn :: MonadLog m => ProcessId -> AID -> VirtualCAD -> m () logSpawn pid aid vcad = do attrs <- processAttributes liftIO $ rawMessage "SPAWN" attrs (show pid ++ " (" ++ show aid ++ ")") False liftIO $ rawMessage "SPAWN" attrs (show vcad) False -- | Log that connection between actor was established. N.B. It means -- that actor now knows where to send data. logConnect :: MonadLog m => Maybe AID -> Maybe AID -> m () logConnect aidSrc aidDst = do attrs <- processAttributes liftIO $ rawMessage "CONNECT" attrs (render aidSrc ++ " -> " ++ render aidDst) False where render = maybe "-" show ---------------------------------------------------------------- -- API for logging ---------------------------------------------------------------- -- | Put message into event log that panic occured. panicMsg :: MonadLog m => String -> m () panicMsg msg = do attrs <- processAttributes liftIO $ rawMessage "PANIC" attrs msg True -- | Put message into log about fatal error fatalMsg :: MonadLog m => String -> m () fatalMsg msg = do verbosity <- logOptVerbose `liftM` logLoggerOpt when (verbosity >= -2) $ do attrs <- processAttributes liftIO $ rawMessage "FATAL" attrs msg True -- | Put message into log about fatal error errorMsg :: MonadLog m => String -> m () errorMsg msg = do verbosity <- logOptVerbose `liftM` logLoggerOpt when (verbosity >= -1) $ do attrs <- processAttributes liftIO $ rawMessage "ERROR" attrs msg True -- | Put a warning message. Warnings have a verbosity of 0. warningMsg :: MonadLog m => String -> m () warningMsg msg = do verbosity <- logOptVerbose `liftM` logLoggerOpt when (verbosity >= -2) $ do attrs <- processAttributes liftIO $ rawMessage "WARNING" attrs msg True -- | Put a debug message debugMsg :: MonadLog m => String -> m () debugMsg msg = do debugEnabled <- logOptDebugPrint `liftM` logLoggerOpt case debugEnabled of NoDebugPrint -> return () _ -> do attrs <- processAttributes liftIO $ rawMessage "DEBUG" attrs msg True -- | Synchronize timings - put into eventlog an event with current wall time. synchronizationPoint :: MonadIO m => String -> m () synchronizationPoint msg = liftIO $ do utcTime <- getCurrentTime -- we are formatting time to number of seconds in POSIX epoch and -- fractional part in picoseconds. let timeString = formatTime defaultTimeLocale "%s.%q" utcTime humanReadable = formatTime defaultTimeLocale "%F %X" utcTime rawMessage "SYNC" [("time", timeString)] msg False rawMessage "MSG" [] ("started at " ++ humanReadable) False ---------------------------------------------------------------- -- Profiling basics ---------------------------------------------------------------- data SamplePoint = StartSample | EndSample -- | Put measurements about execution time of monadic action into -- eventlog. Result of action is evaluated to WHNF. measurement :: MonadIO m => (SamplePoint -> m [Attr]) -- ^ Measurements, might add extra attributes -> String -- ^ Message -> [Attr] -- ^ Attributes -> m a -- ^ DNA action to profile -> m a measurement sample msg attrs dna = do -- Get start sample sample0 <- sample StartSample liftIO $ rawMessage "START" (attrs ++ sample0) msg False -- Perform action r <- liftIO . evaluate =<< dna -- Get end sample, return sample1 <- sample EndSample liftIO $ rawMessage "END" (attrs ++ sample1) msg False return r -- | Put measurements about execution time of monadic action into -- eventlog. Result of action is evaluated to WHNF. logDuration :: MonadLog m => String -> m a -> m a logDuration msg dna = do attrs <- processAttributes let sample _ = return [] -- measurement is implicit from START/END timestamp measurement sample msg attrs dna ---------------------------------------------------------------- -- Profiling ---------------------------------------------------------------- -- | A program annotation providing additional information about how -- much work we expect the program to be doing in a certain phase. The -- purpose of this hint is that we can set-up measurements to match -- these numbers to the program's real performance. Note that the -- hint must only be a best-effort estimate. As a rule of thumb, it is -- better to use a more conservative estimate, as this will generally -- result in lower performance estimates. These hints are passed to -- 'DNA.kernel' or 'DNA.unboundKernel'. -- -- Hints should preferably be constructed using the default -- constructors: 'floatHint', 'memHint', 'ioHint', 'haskellHint' and -- 'cudaHint'. See their definitions for examples. data ProfileHint = FloatHint { hintFloatOps :: !Int , hintDoubleOps :: !Int } -- ^ Estimate for how many floating point operations the code is -- executing. Profiling will use @perf_event@ in order to take -- measurements. Keep in mind that this has double-counting -- issues (20%-40% are not uncommon for SSE or AVX code). | MemHint { hintMemoryReadBytes :: !Int } -- ^ Estimate for the amount of data that will have to be read -- from RAM over the course of the kernel calculation. | IOHint { hintReadBytes :: !Int , hintWriteBytes :: !Int } -- ^ Estimate for how much data the program is reading or -- writing from/to external sources. | HaskellHint { hintAllocation :: !Int } -- ^ Rough estimate for how much Haskell work we are doing | CUDAHint { hintCopyBytesHost :: !Int , hintCopyBytesDevice :: !Int , hintCudaFloatOps :: !Int , hintCudaDoubleOps :: !Int } -- ^ CUDA statistics. The values are hints about how much data -- transfers we expect to be targetting the device and the host -- respectively. -- -- The FLOP hints will only be checked if logging is running in -- either @"float-ops"@ or @"double-ops"@ mode, -- respectively. Note that this requires instrumentation, which -- will reduce overall performance! deriving (Show,Eq) -- | Default constructor for 'FloatHint' with hint 0 for all -- metrics. Can be used for requesting FLOP profiling. Hints can be -- added by overwriting fields values. -- -- For example, we can use this 'ProfileHint' to declare the amount of -- floating point operations involved in computing a sum: -- -- > kernel "compute sum" [floatHint{hintDoubleOps = fromIntegral (2*n)} ] $ -- > return $ (S.sum $ S.zipWith (*) va vb :: Double) floatHint :: ProfileHint floatHint = FloatHint 0 0 -- | Default constructor for 'MemHint' with hint 0 for all -- metrics. Can be used for requesting memory bandwidth profiling. -- Hints can be added by overwriting field values. -- -- This could be used to track the bandwidth involved in copying a -- large buffer: -- -- > let size = Vec.length in * sizeOf (Vec.head in) -- > kernel "copy buffer" [memHint{hintMemoryReadBytes=size}] $ liftIO $ -- > VecMut.copy in out memHint :: ProfileHint memHint = MemHint 0 -- | Default constructor for 'IOHint' with hint 0 for all -- metrics. Can be used for requesting I/O bandwidth profiling. Hints -- can be added by overwriting field values. -- -- This can be used to document the amount of data that we expect to -- read from a hard drive: -- -- > kernel "read vector" [iOHint{hintReadBytes = fromIntegral (n * 8)}] $ -- > liftIO $ readData n off fname ioHint :: ProfileHint ioHint = IOHint 0 0 -- | Default constructor for 'IOHint' with hint 0 for all -- metrics. Can be used for requesting Haskell allocation -- profiling. Hints can be added by overwriting field values. -- -- Useful for tracking the amount of allocation Haskell does in a -- certain computation. This can often be a good indicator for whether -- it has been compiled in an efficient way. -- -- > unboundKernel "generate vector" [HaskellHint (fromIntegral $ n * 8)] $ -- > liftIO $ withFileChan out "data" WriteMode $ \h -> -- > BS.hPut h $ runPut $ -- > replicateM_ (fromIntegral n) $ putFloat64le 0.1 -- -- For example, this 'HaskellHint' specifies that Haskell is allowed -- to only heap-allocate one 'Double'-object per value written. haskellHint :: ProfileHint haskellHint = HaskellHint 0 -- | Default constructor for 'CUDAHint' with hint 0 for all -- metrics. Can be used for requesting Haskell allocation -- profiling. Hints can be added by overwriting field values. -- -- For instance, we could wrap an @accelerate@ computation as follows: -- -- > let size = S.length va -- > kernel "accelerate dot product" [cudaHint{hintCudaDoubleOps=size*2}] $ liftIO $ do -- > let sh = S.length va -- > va' = A.fromVectors (A.Z A.:. size) ((), va) :: A.Vector Double -- > vb' = A.fromVectors (A.Z A.:. size) ((), vb) :: A.Vector Double -- > return $ head $ A.toList $ CUDA.run $ -- > A.fold (+) 0 $ A.zipWith (*) (A.use va') (A.use vb') cudaHint :: ProfileHint cudaHint = CUDAHint 0 0 0 0 -- | Main profiling function. The concrete information output to the -- event log depends on the hints about the code's actions. -- -- Generally, the more hints we have about the code's actions, the -- better. However, also note that more hints generally means that we -- are going to safe more information, so keep in mind that every hint -- means a certain (constant) profiling overhead. logProfile :: (Functor m, MonadLog m) => String -- ^ Message. Will be used in profile view -- to identify costs, so short and -- recognisable names are preferred. -> [ProfileHint] -- ^ Hints about the code's complexity. -> [Attr] -- ^ Extra attributes to add to profile messages -> m a -- ^ The code to profile -> m a logProfile msg hints attrs = measurement sample msg attrs where sample pt = concat `liftM` mapM (hintToSample pt) hints -- | Takes a sample according to the given hint hintToSample :: (Functor m, MonadLog m) => SamplePoint -> ProfileHint -> m [Attr] hintToSample pt fh@FloatHint{} = consHint pt "hint:float-ops" (hintFloatOps fh) . consHint pt "hint:double-ops" (hintDoubleOps fh) <$> floatCounterAttrs pt hintToSample pt fh@MemHint{} = consHint pt "hint:mem-read-bytes" (hintMemoryReadBytes fh) <$> cacheCounterAttrs pt hintToSample pt ioh@IOHint{} = consHint pt "hint:read-bytes" (hintReadBytes ioh) . consHint pt "hint:write-bytes" (hintWriteBytes ioh) <$> ioAttrs hintToSample pt hh@HaskellHint{} = consHint pt "hint:haskell-alloc" (hintAllocation hh) <$> haskellAttrs hintToSample pt ch@CUDAHint{} = consHint pt "hint:memcpy-bytes-host" (hintCopyBytesHost ch) . consHint pt "hint:memcpy-bytes-device" (hintCopyBytesDevice ch) . consHint pt "hint:gpu-float-ops" (hintCudaFloatOps ch) . consHint pt "hint:gpu-double-ops" (hintCudaDoubleOps ch) <$> cudaAttrs pt -- | Prepend an attribute if this is the start point, and it is non-zero consHint :: (Eq a, Num a, Show a) => SamplePoint -> String -> a -> [Attr] -> [Attr] consHint EndSample _ _ = id consHint _ _ 0 = id consHint StartSample n v = ((n, show v):) #ifdef CUDA -- | Prepend an attribute if it is non-zero consAttrNZ :: (Eq a, Num a, Show a) => String -> a -> [Attr] -> [Attr] consAttrNZ _ 0 = id consAttrNZ n v = ((n, show v):) -- | As @consAttrNZ@, but with reference time consAttrNZT :: (Eq a, Num a, Show a) => String -> a -> a -> [Attr] -> [Attr] consAttrNZT _ 0 _ = id consAttrNZT n v t = ((n, show v ++ "/" ++ show t):) #endif ---------------------------------------------------------------- -- perf_events sampling ---------------------------------------------------------------- -- | De/initialise perf_events. We re-initialise them for every single -- kernel call for now - this is probably wasteful, as the RTS -- ought to be reusing bound threads at some level. Still, I can't -- think of a good solution to make sure that perf_events handles -- wouldn't leak, so let's do this for now. samplePerfEvents :: MonadLog m => IORef (Map.Map ThreadId PerfStatGroup) -> [PerfStatDesc] -> SamplePoint -> m [PerfStatCount] samplePerfEvents countersVar countersDesc StartSample = do -- Check that the thread is actually bound isBound <- liftIO $ isCurrentThreadBound when (not isBound) $ warningMsg "perf_events not running in bound thread!" liftIO $ do -- Open the counters counters <- perfEventOpen countersDesc -- Store them as thread-local state tid <- myThreadId atomicModifyIORef' countersVar $ flip (,) () . Map.insert tid counters -- Read values, then enable vals <- perfEventRead counters perfEventEnable counters return vals samplePerfEvents countersVar _ EndSample = liftIO $ do tid <- myThreadId Just counters <- atomicModifyIORef' countersVar $ swap . Map.updateLookupWithKey (\_ _ -> Nothing) tid -- Take end sample, close counters vals <- perfEventRead counters perfEventDisable counters perfEventClose counters return vals -- | Format perf_events counter value for output. We "normalise" the -- counter values if they have not been running for the full time they -- have been enabled. This happens due to the kernel multiplexing the -- counters. -- -- Note that we lose some accuracy in the process, at some point it -- might be worthwhile to document this in the profile as well. formatPerfStat :: Word64 -> PerfStatCount -> String formatPerfStat _ (PerfStatCount _ _ _ 0) = "" formatPerfStat multi (PerfStatCount _ val enabled running) = let f = 4096 -- overflow-save up to about 1250 hours normalised = val * (enabled * f `div` running) `div` f in show (multi * normalised) ++ "/" ++ show enabled -- | The floating point counters, with associated names floatCounterDescs :: [(String, PerfStatDesc)] floatCounterDescs = [ ("cpu-cycles", PerfDesc $ PERF_TYPE_HARDWARE PERF_COUNT_HW_CPU_CYCLES) , ("cpu-instructions", PerfDesc $ PERF_TYPE_HARDWARE PERF_COUNT_HW_INSTRUCTIONS) , ("x87-ops", PfmDesc "FP_COMP_OPS_EXE:X87") , ("scalar-float-ops", PfmDesc "FP_COMP_OPS_EXE:SSE_FP_SCALAR_SINGLE") , ("scalar-double-ops", PfmDesc "FP_COMP_OPS_EXE:SSE_SCALAR_DOUBLE") , ("sse-float-ops", PfmDesc "FP_COMP_OPS_EXE:SSE_PACKED_SINGLE") , ("sse-double-ops", PfmDesc "FP_COMP_OPS_EXE:SSE_FP_PACKED_DOUBLE") , ("avx-float-ops", PfmDesc "SIMD_FP_256:PACKED_SINGLE") , ("avx-double-ops", PfmDesc "SIMD_FP_256:PACKED_DOUBLE") ] -- | Generate message attributes from current floating point counter values floatCounterAttrs :: MonadLog m => SamplePoint -> m [Attr] floatCounterAttrs pt = do -- Get counters from perf_event vals <- samplePerfEvents loggerFloatCounters (map snd floatCounterDescs) pt -- Generate attributes let fmtName (name, _) = "perf:" ++ name return $ filter (not . null . snd) $ zip (map fmtName floatCounterDescs) (map (formatPerfStat 1) vals) -- | The floating point counters, with associated names cacheCounterDescs :: [(String, PerfStatDesc)] cacheCounterDescs = [ ("mem-read-bytes", PfmDesc "OFFCORE_RESPONSE_0:ANY_DATA:LLC_MISS_LOCAL") ] -- | Generate message attributes from current cache performance counter values cacheCounterAttrs :: MonadLog m => SamplePoint -> m [Attr] cacheCounterAttrs pt = do -- Get counters from perf_event vals <- samplePerfEvents loggerCacheCounters (map snd cacheCounterDescs) pt -- Constant enough to hard-code it, I think. let cacheLine = 32 -- Generate attributes let fmtName (name, _) = "perf:" ++ name return $ filter (not . null . snd) $ zip (map fmtName cacheCounterDescs) (map (formatPerfStat cacheLine) vals) ---------------------------------------------------------------- -- I/O data sampling ---------------------------------------------------------------- -- | Generate message attributes for procces I/O statistics ioAttrs :: MonadLog m => m [Attr] ioAttrs = liftIO $ do -- Read /proc/self/io - not the full story by any means, especially -- when consindering mmap I/O (TODO!), but it's easy. ios <- map (break (==':')) . lines <$> readFile "/proc/self/io" let io name = drop 2 $ fromMaybe "" $ lookup name ios return [ ("proc:read-bytes", io "read_bytes") , ("proc:write-bytes", io "write_bytes") ] ---------------------------------------------------------------- -- Haskell RTS sampling ---------------------------------------------------------------- -- | Generate message attributes for procces I/O statistics haskellAttrs :: MonadLog m => m [Attr] haskellAttrs = liftIO $ do -- This might be slightly controversial: This forces a GC so we get -- statistics about the *true* memory residency. performGC -- Now get statistics available <- getGCStatsEnabled if not available then return [] else do stats <- getGCStats return [ ("rts:haskell-alloc", show $ bytesAllocated stats) , ("rts:gc-bytes-copied", show $ bytesCopied stats) , ("rts:mut-time", show $ mutatorCpuSeconds stats) , ("rts:gc-time", show $ gcCpuSeconds stats) , ("rts:heap-size", show $ currentBytesUsed stats) ] ---------------------------------------------------------------- -- CUDA statistics sampling ---------------------------------------------------------------- #ifdef USE_CUDA -- | CUPTI metrics to use depending on configuration. Returns a table -- relating metrics to output attribute names. cudaMetricNames :: LoggerOpt -> [(String, String)] cudaMetricNames opt = case logOptMeasure opt of "fp-inst" -> [ ("cuda:gpu-double-instrs", "inst_fp_32") , ("cuda:gpu-float-instrs", "inst_fp_64") ] "float-ops" -> [ ("cuda:gpu-float-ops", "flop_count_sp") , ("cuda:gpu-float-ops-add", "flop_count_sp_add") , ("cuda:gpu-float-ops-mul", "flop_count_sp_mul") , ("cuda:gpu-float-ops-fma", "flop_count_sp_fma") ] "double-ops" -> [ ("cuda:gpu-double-ops", "flop_count_dp") , ("cuda:gpu-double-ops-add", "flop_count_dp_add") , ("cuda:gpu-double-ops-mul", "flop_count_dp_mul") , ("cuda:gpu-double-ops-fma", "flop_count_dp_fma") ] _other -> [ ] cudaInit :: LoggerOpt -> IO () cudaInit opt = do when (logOptMeasure opt `elem` ["help", "list"]) $ putStrLn "Supported metric groups: fp-inst, float-ops, double-ops" cuptiMetricsInit $ map snd $ cudaMetricNames opt cudaAttrs :: MonadLog m => SamplePoint -> m [Attr] cudaAttrs pt = do -- Get metrics state <- logLoggerOpt let metricNames = map fst $ cudaMetricNames state -- Enable CUPTI if required case pt of StartSample -> liftIO $ modifyMVar_ loggerCuptiEnabled $ \f -> do unless f $ do cuptiEnable when (not $ null metricNames) cuptiMetricsEnable return True EndSample -> liftIO $ modifyMVar_ loggerCuptiEnabled $ \f -> do when f $ do cuptiDisable when (not $ null metricNames) cuptiMetricsDisable return False liftIO $ do -- Flush, so statistics are current cuptiFlush -- Then read stats memsetTime <- cuptiGetMemsetTime kernelTime <- cuptiGetKernelTime overheadTime <- cuptiGetOverheadTime memsetBytes <- cuptiGetMemsetBytes memcpyTimeH <- cuptiGetMemcpyTimeTo CUptiHost memcpyTimeD <- (+) <$> cuptiGetMemcpyTimeTo CUptiDevice <*> cuptiGetMemcpyTimeTo CUptiArray memcpyBytesH <- cuptiGetMemcpyBytesTo CUptiHost memcpyBytesD <- (+) <$> cuptiGetMemcpyBytesTo CUptiDevice <*> cuptiGetMemcpyBytesTo CUptiArray -- Read metrics metrics <- cuptiGetMetrics let formatMetric m = show m ++ "/" ++ show kernelTime metricAttrs = zipWith (,) metricNames (map formatMetric metrics) -- Generate attributes return $ consAttrNZ "cuda:kernel-time" kernelTime $ consAttrNZ "cuda:overhead-time" overheadTime $ consAttrNZT "cuda:memset-bytes" memsetBytes memsetTime $ consAttrNZT "cuda:memcpy-bytes-host" memcpyBytesH memcpyTimeH $ consAttrNZT "cuda:memcpy-bytes-device" memcpyBytesD memcpyTimeD $ metricAttrs #else cudaAttrs :: MonadLog m => SamplePoint -> m [Attr] cudaAttrs _ = return [] #endif
SKA-ScienceDataProcessor/RC
MS5/dna/core/DNA/Logging.hs
apache-2.0
30,115
0
20
7,004
5,052
2,710
2,342
343
3
{-# LANGUAGE OverloadedStrings #-} module Main where import Prelude hiding (foldr) import Control.Concurrent.STM (atomically) import Control.Monad (void) import Control.Monad.Trans.Resource import Data.ByteString (ByteString) import Data.Conduit import Data.Conduit.Process (sourceCmd) import Data.Conduit.TMChan import Data.Foldable (foldr) import Options.Applicative import qualified Data.Conduit.Combinators as Conduit import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC type UName = String type Cmds = String type HostName = String type SSHOpt = String data Options = Opts (Maybe UName) [SSHOpt] Cmds [HostName] deriving Show options :: Parser Options options = Opts <$> optional (strOption ( long "login" <> short 'l' <> metavar "USERNAME" <> help "Username for ssh")) <*> liftA2 (++) (flag [] disableKeyCheck ( long "no-strict-key-check" <> short 'S' <> help "Disable strict host key checking" )) (many (strOption ( long "ssh-opts" <> metavar "OPTS" <> help "Arbitrary options to pass through to ssh" ))) <*> argument str (metavar "COMMAND") <*> some (argument str $ metavar "HOSTS...") disableKeyCheck :: [SSHOpt] disableKeyCheck = ["-o", "StrictHostKeyChecking=no"] data OutputLine = Ln HostName ByteString ssh :: Maybe UName -> HostName -> Cmds -> [SSHOpt] -> Source (ResourceT IO) ByteString ssh user host cmd opts = sourceCmd (unwords args) where args = ["ssh", "-T"] ++ opts ++ [foldr prependUser host user, cmd] prependUser u h = u ++ "@" ++ h ssh' :: Maybe UName -> HostName -> Cmds -> [SSHOpt] -> Source (ResourceT IO) OutputLine ssh' user host cmd opts = ssh user host cmd opts $= Conduit.map (Ln host) dispLine :: Monad m => Conduit OutputLine m ByteString dispLine = Conduit.map $ \(Ln h l) -> "[" <> BSC.pack h <> "] " <> l main :: IO () main = do Opts u os c hs <- execParser $ info (helper <*> options) fullDesc chan <- atomically $ newTBMChan 16 let sources = map (\h -> ssh' u h c os) hs runResourceT $ do merged <- mergeSources sources 16 void . resourceForkIO $ merged $$ dispLine =$ sinkTBMChan chan True sourceTBMChan chan $$ Conduit.stdout
bmjames/xssh-conduit
xssh-conduit.hs
apache-2.0
2,474
0
16
699
760
399
361
64
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE PackageImports #-} module Network ( N.HostName , N.PortNumber , N.PortID(..) , connectTo , withSocketsDo ) where import qualified "network" Network as N import System.Mock.IO.Internal
3of8/mockio
New_Network.hs
bsd-2-clause
230
0
5
34
47
33
14
10
0
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {- NOTES: stackexchange API spec and its document just sucks! -} module IDP.StackExchange where import Control.Monad.Trans.Except import Data.Aeson import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy.Char8 as BSL import Data.Default import qualified Data.Set as Set import Data.Text.Lazy (Text) import qualified Data.Text.Lazy as TL import GHC.Generics import Lens.Micro import Network.HTTP.Conduit import Network.OAuth.OAuth2 import Types import URI.ByteString import URI.ByteString.QQ -- fix key from your application edit page -- https://stackapps.com/apps/oauth stackexchangeAppKey :: ByteString stackexchangeAppKey = "" data StackExchange = StackExchange deriving (Eq, Show) type instance IDPUserInfo StackExchange = StackExchangeResp type instance IDPName StackExchange = StackExchange stackexchangeIdp :: IDP StackExchange stackexchangeIdp = def { idpName = StackExchange, oauth2Config = stackexchangeKey, oauth2FetchAccessToken = fetchAccessTokenInternal ClientSecretPost, oauth2RefreshAccessToken = refreshAccessTokenInternal ClientSecretPost, convertUserInfoToLoginUser = toLoginUser, oauth2FetchUserInfo = fetchUserInfo, -- -- Only StackExchange has such specical app key which has to be append in userinfo uri. -- I feel it's not worth to invent a way to read from config -- file which would break the generic of IDP data type. -- Until discover a easier way, hard code for now. -- oauth2UserInfoUri = appendStackExchangeAppKey [uri|https://api.stackexchange.com/2.2/me?site=stackoverflow|] stackexchangeAppKey } fetchUserInfo :: FromJSON b => IDP a -> Manager -> AccessToken -> ExceptT BSL.ByteString IO b fetchUserInfo IDP {..} mgr accessToken = authGetJSONInternal (Set.fromList [AuthInRequestQuery]) mgr accessToken oauth2UserInfoUri stackexchangeKey :: OAuth2 stackexchangeKey = def { oauth2AuthorizeEndpoint = [uri|https://stackexchange.com/oauth|], oauth2TokenEndpoint = [uri|https://stackexchange.com/oauth/access_token|] } data StackExchangeResp = StackExchangeResp { hasMore :: Bool, quotaMax :: Integer, quotaRemaining :: Integer, items :: [StackExchangeUser] } deriving (Show, Generic) data StackExchangeUser = StackExchangeUser { userId :: Integer, displayName :: Text, profileImage :: Text } deriving (Show, Generic) instance FromJSON StackExchangeResp where parseJSON = genericParseJSON defaultOptions {fieldLabelModifier = camelTo2 '_'} instance FromJSON StackExchangeUser where parseJSON = genericParseJSON defaultOptions {fieldLabelModifier = camelTo2 '_'} toLoginUser :: StackExchangeResp -> LoginUser toLoginUser StackExchangeResp {..} = case items of [] -> LoginUser {loginUserName = TL.pack "Cannot find stackexchange user"} (user : _) -> LoginUser {loginUserName = displayName user} appendStackExchangeAppKey :: URI -> ByteString -> URI appendStackExchangeAppKey useruri k = over (queryL . queryPairsL) (\query -> query ++ [("key", k)]) useruri
freizl/hoauth2
hoauth2-example/src/IDP/StackExchange.hs
bsd-3-clause
3,299
0
11
594
616
367
249
83
2
{-# LANGUAGE FlexibleContexts #-} module Text.XML.Monad.Name where import Control.Monad.Error.Class import Control.Monad.Reader.Class import Data.Char import Data.Function import Text.XML.Monad.Core import Text.XML.Monad.Error import qualified Text.XML.Light as L findElementNameG :: (MonadReader L.Element m, MonadError e m, FromXmlError e) => (L.QName -> L.QName -> Bool) -> L.QName -> m L.Element findElementNameG cmp name = asksMaybeXml (XmlElementNotFoundQ name) $ L.filterElementName (cmp name) findElementName :: (MonadReader L.Element m, MonadError e m, FromXmlError e) => L.QName -> m L.Element findElementName = findElementNameG (==) findElementNameU :: (MonadReader L.Element m, MonadError e m, FromXmlError e) => String -> m L.Element findElementNameU = findElementNameG unqualEq . L.unqual findElementNameUI :: (MonadReader L.Element m, MonadError e m, FromXmlError e) => String -> m L.Element findElementNameUI = findElementNameG unqualEqI . L.unqual findElementsNameG :: (MonadReader L.Element m) => (L.QName -> L.QName -> Bool) -> L.QName -> m [L.Element] findElementsNameG cmp name = asks $ L.filterElementsName (cmp name) findElementsName :: (MonadReader L.Element m) => L.QName -> m [L.Element] findElementsName = findElementsNameG (==) findElementsNameU :: (MonadReader L.Element m) => String -> m [L.Element] findElementsNameU = findElementsNameG unqualEq . L.unqual findElementsNameUI :: (MonadReader L.Element m) => String -> m [L.Element] findElementsNameUI = findElementsNameG unqualEqI . L.unqual testElementNameG :: (MonadReader L.Element m, MonadError e m, FromXmlError e) => (L.QName -> L.QName -> Bool) -> L.QName -> m () testElementNameG cmp expectedName = do actualName <- elName case expectedName `cmp` actualName of True -> return () False -> raiseXml (UnexpectedElementNameQ actualName expectedName) testElementName :: (MonadReader L.Element m, MonadError e m, FromXmlError e) => L.QName -> m () testElementName = testElementNameG (==) testElementNameU :: (MonadReader L.Element m, MonadError e m, FromXmlError e) => String -> m () testElementNameU = testElementNameG unqualEq . L.unqual testElementNameUI :: (MonadReader L.Element m, MonadError e m, FromXmlError e) => String -> m () testElementNameUI = testElementNameG unqualEqI . L.unqual unqualEq :: L.QName -> L.QName -> Bool unqualEq = (==) `on` L.qName unqualEqI :: L.QName -> L.QName -> Bool unqualEqI = (==) `on` (map toLower . L.qName)
aristidb/xml-monad
Text/XML/Monad/Name.hs
bsd-3-clause
2,537
0
12
425
878
467
411
41
2
{-| Module : Data.Boltzmann.System.Sampler Description : Sampler utilities for combinatorial systems. Copyright : (c) Maciej Bendkowski, 2017-2021 License : BSD3 Maintainer : maciej.bendkowski@tcs.uj.edu.pl Stability : experimental -} {-# LANGUAGE DeriveGeneric #-} module Data.Boltzmann.System.Sampler ( Structure(..) , sampleStr , sampleStrIO ) where import Control.Monad (guard) import Control.Monad.Trans (lift) import Control.Monad.Trans.Maybe (MaybeT(..), runMaybeT) import Control.Monad.Random (RandomGen(..), Rand, getRandomR, evalRandIO) import GHC.Generics import Data.Aeson import Data.Map ((!)) import qualified Data.Map as M import Data.Boltzmann.System -- | General structure data type. data Structure = Structure { name :: String , nodes :: [Structure] } deriving (Generic, Show) instance ToJSON Structure where toEncoding = genericToEncoding defaultOptions data SamplerS = SamplerS { typeCons :: String -> [(Cons Double, Int)] , typeProb :: String -> Double } -- | Prepares a general, parametrised system for sampling. prepare :: PSystem Double -> SamplerS prepare sys = SamplerS { typeCons = \s -> M.fromList (paramTypesW sys) ! s , typeProb = typeWeight sys } randomP :: RandomGen g => MaybeT (Rand g) Double randomP = lift (getRandomR (0, 1)) -- | Special list structure with auxiliary name. listStr :: [Structure] -> Structure listStr str = Structure {name = "[]", nodes = str} genRandomArgs :: RandomGen g => SamplerS -> Int -> [Arg] -> MaybeT (Rand g) ([Structure], Int) genRandomArgs sys ub (Type t : xs) = do guard (ub > 0) (arg, s) <- genRandomStr' sys t ub (args', ub') <- genRandomArgs sys (ub - s) xs return (arg : args', s + ub') genRandomArgs sys ub (List t : xs) = do guard (ub > 0) (arg, s) <- genRandomStrL sys t ub (args', ub') <- genRandomArgs sys (ub -s) xs return (listStr arg : args', s + ub') genRandomArgs _ _ [] = return ([], 0) choose :: [(Cons Double, Int)] -> Double -> (String, [Arg], Int) choose [(x,w)] _ = (func x, args x, w) choose ((x,w):xs) p | p < weight x = (func x, args x, w) | otherwise = choose xs p choose _ _ = error "I wasn't expecting the Spanish inquisition!" genRandomStr :: RandomGen g => PSystem Double -> String -> Int -> MaybeT (Rand g) (Structure, Int) genRandomStr = genRandomStr' . prepare sampleStr :: RandomGen g => PSystem Double -> String -> Int -> Int -> Rand g (Structure, Int) sampleStr sys str lb ub = do sample <- runMaybeT (genRandomStr sys str ub) case sample of Nothing -> sampleStr sys str lb ub Just (x, s) -> if lb <= s then return (x, s) else sampleStr sys str lb ub sampleStrIO :: PSystem Double -> String -> Int -> Int -> IO (Structure, Int) sampleStrIO sys str lb ub = evalRandIO $ sampleStr sys str lb ub genRandomStr' :: RandomGen g => SamplerS -> String -> Int -> MaybeT (Rand g) (Structure, Int) genRandomStr' sys str ub = do guard (ub > 0) p <- randomP let opts = typeCons sys str let (constr, args', w) = choose opts p (args'', w') <- genRandomArgs sys (ub - w) args' return (Structure { name = constr , nodes = args''}, w + w') genRandomStrL :: RandomGen g => SamplerS -> String -> Int -> MaybeT (Rand g) ([Structure], Int) genRandomStrL sys str ub = do guard (ub > 0) p <- randomP if p < typeProb sys str then do (x, s) <- genRandomStr' sys str ub (xs, s') <- genRandomStrL sys str (ub - s) return (x : xs, s + s') else return ([], 0)
maciej-bendkowski/boltzmann-brain
Data/Boltzmann/System/Sampler.hs
bsd-3-clause
4,276
0
13
1,522
1,380
733
647
100
3
{-# LANGUAGE OverloadedStrings #-} module IrcScanner.SnapUtil where import Data.Text(append,Text) import Data.ByteString(ByteString) import Control.Monad.Trans.Either (EitherT(..)) import Snap import Snap.Snaplet.Heist import IrcScanner.Types import Control.Monad.Trans (lift) import Control.Monad.Reader(ask,runReaderT) import Control.Monad.IO.Class(liftIO) import Data.IORef(readIORef) import Control.Lens(view) import Data.Text.Encoding(decodeUtf8, encodeUtf8) import Heist(HeistT) getParamET :: Text -> EitherT Text (Handler IrcSnaplet IrcSnaplet) ByteString getParamET p = --undefined lift (getParam $ encodeUtf8 p) >>= doit where doit :: Maybe ByteString -> EitherT Text (Handler IrcSnaplet IrcSnaplet) ByteString doit x = EitherT $ return (maybe (Left $ "'" `append` p `append` "' not specified") Right x) getTextParamOrDefault :: HasHeist x => Text -> Text -> Handler x IrcSnaplet Text getTextParamOrDefault p d = --undefined do maybeText <- (getParam $ encodeUtf8 p) return $ maybe d id (fmap decodeUtf8 maybeText) getTextParam :: HasHeist x => Text -> Handler x IrcSnaplet (Maybe Text) getTextParam p = --undefined do v <- (getParam $ encodeUtf8 p) return $ fmap decodeUtf8 v handleETHandler :: EitherT Text (Handler IrcSnaplet IrcSnaplet) () -> Handler IrcSnaplet IrcSnaplet () handleETHandler et = do lr <- runEitherT et case lr of Left x -> logError $ encodeUtf8 x Right _ -> return () getState :: Handler IrcSnaplet IrcSnaplet IState getState = do s <- (ask :: Handler IrcSnaplet IrcSnaplet IrcSnaplet) liftIO $ readIORef (view (iconfig . cstate) s) --runIST :: SnapletISplice IrcSnaplet runIST :: IST IO x -> HeistT (Handler IrcSnaplet IrcSnaplet) (Handler IrcSnaplet IrcSnaplet) x runIST ist = do s <- ask lift $ liftIO $ runReaderT ist (_iconfig s) runIST' :: IST IO x -> (Handler IrcSnaplet IrcSnaplet) x runIST' ist = do s <- ask liftIO $ runReaderT ist (_iconfig s)
redfish64/IrcScanner
src/IrcScanner/SnapUtil.hs
bsd-3-clause
2,097
0
14
476
691
356
335
58
2
module Tests.Algorithms where import Test.Framework (defaultMain, testGroup) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.QuickCheck import Control.Monad (liftM) import Data.Function (on) import Data.Foldable as F import Data.List as L import Data.IntMap as M hiding ((!)) import Math.LinearAlgebra.Sparse import Tests.Matrix import Tests.Generators testgr_algorithms = testGroup "ALGORITHMS TESTS" [ testProperty "Staircase form" prop_staircase , testProperty "Diagonal form" prop_diagonal --, testProperty "Linear system solution" prop_solve ] -------------------------------------------------------------------------------- -- ALGORITHMS -- ---------------- prop_staircase = forAll (genSize (1,50)) $ \h -> forAll (genSize (1,70)) $ \w -> forAll (genSparseMatrix (h,w) :: Gen (SparseMatrix Integer)) $ \m -> let (s,t) = staircase m -- (sz,en) = (size (mx m), L.sum [ size r | r <- elems (mx m) ]) in -- collect (sz,en,show (en `div` 100)++"%") $ -- (h,w) $ t × m == s prop_diagonal = forAll (genSparseMatrix (30,50) :: Gen (SparseMatrix Integer)) $ \m -> let (d,t,u) = toDiag m (sz,en) = (size (mx m), L.sum [ size r | r <- elems (mx m) ]) in -- collect (sz,en,show (en `div` 100)++"%") $ -- (h,w) $ t × m × (trans u) == d prop_solve = forAll (genSparseMatrix (10,5) :: Gen (SparseMatrix Integer)) $ \m -> forAll (genSparseVector 10 :: Gen (SparseVector Integer)) $ \b -> let x = solveLinear m b in collect (m,b,x) $ case x of Nothing -> True Just x' -> m ×· x' == b --forAll (genSparseVector 5 :: Gen (SparseVector Integer)) $ \x -> -- let b = m ×· x -- x' = solveLinear m b -- in collect (m,x,b) $ -- Just x == solveLinear m b
laughedelic/sparse-lin-alg
Tests/Algorithms.hs
bsd-3-clause
1,911
0
18
506
525
290
235
34
2
{-# LANGUAGE QuasiQuotes #-} import LiquidHaskell [lq| foo :: Fractional a => {v:a | v >= 1.0} |] foo :: Fractional a => a foo = undefined [lq| foo'' :: RealFloat a => {v:a | v >= 1.0} |] foo'' :: RealFloat a => a foo'' = undefined [lq| foo' :: Num a => {v:a | v >= 1} |] foo' :: Num a => a foo' = undefined
spinda/liquidhaskell
tests/gsoc15/unknown/pos/Fractional.hs
bsd-3-clause
316
0
6
77
77
45
32
11
1
{-# LANGUAGE NoMonomorphismRestriction #-} module Lib where import Data.List (elemIndex) import Data.Monoid import Test.QuickCheck import Test.QuickCheck.Checkers import Test.QuickCheck.Classes import Control.Applicative (liftA3) -- 17.5 Applicative in use -- Exercises: Lookups -- 1 added :: Maybe Integer added = (+3) <$> (lookup 3 $ zip [1,2,3] [4,5,6]) -- 2 y :: Maybe Integer y = lookup 3 $ zip [1,2,3] [4,5,6] z :: Maybe Integer z = lookup 2 $ zip [1,2,3] [4,5,6] tuple :: Maybe (Integer, Integer) tuple = (,) <$> y <*> z -- 3 x' :: Maybe Int x' = elemIndex 3 [1..5] y' :: Maybe Int y' = elemIndex 4 [1..5] max' :: Int -> Int -> Int max' = max maxed :: Maybe Int maxed = max' <$> x' <*> y' -- 4 xs = [1,2,3] ys = [4,5,6] x'' :: Maybe Integer x'' = lookup 3 $ zip xs ys y'' :: Maybe Integer y'' = lookup 2 $ zip xs ys -- This is tricky, finally the sum is trying to fold a tuple -- For tuple, just like snd. So the result is Just 5, not Just 11 -- The reason could be found the Chapter of Foldable summed :: Maybe Integer summed = sum <$> ((,) <$> x'' <*> y'') -- Exercise: Identity Instance newtype Identity a = Identity a deriving (Eq, Ord, Show) instance Functor Identity where fmap f (Identity a) = Identity $ f a instance Applicative Identity where pure = Identity (Identity f) <*> (Identity a) = Identity $ f a -- Exercise: Constant Instance newtype Constant a b = Constant { getConstant :: a} deriving (Eq, Ord, Show) instance Functor (Constant a) where fmap _ (Constant a) = Constant a instance Monoid a => Applicative (Constant a) where pure _ = Constant mempty (Constant a1) <*> (Constant a2) = Constant $ a1 <> a2 -- 17.8 ZipList Monoid -- List Applicative Exercise data List a = Nil | Cons a (List a) deriving (Eq, Show) instance Functor List where fmap _ Nil = Nil fmap f (Cons a as) = Cons (f a) (fmap f as) instance Applicative List where pure a = Cons a Nil fs <*> as = flatMap (`fmap` as) fs flatMap :: (a -> List b) -> List a -> List b flatMap _ Nil = Nil flatMap f la = concat' $ fmap f la concat' :: List (List a) -> List a concat' = fold append Nil append :: List a -> List a -> List a append Nil ys = ys append (Cons x xs) ys = Cons x $ xs `append` ys fold :: (a->b->b)->b->List a->b fold _ b Nil = b fold f b (Cons h t) = f h (fold f b t) instance (Eq a) => EqProp (List a) where (=-=) = eq fromList :: [a] -> List a fromList = foldr Cons Nil -- As List is homogeneous with [a] -- Here we construct a [a], then convert to a List. Put a limit of 200 to avoid extremely long list -- Another alternative is using sized from QuickCheck which we will see in future chapters instance (Arbitrary a) => Arbitrary (List a) where arbitrary = fromList . take 200 <$> arbitrary -- ZipList Applicative Exercise newtype ZipList' a = ZipList' (List a) deriving (Eq, Show) instance Functor ZipList' where fmap f (ZipList' xs) = ZipList' $ fmap f xs instance Applicative ZipList' where pure a = ZipList' $ repeat' a _ <*> (ZipList' Nil) = ZipList' Nil (ZipList' Nil) <*> _ = ZipList' Nil (ZipList' (Cons f fs)) <*> (ZipList' (Cons a as)) = ZipList' $ Cons (f a) xs where (ZipList' xs) = ZipList' fs <*> ZipList' as repeat' :: a->List a repeat' a = Cons a (repeat' a) take' :: Int -> List a -> List a take' _ Nil = Nil take' 0 as = Nil take' n (Cons a as) = Cons a $ take' (n-1) as instance Arbitrary a => Arbitrary (ZipList' a) where arbitrary = ZipList' <$> arbitrary instance Eq a => EqProp (ZipList' a) where xs =-= ys = xs' `eq` ys' where xs' = let (ZipList' l) = xs in take' 3000 l ys' = let (ZipList' l) = ys in take' 3000 l -- Exercise: Variations on Either data Validation e a = Failure' e | Success' a deriving (Eq, Show) instance Functor (Validation e) where fmap _ (Failure' e) = Failure' e fmap f (Success' a) = Success' $ f a instance Monoid e => Applicative (Validation e) where pure = Success' (Failure' e1) <*> (Failure' e2) = Failure' $ e1 <> e2 (Failure' e) <*> _ = Failure' e _ <*> (Failure' e) = Failure' e (Success' f) <*> (Success' a) = Success' $ f a instance (Arbitrary e, Arbitrary a) => Arbitrary (Validation e a) where arbitrary = frequency [(1, Failure' <$> arbitrary), (1, Success' <$> arbitrary)] instance (Eq a, Eq e) => EqProp (Validation e a) where (=-=) = eq -- 17.9 Chapter Exercises -- Applicative type verification. Here in REPL, let p1 = .... -- 1 [] p1 = pure :: a -> [] a ap1 = (<*>) :: [] (a -> b) -> [] a -> [] b -- 2 IO p2 = pure :: a -> IO a ap2 = (<*>) :: IO (a -> b) -> IO a -> IO b -- 3 (,) a p3 = pure :: (Monoid a) => b -> (,) a b ap3 = (<*>) :: (Monoid c) => (,) c (a -> b) -> (,) c a -> (,) c b -- 4 (->) e p4 = pure :: a -> (e -> a) ap4 = (<*>) :: (e -> a -> b) -> (e -> a) -> (e -> b) -- Write applicative instance -- 1 Pair data Pair a = Pair a a deriving (Eq, Show) instance Functor Pair where fmap f (Pair a1 a2) = Pair (f a1) (f a2) instance Applicative Pair where pure a = Pair a a (Pair f1 f2) <*> (Pair a1 a2) = Pair (f1 a1) (f2 a2) instance (Arbitrary a) => Arbitrary (Pair a) where arbitrary = Pair <$> arbitrary <*> arbitrary instance (Eq a) => EqProp (Pair a) where (=-=) = eq -- 2 Two data Two a b = Two a b deriving (Eq, Show) instance Functor (Two a) where fmap f (Two a b) = Two a (f b) instance (Monoid a) => Applicative (Two a) where pure = Two mempty (Two a1 f) <*> (Two a2 b) = Two (a1 <> a2) (f b) instance (Arbitrary a, Arbitrary b) => Arbitrary (Two a b) where arbitrary = Two <$> arbitrary <*> arbitrary instance (Eq a, Eq b) => EqProp (Two a b) where (=-=) = eq -- 3 Three data Three a b c = Three a b c deriving (Eq, Show) instance Functor (Three a b) where fmap f (Three a b c) = Three a b (f c) instance (Monoid a, Monoid b) => Applicative (Three a b) where pure = Three mempty mempty (Three a1 b1 f) <*> (Three a2 b2 c) = Three (a1 <> a2) (b1 <> b2) (f c) instance (Arbitrary a, Arbitrary b, Arbitrary c) => Arbitrary (Three a b c) where arbitrary = Three <$> arbitrary <*> arbitrary <*> arbitrary instance (Eq a, Eq b, Eq c) => EqProp (Three a b c) where (=-=) = eq -- 4 Three' data Three' a b = Three' a b b deriving (Eq, Show) instance Functor (Three' a) where fmap f (Three' a b1 b2) = Three' a (f b1) (f b2) instance (Monoid a) => Applicative (Three' a) where pure b = Three' mempty b b (Three' a1 f1 f2) <*> (Three' a2 b1 b2) = Three' (a1 <> a2) (f1 b1) (f2 b2) instance (Arbitrary a, Arbitrary b) => Arbitrary (Three' a b) where arbitrary = Three' <$> arbitrary <*> arbitrary <*> arbitrary instance (Eq a, Eq b) => EqProp (Three' a b) where (=-=) = eq -- 5 Four data Four a b c d = Four a b c d deriving (Eq, Show) instance Functor (Four a b c) where fmap f (Four a b c d) = Four a b c (f d) instance (Monoid a, Monoid b, Monoid c) => Applicative (Four a b c) where pure = Four mempty mempty mempty (Four a1 b1 c1 f) <*> (Four a2 b2 c2 d) = Four (a1 <> a2) (b1 <> b2) (c1 <> c2) (f d) instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d) => Arbitrary (Four a b c d) where arbitrary = Four <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance (Eq a, Eq b, Eq c, Eq d) => EqProp (Four a b c d) where (=-=) = eq -- 6 Four' data Four' a b = Four' a a a b deriving (Eq, Show) instance Functor (Four' a) where fmap f (Four' a1 a2 a3 b) = Four' a1 a2 a3 (f b) instance (Monoid a) => Applicative (Four' a) where pure = Four' mempty mempty mempty (Four' a11 a12 a13 f) <*> (Four' a21 a22 a23 b) = Four' (a11 <> a21) (a12 <> a22) (a13 <> a23) (f b) instance (Arbitrary a, Arbitrary b) => Arbitrary (Four' a b) where arbitrary = Four' <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance (Eq a, Eq b) => EqProp (Four' a b) where (=-=) = eq -- Combinations stops :: String stops = "pbtdkg" vowels :: String vowels = "aeiou" combos :: [a] -> [b] -> [c] -> [(a, b, c)] combos = liftA3 (,,) -- combos stops vowels stops
backofhan/HaskellExercises
CH17/src/Lib.hs
bsd-3-clause
8,089
0
13
1,961
3,756
1,970
1,786
182
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} module PeerTrader.Account.Web where import Control.Concurrent (ThreadId) import Control.Concurrent.STM import Control.Lens import Database.PostgreSQL.Simple.ToField import Database.PostgreSQL.Simple.ToRow import Prosper import PeerTrader.P2PPicks.Account data AccountData = AccountData { _prosperUser :: User , _prosperAccount :: TVar Account , _prosperAccountThread :: Maybe ThreadId , _prosperResponses :: TChan InvestResponse , _p2ppicksAccount :: Maybe P2PPicksAccount } makeLenses ''AccountData instance Show AccountData where show (AccountData ui _ att _ _) = "AccountData " ++ show ui ++ " " ++ show att instance ToRow AccountData where toRow (AccountData { _prosperUser = User {..} }) = [ toField username , toField password ] accountData :: User -> Account -> Maybe P2PPicksAccount -> IO AccountData accountData ui a p2ppicks = do (ta, tr) <- atomically $ do ta <- newTVar a tr <- newTChan return (ta, tr) return $ AccountData ui ta Nothing tr p2ppicks
WraithM/peertrader-backend
src/PeerTrader/Account/Web.hs
bsd-3-clause
1,237
0
12
350
305
162
143
30
1
{-# LANGUAGE OverloadedStrings #-} module Site (app) where import qualified API import qualified Documentation import Application import Data.ByteString (ByteString) import qualified Snap.CORS as CORS import Snap.Snaplet import Snap.Snaplet.Heist import Snap.Util.FileServe routes :: [(ByteString, Handler App App ())] routes = [ ("/static", serveDirectory "static") , ("/", Documentation.index) , ("/try", Documentation.try) , ("/api", Documentation.docs) , ("/languages", Documentation.languages) , ("/api/evaluate", API.evaluate) , ("/api/languages", API.languages) ] app :: SnapletInit App App app = makeSnaplet "app" "An snaplet example application." Nothing $ do h <- nestSnaplet "" heist $ heistInit "templates" -- $ mempty { hcInterpretedSplices = defaultInterpretedSplices } addRoutes routes CORS.wrapCORS return $ App h
eval-so/frontend3
src/Site.hs
bsd-3-clause
926
0
10
197
229
133
96
25
1
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, TypeFamilies #-} -- TODO: ~15 minutes, needs profiling import Control.Monad (forM_, when) import Control.Monad.ST (runST, ST) import Control.Monad.Primitive import qualified Data.Vector.Unboxed as V import qualified Data.Vector.Unboxed.Mutable as MV import qualified Common.DataStructure.Fenwick as F import Common.NumMod.MkNumMod import Prelude hiding (read) mkNumMod True 1000000000000000000 type Zn = Int1000000000000000000 (!) = (V.!) read :: (PrimMonad m, MV.Unbox a) => MV.MVector (PrimState m) a -> Int -> m a read = MV.unsafeRead write :: (PrimMonad m, MV.Unbox a) => MV.MVector (PrimState m) a -> Int -> a -> m () write = MV.unsafeWrite eratos :: Int -> V.Vector Int eratos n = V.create $ do isPrime <- MV.replicate (n + 1) True minPrimePart <- V.thaw $ V.fromList [0 .. n] sumOfDivisors <- MV.replicate (n + 1) 2 write sumOfDivisors 1 1 forM_ [2 .. n] $ \i -> do prime <- read isPrime i when prime $ forM_ [i^2, i^2 + i .. n] $ \j -> do prime' <- read isPrime j when prime' $ do write isPrime j False let q = j `div` i minPrime' <- read minPrimePart q if minPrime' `mod` i == 0 then write minPrimePart j (minPrime' * i) else write minPrimePart j i d1 <- read minPrimePart j when (d1 == j) $ do s <- read sumOfDivisors q write sumOfDivisors j (s + 1) forM_ [2 .. n] $ \i -> do d1 <- read minPrimePart i let d2 = i `div` d1 when (d1 /= i) $ do s1 <- read sumOfDivisors d1 s2 <- read sumOfDivisors d2 write sumOfDivisors i (s1 * s2) return sumOfDivisors buildDT :: Int -> V.Vector Int buildDT n = V.fromList $ map f [0 .. n] where d = eratos (n + 1) f 0 = 0 f i | odd i = (d!i) * (d!((i + 1) `div` 2)) | otherwise = (d!(i `div` 2)) * (d!(i + 1)) solve :: Int -> Zn solve n = runST $ do let dT = buildDT n let maxd = V.maximum dT dp1 <- F.make maxd :: ST s (F.Fenwick (ST s) Zn) dp2 <- F.make maxd dp3 <- F.make maxd V.forM_ (V.drop 1 dT) $ \d -> do F.modify dp1 (+) d 1 F.askLR dp1 (+) (d + 1) maxd >>= F.modify dp2 (+) d F.askLR dp2 (+) (d + 1) maxd >>= F.modify dp3 (+) d F.ask dp3 (+) maxd main = print $ solve 60000000
foreverbell/project-euler-solutions
src/378.hs
bsd-3-clause
2,378
0
24
697
1,077
548
529
65
2
-- | A binary tree for storing quantifiers. module Logic.PrenexTree ( PrenexTree(..) , Type(..) , add , flatten , merge , swapAll , swapWhen ) where -- | Type of a quantifier together with its bound variable. data Type a = F a -- ^ Universal quantifier. | E a -- ^ Existential quantifier. deriving (Eq, Ord, Show) -- | A (quantifier) prenex tree. -- -- Tree node stores whether the quantifiers should be swapped, list of -- quantifiers and two subtrees, which are used for binary logical operators. data PrenexTree a = Nil -- ^ Empty tree. | Node Bool [Type a] (PrenexTree a) (PrenexTree a) -- ^ Tree node. deriving (Eq, Ord, Show) -- | Adds a new quantifier to a prefix tree. add :: Type a -> PrenexTree a -> PrenexTree a add q Nil = Node False [q] Nil Nil add q (Node b qs l r) = Node b (swapWhen b q:qs) l r -- | Swaps one quantifier when the condition holds. When it doesn't, it behaves -- as an 'id'. swapWhen :: Bool -> Type a -> Type a swapWhen p = if p then s else id where s (F x) = E x s (E x) = F x -- | Swaps all quantifiers in a prefix tree. swapAll :: PrenexTree a -> PrenexTree a swapAll Nil = Nil swapAll (Node b qs l r) = Node (not b) qs l r -- | Merges two prefix trees into one. merge :: PrenexTree a -> PrenexTree a -> PrenexTree a merge = Node False [] -- | Flattens a 'PrenexTree' into a list in preorder fashion. Swaps all -- quantifiers according to the 'Bool' flags. flatten :: PrenexTree a -> [Type a] flatten p = go False p [] where go _ Nil = id go q (Node b qs l r) = goL b' qs . go b' l . go b' r where b' = b /= q goL s = flip (foldr ((:) . swapWhen s))
vituscze/logic
src/Logic/PrenexTree.hs
bsd-3-clause
1,800
0
14
553
518
273
245
34
3
{-| Module : Idris.Parser Description : Idris' parser. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE GeneralizedNewtypeDeriving, ConstraintKinds, PatternGuards #-} {-# OPTIONS_GHC -O0 #-} module Idris.Parser(module Idris.Parser, module Idris.Parser.Expr, module Idris.Parser.Data, module Idris.Parser.Helpers, module Idris.Parser.Ops) where import Prelude hiding (pi) import qualified System.Directory as Dir (makeAbsolute) import Text.Trifecta.Delta import Text.Trifecta hiding (span, stringLiteral, charLiteral, natural, symbol, char, string, whiteSpace, Err) import Text.Parser.LookAhead import Text.Parser.Expression import qualified Text.Parser.Token as Tok import qualified Text.Parser.Char as Chr import qualified Text.Parser.Token.Highlight as Hi import Text.PrettyPrint.ANSI.Leijen (Doc, plain) import qualified Text.PrettyPrint.ANSI.Leijen as ANSI import Idris.AbsSyntax hiding (namespace, params) import Idris.DSL import Idris.Imports import Idris.Delaborate import Idris.Error import Idris.Elab.Value import Idris.Elab.Term import Idris.ElabDecls import Idris.Coverage import Idris.IBC import Idris.Unlit import Idris.Providers import Idris.Output import Idris.Parser.Helpers import Idris.Parser.Ops import Idris.Parser.Expr import Idris.Parser.Data import Idris.Docstrings hiding (Unchecked) import Paths_idris import Util.DynamicLinker import Util.System (readSource, writeSource) import qualified Util.Pretty as P import Idris.Core.TT import Idris.Core.Evaluate import Control.Applicative hiding (Const) import Control.Monad import Control.Monad.State.Strict import Data.Function import Data.Maybe import qualified Data.List.Split as Spl import Data.List import Data.Monoid import Data.Char import Data.Ord import Data.Foldable (asum) import Data.Generics.Uniplate.Data (descendM) import qualified Data.Map as M import qualified Data.HashSet as HS import qualified Data.Text as T import qualified Data.ByteString.UTF8 as UTF8 import qualified Data.Set as S import Debug.Trace import System.FilePath import System.IO {- @ grammar shortcut notation: ~CHARSEQ = complement of char sequence (i.e. any character except CHARSEQ) RULE? = optional rule (i.e. RULE or nothing) RULE* = repeated rule (i.e. RULE zero or more times) RULE+ = repeated rule with at least one match (i.e. RULE one or more times) RULE! = invalid rule (i.e. rule that is not valid in context, report meaningful error in case) RULE{n} = rule repeated n times @ -} {- * Main grammar -} {-| Parses module definition @ ModuleHeader ::= DocComment_t? 'module' Identifier_t ';'?; @ -} moduleHeader :: IdrisParser (Maybe (Docstring ()), [String], [(FC, OutputAnnotation)]) moduleHeader = try (do docs <- optional docComment noArgs docs reservedHL "module" (i, ifc) <- identifier option ';' (lchar ';') let modName = moduleName i return (fmap fst docs, modName, [(ifc, AnnNamespace (map T.pack modName) Nothing)])) <|> try (do lchar '%'; reserved "unqualified" return (Nothing, [], [])) <|> return (Nothing, moduleName "Main", []) where moduleName x = case span (/='.') x of (x, "") -> [x] (x, '.':y) -> x : moduleName y noArgs (Just (_, args)) | not (null args) = fail "Modules do not take arguments" noArgs _ = return () data ImportInfo = ImportInfo { import_reexport :: Bool , import_path :: FilePath , import_rename :: Maybe (String, FC) , import_namespace :: [T.Text] , import_location :: FC , import_modname_location :: FC } {-| Parses an import statement @ Import ::= 'import' Identifier_t ';'?; @ -} import_ :: IdrisParser ImportInfo import_ = do fc <- getFC reservedHL "import" reexport <- option False (do reservedHL "public" return True) (id, idfc) <- identifier newName <- optional (do reservedHL "as" identifier) option ';' (lchar ';') return $ ImportInfo reexport (toPath id) (fmap (\(n, fc) -> (toPath n, fc)) newName) (map T.pack $ ns id) fc idfc <?> "import statement" where ns = Spl.splitOn "." toPath = foldl1' (</>) . ns {-| Parses program source @ Prog ::= Decl* EOF; @ -} prog :: SyntaxInfo -> IdrisParser [PDecl] prog syn = do whiteSpace decls <- many (decl syn) let c = concat decls case maxline syn of Nothing -> do notOpenBraces; eof _ -> return () ist <- get fc <- getFC put ist { idris_parsedSpan = Just (FC (fc_fname fc) (0,0) (fc_end fc)), ibc_write = IBCParsedRegion fc : ibc_write ist } return c {-| Parses a top-level declaration @ Decl ::= Decl' | Using | Params | Mutual | Namespace | Class | Instance | DSL | Directive | Provider | Transform | Import! | RunElabDecl ; @ -} decl :: SyntaxInfo -> IdrisParser [PDecl] decl syn = try (externalDecl syn) <|> internalDecl syn <?> "declaration" internalDecl :: SyntaxInfo -> IdrisParser [PDecl] internalDecl syn = do fc <- getFC -- if we're after maxline, stop at the next type declaration -- (so we get all cases of a definition to preserve totality -- results, in particular). let continue = case maxline syn of Nothing -> True Just l -> if fst (fc_end fc) > l then mut_nesting syn /= 0 else True -- What I'd really like to do here is explicitly save the -- current state, then if reading ahead finds we've passed -- the end of the definition, reset the state. But I've lost -- patience with trying to find out how to do that from the -- trifecta docs, so this does the job instead. if continue then do notEndBlock declBody continue else try (do notEndBlock declBody continue) <|> fail "End of readable input" where declBody :: Bool -> IdrisParser [PDecl] declBody b = try (instance_ True syn) <|> try (openInterface syn) <|> declBody' b <|> using_ syn <|> params syn <|> mutual syn <|> namespace syn <|> class_ syn <|> do d <- dsl syn; return [d] <|> directive syn <|> provider syn <|> transform syn <|> do import_; fail "imports must be at top of file" <?> "declaration" declBody' :: Bool -> IdrisParser [PDecl] declBody' cont = do d <- decl' syn i <- get let d' = fmap (debindApp syn . (desugar syn i)) d if continue cont d' then return [d'] else fail "End of readable input" -- Keep going while we're still parsing clauses continue False (PClauses _ _ _ _) = True continue c _ = c {-| Parses a top-level declaration with possible syntax sugar @ Decl' ::= Fixity | FunDecl' | Data | Record | SyntaxDecl ; @ -} decl' :: SyntaxInfo -> IdrisParser PDecl decl' syn = fixity <|> syntaxDecl syn <|> fnDecl' syn <|> data_ syn <|> record syn <|> runElabDecl syn <?> "declaration" externalDecl :: SyntaxInfo -> IdrisParser [PDecl] externalDecl syn = do i <- get notEndBlock FC fn start _ <- getFC decls <- declExtensions syn (syntaxRulesList $ syntax_rules i) FC _ _ end <- getFC let outerFC = FC fn start end return $ map (mapPDeclFC (fixFC outerFC) (fixFCH fn outerFC)) decls where -- | Fix non-highlighting FCs to prevent spurious error location reports fixFC :: FC -> FC -> FC fixFC outer inner | inner `fcIn` outer = inner | otherwise = outer -- | Fix highlighting FCs by obliterating them, to avoid spurious highlights fixFCH fn outer inner | inner `fcIn` outer = inner | otherwise = FileFC fn declExtensions :: SyntaxInfo -> [Syntax] -> IdrisParser [PDecl] declExtensions syn rules = declExtension syn [] (filter isDeclRule rules) <?> "user-defined declaration" where isDeclRule (DeclRule _ _) = True isDeclRule _ = False declExtension :: SyntaxInfo -> [Maybe (Name, SynMatch)] -> [Syntax] -> IdrisParser [PDecl] declExtension syn ns rules = choice $ flip map (groupBy (ruleGroup `on` syntaxSymbols) rules) $ \rs -> case head rs of -- can never be [] DeclRule (symb:_) _ -> try $ do n <- extSymbol symb declExtension syn (n : ns) [DeclRule ss t | (DeclRule (_:ss) t) <- rs] -- If we have more than one Rule in this bucket, our grammar is -- nondeterministic. DeclRule [] dec -> let r = map (update (mapMaybe id ns)) dec in return r where update :: [(Name, SynMatch)] -> PDecl -> PDecl update ns = updateNs ns . fmap (updateRefs ns) . fmap (updateSynMatch ns) updateRefs ns = mapPT newref where newref (PRef fc fcs n) = PRef fc fcs (updateB ns n) newref t = t -- Below is a lot of tedious boilerplate which updates any top level -- names in the declaration. It will only change names which are bound in -- the declaration (including method names in classes and field names in -- record declarations, not including pattern variables) updateB :: [(Name, SynMatch)] -> Name -> Name updateB ns (NS n mods) = NS (updateB ns n) mods updateB ns n = case lookup n ns of Just (SynBind tfc t) -> t _ -> n updateNs :: [(Name, SynMatch)] -> PDecl -> PDecl updateNs ns (PTy doc argdoc s fc o n fc' t) = PTy doc argdoc s fc o (updateB ns n) fc' t updateNs ns (PClauses fc o n cs) = PClauses fc o (updateB ns n) (map (updateClause ns) cs) updateNs ns (PCAF fc n t) = PCAF fc (updateB ns n) t updateNs ns (PData ds cds s fc o dat) = PData ds cds s fc o (updateData ns dat) updateNs ns (PParams fc ps ds) = PParams fc ps (map (updateNs ns) ds) updateNs ns (PNamespace s fc ds) = PNamespace s fc (map (updateNs ns) ds) updateNs ns (PRecord doc syn fc o n fc' ps pdocs fields cname cdoc s) = PRecord doc syn fc o (updateB ns n) fc' ps pdocs (map (updateField ns) fields) (updateRecCon ns cname) cdoc s updateNs ns (PClass docs s fc cs cn fc' ps pdocs pdets ds cname cdocs) = PClass docs s fc cs (updateB ns cn) fc' ps pdocs pdets (map (updateNs ns) ds) (updateRecCon ns cname) cdocs updateNs ns (PInstance docs pdocs s fc cs pnames acc opts cn fc' ps pextra ity ni ds) = PInstance docs pdocs s fc cs pnames acc opts (updateB ns cn) fc' ps pextra ity (fmap (updateB ns) ni) (map (updateNs ns) ds) updateNs ns (PMutual fc ds) = PMutual fc (map (updateNs ns) ds) updateNs ns (PProvider docs s fc fc' pw n) = PProvider docs s fc fc' pw (updateB ns n) updateNs ns d = d updateRecCon ns Nothing = Nothing updateRecCon ns (Just (n, fc)) = Just (updateB ns n, fc) updateField ns (m, p, t, doc) = (updateRecCon ns m, p, t, doc) updateClause ns (PClause fc n t ts t' ds) = PClause fc (updateB ns n) t ts t' (map (update ns) ds) updateClause ns (PWith fc n t ts t' m ds) = PWith fc (updateB ns n) t ts t' m (map (update ns) ds) updateClause ns (PClauseR fc ts t ds) = PClauseR fc ts t (map (update ns) ds) updateClause ns (PWithR fc ts t m ds) = PWithR fc ts t m (map (update ns) ds) updateData ns (PDatadecl n fc t cs) = PDatadecl (updateB ns n) fc t (map (updateCon ns) cs) updateData ns (PLaterdecl n fc t) = PLaterdecl (updateB ns n) fc t updateCon ns (cd, ads, cn, fc, ty, fc', fns) = (cd, ads, updateB ns cn, fc, ty, fc', fns) ruleGroup [] [] = True ruleGroup (s1:_) (s2:_) = s1 == s2 ruleGroup _ _ = False extSymbol :: SSymbol -> IdrisParser (Maybe (Name, SynMatch)) extSymbol (Keyword n) = do fc <- reservedFC (show n) highlightP fc AnnKeyword return Nothing extSymbol (Expr n) = do tm <- expr syn return $ Just (n, SynTm tm) extSymbol (SimpleExpr n) = do tm <- simpleExpr syn return $ Just (n, SynTm tm) extSymbol (Binding n) = do (b, fc) <- name return $ Just (n, SynBind fc b) extSymbol (Symbol s) = do fc <- symbolFC s highlightP fc AnnKeyword return Nothing {-| Parses a syntax extension declaration (and adds the rule to parser state) @ SyntaxDecl ::= SyntaxRule; @ -} syntaxDecl :: SyntaxInfo -> IdrisParser PDecl syntaxDecl syn = do s <- syntaxRule syn i <- get put (i `addSyntax` s) fc <- getFC return (PSyntax fc s) -- | Extend an 'IState' with a new syntax extension. See also 'addReplSyntax'. addSyntax :: IState -> Syntax -> IState addSyntax i s = i { syntax_rules = updateSyntaxRules [s] rs, syntax_keywords = ks ++ ns, ibc_write = IBCSyntax s : map IBCKeyword ks ++ ibc } where rs = syntax_rules i ns = syntax_keywords i ibc = ibc_write i ks = map show (syntaxNames s) -- | Like 'addSyntax', but no effect on the IBC. addReplSyntax :: IState -> Syntax -> IState addReplSyntax i s = i { syntax_rules = updateSyntaxRules [s] rs, syntax_keywords = ks ++ ns } where rs = syntax_rules i ns = syntax_keywords i ks = map show (syntaxNames s) {-| Parses a syntax extension declaration @ SyntaxRuleOpts ::= 'term' | 'pattern'; @ @ SyntaxRule ::= SyntaxRuleOpts? 'syntax' SyntaxSym+ '=' TypeExpr Terminator; @ @ SyntaxSym ::= '[' Name_t ']' | '{' Name_t '}' | Name_t | StringLiteral_t ; @ -} syntaxRule :: SyntaxInfo -> IdrisParser Syntax syntaxRule syn = do sty <- try (do pushIndent sty <- option AnySyntax (do reservedHL "term"; return TermSyntax <|> do reservedHL "pattern"; return PatternSyntax) reservedHL "syntax" return sty) syms <- some syntaxSym when (all isExpr syms) $ unexpected "missing keywords in syntax rule" let ns = mapMaybe getName syms when (length ns /= length (nub ns)) $ unexpected "repeated variable in syntax rule" lchar '=' tm <- typeExpr (allowImp syn) >>= uniquifyBinders [n | Binding n <- syms] terminator return (Rule (mkSimple syms) tm sty) <|> do reservedHL "decl"; reservedHL "syntax" syms <- some syntaxSym when (all isExpr syms) $ unexpected "missing keywords in syntax rule" let ns = mapMaybe getName syms when (length ns /= length (nub ns)) $ unexpected "repeated variable in syntax rule" lchar '=' openBlock dec <- some (decl syn) closeBlock return (DeclRule (mkSimple syms) (concat dec)) where isExpr (Expr _) = True isExpr _ = False getName (Expr n) = Just n getName _ = Nothing -- Can't parse two full expressions (i.e. expressions with application) in a row -- so change them both to a simple expression mkSimple (Expr e : es) = SimpleExpr e : mkSimple' es mkSimple xs = mkSimple' xs mkSimple' (Expr e : Expr e1 : es) = SimpleExpr e : SimpleExpr e1 : mkSimple es -- Can't parse a full expression followed by operator like characters due to ambiguity mkSimple' (Expr e : Symbol s : es) | takeWhile (`elem` opChars) ts /= "" = SimpleExpr e : Symbol s : mkSimple' es where ts = dropWhile isSpace . dropWhileEnd isSpace $ s mkSimple' (e : es) = e : mkSimple' es mkSimple' [] = [] -- Prevent syntax variable capture by making all binders under syntax unique -- (the ol' Common Lisp GENSYM approach) uniquifyBinders :: [Name] -> PTerm -> IdrisParser PTerm uniquifyBinders userNames = fixBind 0 [] where fixBind :: Int -> [(Name, Name)] -> PTerm -> IdrisParser PTerm fixBind 0 rens (PRef fc hls n) | Just n' <- lookup n rens = return $ PRef fc hls n' fixBind 0 rens (PPatvar fc n) | Just n' <- lookup n rens = return $ PPatvar fc n' fixBind 0 rens (PLam fc n nfc ty body) | n `elem` userNames = liftM2 (PLam fc n nfc) (fixBind 0 rens ty) (fixBind 0 rens body) | otherwise = do ty' <- fixBind 0 rens ty n' <- gensym n body' <- fixBind 0 ((n,n'):rens) body return $ PLam fc n' nfc ty' body' fixBind 0 rens (PPi plic n nfc argTy body) | n `elem` userNames = liftM2 (PPi plic n nfc) (fixBind 0 rens argTy) (fixBind 0 rens body) | otherwise = do ty' <- fixBind 0 rens argTy n' <- gensym n body' <- fixBind 0 ((n,n'):rens) body return $ (PPi plic n' nfc ty' body') fixBind 0 rens (PLet fc n nfc ty val body) | n `elem` userNames = liftM3 (PLet fc n nfc) (fixBind 0 rens ty) (fixBind 0 rens val) (fixBind 0 rens body) | otherwise = do ty' <- fixBind 0 rens ty val' <- fixBind 0 rens val n' <- gensym n body' <- fixBind 0 ((n,n'):rens) body return $ PLet fc n' nfc ty' val' body' fixBind 0 rens (PMatchApp fc n) | Just n' <- lookup n rens = return $ PMatchApp fc n' -- Also rename resolved quotations, to allow syntax rules to -- have quoted references to their own bindings. fixBind 0 rens (PQuoteName n True fc) | Just n' <- lookup n rens = return $ PQuoteName n' True fc -- Don't mess with quoted terms fixBind q rens (PQuasiquote tm goal) = flip PQuasiquote goal <$> fixBind (q + 1) rens tm fixBind q rens (PUnquote tm) = PUnquote <$> fixBind (q - 1) rens tm fixBind q rens x = descendM (fixBind q rens) x gensym :: Name -> IdrisParser Name gensym n = do ist <- get let idx = idris_name ist put ist { idris_name = idx + 1 } return $ sMN idx (show n) {-| Parses a syntax symbol (either binding variable, keyword or expression) @ SyntaxSym ::= '[' Name_t ']' | '{' Name_t '}' | Name_t | StringLiteral_t ; @ -} syntaxSym :: IdrisParser SSymbol syntaxSym = try (do lchar '['; n <- fst <$> name; lchar ']' return (Expr n)) <|> try (do lchar '{'; n <- fst <$> name; lchar '}' return (Binding n)) <|> do n <- fst <$> iName [] return (Keyword n) <|> do sym <- fmap fst stringLiteral return (Symbol sym) <?> "syntax symbol" {-| Parses a function declaration with possible syntax sugar @ FunDecl ::= FunDecl'; @ -} fnDecl :: SyntaxInfo -> IdrisParser [PDecl] fnDecl syn = try (do notEndBlock d <- fnDecl' syn i <- get let d' = fmap (desugar syn i) d return [d']) <?> "function declaration" {-| Parses a function declaration @ FunDecl' ::= DocComment_t? FnOpts* Accessibility? FnOpts* FnName TypeSig Terminator | Postulate | Pattern | CAF ; @ -} fnDecl' :: SyntaxInfo -> IdrisParser PDecl fnDecl' syn = checkFixity $ do (doc, argDocs, fc, opts', n, nfc, acc) <- try (do pushIndent (doc, argDocs) <- docstring syn (opts, acc) <- fnOpts (n_in, nfc) <- fnName let n = expandNS syn n_in fc <- getFC lchar ':' return (doc, argDocs, fc, opts, n, nfc, acc)) ty <- typeExpr (allowImp syn) terminator -- If it's a top level function, note the accessibility -- rules when (syn_toplevel syn) $ addAcc n acc return (PTy doc argDocs syn fc opts' n nfc ty) <|> postulate syn <|> caf syn <|> pattern syn <?> "function declaration" where checkFixity :: IdrisParser PDecl -> IdrisParser PDecl checkFixity p = do decl <- p case getName decl of Nothing -> return decl Just n -> do fOk <- fixityOK n unless fOk . fail $ "Missing fixity declaration for " ++ show n return decl getName (PTy _ _ _ _ _ n _ _) = Just n getName _ = Nothing fixityOK (NS n _) = fixityOK n fixityOK (UN n) | all (flip elem opChars) (str n) = do fixities <- fmap idris_infixes get return . elem (str n) . map (\ (Fix _ op) -> op) $ fixities | otherwise = return True fixityOK _ = return True {-| Parses a series of function and accessbility options @ FnOpts ::= FnOpt* Accessibility FnOpt* @ -} fnOpts :: IdrisParser ([FnOpt], Accessibility) fnOpts = do opts <- many fnOpt acc <- accessibility opts' <- many fnOpt let allOpts = opts ++ opts' let existingTotality = allOpts `intersect` [TotalFn, CoveringFn, PartialFn] opts'' <- addDefaultTotality (nub existingTotality) allOpts return (opts'', acc) where prettyTot TotalFn = "total" prettyTot PartialFn = "partial" prettyTot CoveringFn = "covering" addDefaultTotality [] opts = do ist <- get case default_total ist of DefaultCheckingTotal -> return (TotalFn:opts) DefaultCheckingCovering -> return (CoveringFn:opts) DefaultCheckingPartial -> return opts -- Don't add partial so that --warn-partial still reports warnings if necessary addDefaultTotality [tot] opts = return opts -- Should really be a semantics error instead of a parser error addDefaultTotality (tot1:tot2:tots) opts = fail ("Conflicting totality modifiers specified " ++ prettyTot tot1 ++ " and " ++ prettyTot tot2) {-| Parses a function option @ FnOpt ::= 'total' | 'partial' | 'covering' | 'implicit' | '%' 'no_implicit' | '%' 'assert_total' | '%' 'error_handler' | '%' 'reflection' | '%' 'specialise' '[' NameTimesList? ']' ; @ @ NameTimes ::= FnName Natural?; @ @ NameTimesList ::= NameTimes | NameTimes ',' NameTimesList ; @ -} fnOpt :: IdrisParser FnOpt fnOpt = do reservedHL "total"; return TotalFn <|> do reservedHL "partial"; return PartialFn <|> do reservedHL "covering"; return CoveringFn <|> do try (lchar '%' *> reserved "export"); c <- fmap fst stringLiteral; return $ CExport c <|> do try (lchar '%' *> reserved "no_implicit"); return NoImplicit <|> do try (lchar '%' *> reserved "inline"); return Inlinable <|> do try (lchar '%' *> reserved "assert_total"); fc <- getFC parserWarning fc Nothing (Msg "%assert_total is deprecated. Use the 'assert_total' function instead.") return AssertTotal <|> do try (lchar '%' *> reserved "error_handler"); return ErrorHandler <|> do try (lchar '%' *> reserved "error_reverse"); return ErrorReverse <|> do try (lchar '%' *> reserved "reflection"); return Reflection <|> do try (lchar '%' *> reserved "hint"); return AutoHint <|> do lchar '%'; reserved "specialise"; lchar '['; ns <- sepBy nameTimes (lchar ','); lchar ']'; return $ Specialise ns <|> do reservedHL "implicit"; return Implicit <?> "function modifier" where nameTimes :: IdrisParser (Name, Maybe Int) nameTimes = do n <- fst <$> fnName t <- option Nothing (do reds <- fmap fst natural return (Just (fromInteger reds))) return (n, t) {-| Parses a postulate @ Postulate ::= DocComment_t? 'postulate' FnOpts* Accesibility? FnOpts* FnName TypeSig Terminator ; @ -} postulate :: SyntaxInfo -> IdrisParser PDecl postulate syn = do (doc, ext) <- try $ do (doc, _) <- docstring syn pushIndent ext <- ppostDecl return (doc, ext) ist <- get (opts, acc) <- fnOpts (n_in, nfc) <- fnName let n = expandNS syn n_in lchar ':' ty <- typeExpr (allowImp syn) fc <- getFC terminator addAcc n acc return (PPostulate ext doc syn fc nfc opts n ty) <?> "postulate" where ppostDecl = do fc <- reservedHL "postulate"; return False <|> do lchar '%'; reserved "extern"; return True {-| Parses a using declaration @ Using ::= 'using' '(' UsingDeclList ')' OpenBlock Decl* CloseBlock ; @ -} using_ :: SyntaxInfo -> IdrisParser [PDecl] using_ syn = do reservedHL "using" lchar '('; ns <- usingDeclList syn; lchar ')' openBlock let uvars = using syn ds <- many (decl (syn { using = uvars ++ ns })) closeBlock return (concat ds) <?> "using declaration" {-| Parses a parameters declaration @ Params ::= 'parameters' '(' TypeDeclList ')' OpenBlock Decl* CloseBlock ; @ -} params :: SyntaxInfo -> IdrisParser [PDecl] params syn = do reservedHL "parameters"; lchar '('; ns <- typeDeclList syn; lchar ')' let ns' = [(n, ty) | (n, _, ty) <- ns] openBlock let pvars = syn_params syn ds <- many (decl syn { syn_params = pvars ++ ns' }) closeBlock fc <- getFC return [PParams fc ns' (concat ds)] <?> "parameters declaration" -- | Parses an open block openInterface :: SyntaxInfo -> IdrisParser [PDecl] openInterface syn = do reservedHL "using" reservedHL "implementation" fc <- getFC ns <- sepBy1 fnName (lchar ',') openBlock ds <- many (decl syn) closeBlock return [POpenInterfaces fc (map fst ns) (concat ds)] <?> "open interface declaration" {-| Parses a mutual declaration (for mutually recursive functions) @ Mutual ::= 'mutual' OpenBlock Decl* CloseBlock ; @ -} mutual :: SyntaxInfo -> IdrisParser [PDecl] mutual syn = do reservedHL "mutual" openBlock let pvars = syn_params syn ds <- many (decl (syn { mut_nesting = mut_nesting syn + 1 } )) closeBlock fc <- getFC return [PMutual fc (concat ds)] <?> "mutual block" {-| Parses a namespace declaration @ Namespace ::= 'namespace' identifier OpenBlock Decl+ CloseBlock ; @ -} namespace :: SyntaxInfo -> IdrisParser [PDecl] namespace syn = do reservedHL "namespace" (n, nfc) <- identifier openBlock ds <- some (decl syn { syn_namespace = n : syn_namespace syn }) closeBlock return [PNamespace n nfc (concat ds)] <?> "namespace declaration" {-| Parses a methods block (for instances) @ InstanceBlock ::= 'where' OpenBlock FnDecl* CloseBlock @ -} instanceBlock :: SyntaxInfo -> IdrisParser [PDecl] instanceBlock syn = do reservedHL "where" openBlock ds <- many (fnDecl syn) closeBlock return (concat ds) <?> "implementation block" {-| Parses a methods and instances block (for type classes) @ MethodOrInstance ::= FnDecl | Instance ; @ @ ClassBlock ::= 'where' OpenBlock Constructor? MethodOrInstance* CloseBlock ; @ -} classBlock :: SyntaxInfo -> IdrisParser (Maybe (Name, FC), Docstring (Either Err PTerm), [PDecl]) classBlock syn = do reservedHL "where" openBlock (cn, cd) <- option (Nothing, emptyDocstring) $ try (do (doc, _) <- option noDocs docComment n <- constructor return (Just n, doc)) ist <- get let cd' = annotate syn ist cd ds <- many (notEndBlock >> try (instance_ True syn) <|> do x <- data_ syn return [x] <|> fnDecl syn) closeBlock return (cn, cd', concat ds) <?> "class block" where constructor :: IdrisParser (Name, FC) constructor = reservedHL "constructor" *> fnName annotate :: SyntaxInfo -> IState -> Docstring () -> Docstring (Either Err PTerm) annotate syn ist = annotCode $ tryFullExpr syn ist {-| Parses a type class declaration @ ClassArgument ::= Name | '(' Name ':' Expr ')' ; @ @ Class ::= DocComment_t? Accessibility? 'class' ConstraintList? Name ClassArgument* ClassBlock? ; @ -} class_ :: SyntaxInfo -> IdrisParser [PDecl] class_ syn = do (doc, argDocs, acc) <- try (do (doc, argDocs) <- docstring syn acc <- accessibility classKeyword return (doc, argDocs, acc)) fc <- getFC cons <- constraintList syn let cons' = [(c, ty) | (c, _, ty) <- cons] (n_in, nfc) <- fnName let n = expandNS syn n_in cs <- many carg fds <- option [(cn, NoFC) | (cn, _, _) <- cs] fundeps (cn, cd, ds) <- option (Nothing, fst noDocs, []) (classBlock syn) accData acc n (concatMap declared ds) return [PClass doc syn fc cons' n nfc cs argDocs fds ds cn cd] <?> "type-class declaration" where fundeps :: IdrisParser [(Name, FC)] fundeps = do lchar '|'; sepBy name (lchar ',') classKeyword :: IdrisParser () classKeyword = reservedHL "interface" <|> do reservedHL "class" fc <- getFC parserWarning fc Nothing (Msg "The 'class' keyword is deprecated. Use 'interface' instead.") carg :: IdrisParser (Name, FC, PTerm) carg = do lchar '('; (i, ifc) <- name; lchar ':'; ty <- expr syn; lchar ')' return (i, ifc, ty) <|> do (i, ifc) <- name fc <- getFC return (i, ifc, PType fc) {-| Parses a type class instance declaration @ Instance ::= DocComment_t? 'instance' InstanceName? ConstraintList? Name SimpleExpr* InstanceBlock? ; @ @ InstanceName ::= '[' Name ']'; @ -} instance_ :: Bool -> SyntaxInfo -> IdrisParser [PDecl] instance_ kwopt syn = do ist <- get (doc, argDocs) <- docstring syn (opts, acc) <- fnOpts if kwopt then optional instanceKeyword else do instanceKeyword return (Just ()) fc <- getFC en <- optional instanceName cs <- constraintList syn let cs' = [(c, ty) | (c, _, ty) <- cs] (cn, cnfc) <- fnName args <- many (simpleExpr syn) let sc = PApp fc (PRef cnfc [cnfc] cn) (map pexp args) let t = bindList (PPi constraint) cs sc pnames <- instanceUsing ds <- instanceBlock syn return [PInstance doc argDocs syn fc cs' pnames acc opts cn cnfc args [] t en ds] <?> "implementation declaration" where instanceName :: IdrisParser Name instanceName = do lchar '['; n_in <- fst <$> fnName; lchar ']' let n = expandNS syn n_in return n <?> "implementation name" instanceKeyword :: IdrisParser () instanceKeyword = reservedHL "implementation" <|> do reservedHL "instance" fc <- getFC parserWarning fc Nothing (Msg "The 'instance' keyword is deprecated. Use 'implementation' (or omit it) instead.") instanceUsing :: IdrisParser [Name] instanceUsing = do reservedHL "using" ns <- sepBy1 fnName (lchar ',') return (map fst ns) <|> return [] -- | Parse a docstring docstring :: SyntaxInfo -> IdrisParser (Docstring (Either Err PTerm), [(Name,Docstring (Either Err PTerm))]) docstring syn = do (doc, argDocs) <- option noDocs docComment ist <- get let doc' = annotCode (tryFullExpr syn ist) doc argDocs' = [ (n, annotCode (tryFullExpr syn ist) d) | (n, d) <- argDocs ] return (doc', argDocs') {-| Parses a using declaration list @ UsingDeclList ::= UsingDeclList' | NameList TypeSig ; @ @ UsingDeclList' ::= UsingDecl | UsingDecl ',' UsingDeclList' ; @ @ NameList ::= Name | Name ',' NameList ; @ -} usingDeclList :: SyntaxInfo -> IdrisParser [Using] usingDeclList syn = try (sepBy1 (usingDecl syn) (lchar ',')) <|> do ns <- sepBy1 (fst <$> name) (lchar ',') lchar ':' t <- typeExpr (disallowImp syn) return (map (\x -> UImplicit x t) ns) <?> "using declaration list" {-| Parses a using declaration @ UsingDecl ::= FnName TypeSig | FnName FnName+ ; @ -} usingDecl :: SyntaxInfo -> IdrisParser Using usingDecl syn = try (do x <- fst <$> fnName lchar ':' t <- typeExpr (disallowImp syn) return (UImplicit x t)) <|> do c <- fst <$> fnName xs <- many (fst <$> fnName) return (UConstraint c xs) <?> "using declaration" {-| Parse a clause with patterns @ Pattern ::= Clause; @ -} pattern :: SyntaxInfo -> IdrisParser PDecl pattern syn = do fc <- getFC clause <- clause syn return (PClauses fc [] (sMN 2 "_") [clause]) -- collect together later <?> "pattern" {-| Parse a constant applicative form declaration @ CAF ::= 'let' FnName '=' Expr Terminator; @ -} caf :: SyntaxInfo -> IdrisParser PDecl caf syn = do reservedHL "let" n_in <- fst <$> fnName; let n = expandNS syn n_in pushIndent lchar '=' t <- indented $ expr syn terminator fc <- getFC return (PCAF fc n t) <?> "constant applicative form declaration" {-| Parse an argument expression @ ArgExpr ::= HSimpleExpr | {- In Pattern External (User-defined) Expression -}; @ -} argExpr :: SyntaxInfo -> IdrisParser PTerm argExpr syn = let syn' = syn { inPattern = True } in try (hsimpleExpr syn') <|> simpleExternalExpr syn' <?> "argument expression" {-| Parse a right hand side of a function @ RHS ::= '=' Expr | '?=' RHSName? Expr | Impossible ; @ @ RHSName ::= '{' FnName '}'; @ -} rhs :: SyntaxInfo -> Name -> IdrisParser PTerm rhs syn n = do lchar '=' indentPropHolds gtProp expr syn <|> do symbol "?="; fc <- getFC name <- option n' (do symbol "{"; n <- fst <$> fnName; symbol "}"; return n) r <- expr syn return (addLet fc name r) <|> impossible <?> "function right hand side" where mkN :: Name -> Name mkN (UN x) = if (tnull x || not (isAlpha (thead x))) then sUN "infix_op_lemma_1" else sUN (str x++"_lemma_1") mkN (NS x n) = NS (mkN x) n n' :: Name n' = mkN n addLet :: FC -> Name -> PTerm -> PTerm addLet fc nm (PLet fc' n nfc ty val r) = PLet fc' n nfc ty val (addLet fc nm r) addLet fc nm (PCase fc' t cs) = PCase fc' t (map addLetC cs) where addLetC (l, r) = (l, addLet fc nm r) addLet fc nm r = (PLet fc (sUN "value") NoFC Placeholder r (PMetavar NoFC nm)) {-|Parses a function clause @ RHSOrWithBlock ::= RHS WhereOrTerminator | 'with' SimpleExpr OpenBlock FnDecl+ CloseBlock ; @ @ Clause ::= WExpr+ RHSOrWithBlock | SimpleExpr '<==' FnName RHS WhereOrTerminator | ArgExpr Operator ArgExpr WExpr* RHSOrWithBlock {- Except "=" and "?=" operators to avoid ambiguity -} | FnName ConstraintArg* ImplicitOrArgExpr* WExpr* RHSOrWithBlock ; @ @ ImplicitOrArgExpr ::= ImplicitArg | ArgExpr; @ @ WhereOrTerminator ::= WhereBlock | Terminator; @ -} clause :: SyntaxInfo -> IdrisParser PClause clause syn = do wargs <- try (do pushIndent; some (wExpr syn)) fc <- getFC ist <- get n <- case lastParse ist of Just t -> return t Nothing -> fail "Invalid clause" (do r <- rhs syn n let ctxt = tt_ctxt ist let wsyn = syn { syn_namespace = [], syn_toplevel = False } (wheres, nmap) <- choice [do x <- whereBlock n wsyn popIndent return x, do terminator return ([], [])] return $ PClauseR fc wargs r wheres) <|> (do popIndent reservedHL "with" wval <- simpleExpr syn pn <- optProof openBlock ds <- some $ fnDecl syn let withs = concat ds closeBlock return $ PWithR fc wargs wval pn withs) <|> do ty <- try (do pushIndent ty <- simpleExpr syn symbol "<==" return ty) fc <- getFC n_in <- fst <$> fnName; let n = expandNS syn n_in r <- rhs syn n ist <- get let ctxt = tt_ctxt ist let wsyn = syn { syn_namespace = [] } (wheres, nmap) <- choice [do x <- whereBlock n wsyn popIndent return x, do terminator return ([], [])] let capp = PLet fc (sMN 0 "match") NoFC ty (PMatchApp fc n) (PRef fc [] (sMN 0 "match")) ist <- get put (ist { lastParse = Just n }) return $ PClause fc n capp [] r wheres <|> do (l, op, nfc) <- try (do pushIndent l <- argExpr syn (op, nfc) <- operatorFC when (op == "=" || op == "?=" ) $ fail "infix clause definition with \"=\" and \"?=\" not supported " return (l, op, nfc)) let n = expandNS syn (sUN op) r <- argExpr syn fc <- getFC wargs <- many (wExpr syn) (do rs <- rhs syn n let wsyn = syn { syn_namespace = [] } (wheres, nmap) <- choice [do x <- whereBlock n wsyn popIndent return x, do terminator return ([], [])] ist <- get let capp = PApp fc (PRef nfc [nfc] n) [pexp l, pexp r] put (ist { lastParse = Just n }) return $ PClause fc n capp wargs rs wheres) <|> (do popIndent reservedHL "with" wval <- bracketed syn pn <- optProof openBlock ds <- some $ fnDecl syn closeBlock ist <- get let capp = PApp fc (PRef fc [] n) [pexp l, pexp r] let withs = map (fillLHSD n capp wargs) $ concat ds put (ist { lastParse = Just n }) return $ PWith fc n capp wargs wval pn withs) <|> do pushIndent (n_in, nfc) <- fnName; let n = expandNS syn n_in fc <- getFC args <- many (try (implicitArg (syn { inPattern = True } )) <|> try (constraintArg (syn { inPattern = True })) <|> (fmap pexp (argExpr syn))) wargs <- many (wExpr syn) let capp = PApp fc (PRef nfc [nfc] n) args (do r <- rhs syn n ist <- get let ctxt = tt_ctxt ist let wsyn = syn { syn_namespace = [] } (wheres, nmap) <- choice [do x <- whereBlock n wsyn popIndent return x, do terminator return ([], [])] ist <- get put (ist { lastParse = Just n }) return $ PClause fc n capp wargs r wheres) <|> (do reservedHL "with" ist <- get put (ist { lastParse = Just n }) wval <- bracketed syn pn <- optProof openBlock ds <- some $ fnDecl syn let withs = map (fillLHSD n capp wargs) $ concat ds closeBlock popIndent return $ PWith fc n capp wargs wval pn withs) <?> "function clause" where optProof = option Nothing (do reservedHL "proof" n <- fnName return (Just n)) fillLHS :: Name -> PTerm -> [PTerm] -> PClause -> PClause fillLHS n capp owargs (PClauseR fc wargs v ws) = PClause fc n capp (owargs ++ wargs) v ws fillLHS n capp owargs (PWithR fc wargs v pn ws) = PWith fc n capp (owargs ++ wargs) v pn (map (fillLHSD n capp (owargs ++ wargs)) ws) fillLHS _ _ _ c = c fillLHSD :: Name -> PTerm -> [PTerm] -> PDecl -> PDecl fillLHSD n c a (PClauses fc o fn cs) = PClauses fc o fn (map (fillLHS n c a) cs) fillLHSD n c a x = x {-| Parses with pattern @ WExpr ::= '|' Expr'; @ -} wExpr :: SyntaxInfo -> IdrisParser PTerm wExpr syn = do lchar '|' expr' (syn { inPattern = True }) <?> "with pattern" {-| Parses a where block @ WhereBlock ::= 'where' OpenBlock Decl+ CloseBlock; @ -} whereBlock :: Name -> SyntaxInfo -> IdrisParser ([PDecl], [(Name, Name)]) whereBlock n syn = do reservedHL "where" ds <- indentedBlock1 (decl syn) let dns = concatMap (concatMap declared) ds return (concat ds, map (\x -> (x, decoration syn x)) dns) <?> "where block" {-|Parses a code generation target language name @ Codegen ::= 'C' | 'Java' | 'JavaScript' | 'Node' | 'LLVM' | 'Bytecode' ; @ -} codegen_ :: IdrisParser Codegen codegen_ = do n <- fst <$> identifier return (Via IBCFormat (map toLower n)) <|> do reserved "Bytecode"; return Bytecode <?> "code generation language" {-|Parses a compiler directive @ StringList ::= String | String ',' StringList ; @ @ Directive ::= '%' Directive'; @ @ Directive' ::= 'lib' CodeGen String_t | 'link' CodeGen String_t | 'flag' CodeGen String_t | 'include' CodeGen String_t | 'hide' Name | 'freeze' Name | 'thaw' Name | 'access' Accessibility | 'default' Totality | 'logging' Natural | 'dynamic' StringList | 'name' Name NameList | 'error_handlers' Name NameList | 'language' 'TypeProviders' | 'language' 'ErrorReflection' | 'deprecated' Name String | 'fragile' Name Reason ; @ -} directive :: SyntaxInfo -> IdrisParser [PDecl] directive syn = do try (lchar '%' *> reserved "lib") cgn <- codegen_ lib <- fmap fst stringLiteral return [PDirective (DLib cgn lib)] <|> do try (lchar '%' *> reserved "link") cgn <- codegen_; obj <- fst <$> stringLiteral return [PDirective (DLink cgn obj)] <|> do try (lchar '%' *> reserved "flag") cgn <- codegen_; flag <- fst <$> stringLiteral return [PDirective (DFlag cgn flag)] <|> do try (lchar '%' *> reserved "include") cgn <- codegen_ hdr <- fst <$> stringLiteral return [PDirective (DInclude cgn hdr)] <|> do try (lchar '%' *> reserved "hide"); n <- fst <$> fnName return [PDirective (DHide n)] <|> do try (lchar '%' *> reserved "freeze"); n <- fst <$> iName [] return [PDirective (DFreeze n)] <|> do try (lchar '%' *> reserved "thaw"); n <- fst <$> iName [] return [PDirective (DThaw n)] -- injectivity assertins are intended for debugging purposes -- only, and won't be documented/could be removed at any point <|> do try (lchar '%' *> reserved "assert_injective"); n <- fst <$> fnName return [PDirective (DInjective n)] -- Assert totality of something after definition. This is -- here as a debugging aid, so commented out... -- <|> do try (lchar '%' *> reserved "assert_set_total"); n <- fst <$> fnName -- return [PDirective (DSetTotal n)] <|> do try (lchar '%' *> reserved "access") acc <- accessibility ist <- get put ist { default_access = acc } return [PDirective (DAccess acc)] <|> do try (lchar '%' *> reserved "default"); tot <- totality i <- get put (i { default_total = tot } ) return [PDirective (DDefault tot)] <|> do try (lchar '%' *> reserved "logging") i <- fst <$> natural return [PDirective (DLogging i)] <|> do try (lchar '%' *> reserved "dynamic") libs <- sepBy1 (fmap fst stringLiteral) (lchar ',') return [PDirective (DDynamicLibs libs)] <|> do try (lchar '%' *> reserved "name") (ty, tyFC) <- fnName ns <- sepBy1 name (lchar ',') return [PDirective (DNameHint ty tyFC ns)] <|> do try (lchar '%' *> reserved "error_handlers") (fn, nfc) <- fnName (arg, afc) <- fnName ns <- sepBy1 name (lchar ',') return [PDirective (DErrorHandlers fn nfc arg afc ns) ] <|> do try (lchar '%' *> reserved "language"); ext <- pLangExt; return [PDirective (DLanguage ext)] <|> do try (lchar '%' *> reserved "deprecate") n <- fst <$> fnName alt <- option "" (fst <$> stringLiteral) return [PDirective (DDeprecate n alt)] <|> do try (lchar '%' *> reserved "fragile") n <- fst <$> fnName alt <- option "" (fst <$> stringLiteral) return [PDirective (DFragile n alt)] <|> do fc <- getFC try (lchar '%' *> reserved "used") fn <- fst <$> fnName arg <- fst <$> iName [] return [PDirective (DUsed fc fn arg)] <|> do try (lchar '%' *> reserved "auto_implicits") b <- on_off return [PDirective (DAutoImplicits b)] <?> "directive" where on_off = do reserved "on"; return True <|> do reserved "off"; return False pLangExt :: IdrisParser LanguageExt pLangExt = (reserved "TypeProviders" >> return TypeProviders) <|> (reserved "ErrorReflection" >> return ErrorReflection) {-| Parses a totality @ Totality ::= 'partial' | 'total' | 'covering' @ -} totality :: IdrisParser DefaultTotality totality = do reservedHL "total"; return DefaultCheckingTotal <|> do reservedHL "partial"; return DefaultCheckingPartial <|> do reservedHL "covering"; return DefaultCheckingCovering {-| Parses a type provider @ Provider ::= DocComment_t? '%' 'provide' Provider_What? '(' FnName TypeSig ')' 'with' Expr; ProviderWhat ::= 'proof' | 'term' | 'type' | 'postulate' @ -} provider :: SyntaxInfo -> IdrisParser [PDecl] provider syn = do doc <- try (do (doc, _) <- docstring syn fc1 <- getFC lchar '%' fc2 <- reservedFC "provide" highlightP (spanFC fc1 fc2) AnnKeyword return doc) provideTerm doc <|> providePostulate doc <?> "type provider" where provideTerm doc = do lchar '('; (n, nfc) <- fnName; lchar ':'; t <- typeExpr syn; lchar ')' fc <- getFC reservedHL "with" e <- expr syn <?> "provider expression" return [PProvider doc syn fc nfc (ProvTerm t e) n] providePostulate doc = do reservedHL "postulate" (n, nfc) <- fnName fc <- getFC reservedHL "with" e <- expr syn <?> "provider expression" return [PProvider doc syn fc nfc (ProvPostulate e) n] {-| Parses a transform @ Transform ::= '%' 'transform' Expr '==>' Expr @ -} transform :: SyntaxInfo -> IdrisParser [PDecl] transform syn = do try (lchar '%' *> reserved "transform") -- leave it unchecked, until we work out what this should -- actually mean... -- safety <- option True (do reserved "unsafe" -- return False) l <- expr syn fc <- getFC symbol "==>" r <- expr syn return [PTransform fc False l r] <?> "transform" {-| Parses a top-level reflected elaborator script @ RunElabDecl ::= '%' 'runElab' Expr @ -} runElabDecl :: SyntaxInfo -> IdrisParser PDecl runElabDecl syn = do kwFC <- try (do fc <- getFC lchar '%' fc' <- reservedFC "runElab" return (spanFC fc fc')) script <- expr syn <?> "elaborator script" highlightP kwFC AnnKeyword return $ PRunElabDecl kwFC script (syn_namespace syn) <?> "top-level elaborator script" {- * Loading and parsing -} {-| Parses an expression from input -} parseExpr :: IState -> String -> Result PTerm parseExpr st = runparser (fullExpr defaultSyntax) st "(input)" {-| Parses a constant form input -} parseConst :: IState -> String -> Result Const parseConst st = runparser (fmap fst constant) st "(input)" {-| Parses a tactic from input -} parseTactic :: IState -> String -> Result PTactic parseTactic st = runparser (fullTactic defaultSyntax) st "(input)" {-| Parses a do-step from input (used in the elab shell) -} parseElabShellStep :: IState -> String -> Result (Either ElabShellCmd PDo) parseElabShellStep ist = runparser (fmap Right (do_ defaultSyntax) <|> fmap Left elabShellCmd) ist "(input)" where elabShellCmd = char ':' >> (reserved "qed" >> pure EQED ) <|> (reserved "abandon" >> pure EAbandon ) <|> (reserved "undo" >> pure EUndo ) <|> (reserved "state" >> pure EProofState) <|> (reserved "term" >> pure EProofTerm ) <|> (expressionTactic ["e", "eval"] EEval ) <|> (expressionTactic ["t", "type"] ECheck) <|> (expressionTactic ["search"] ESearch ) <|> (do reserved "doc" doc <- (Right . fst <$> constant) <|> (Left . fst <$> fnName) eof return (EDocStr doc)) <?> "elab command" expressionTactic cmds tactic = do asum (map reserved cmds) t <- spaced (expr defaultSyntax) i <- get return $ tactic (desugar defaultSyntax i t) spaced parser = indentPropHolds gtProp *> parser -- | Parse module header and imports parseImports :: FilePath -> String -> Idris (Maybe (Docstring ()), [String], [ImportInfo], Maybe Delta) parseImports fname input = do i <- getIState case parseString (runInnerParser (evalStateT imports i)) (Directed (UTF8.fromString fname) 0 0 0 0) input of Failure (ErrInfo err _) -> fail (show err) Success (x, annots, i) -> do putIState i fname' <- runIO $ Dir.makeAbsolute fname sendHighlighting $ addPath annots fname' return x where imports :: IdrisParser ((Maybe (Docstring ()), [String], [ImportInfo], Maybe Delta), [(FC, OutputAnnotation)], IState) imports = do whiteSpace (mdoc, mname, annots) <- moduleHeader ps_exp <- many import_ mrk <- mark isEof <- lookAheadMatches eof let mrk' = if isEof then Nothing else Just mrk i <- get -- add Builtins and Prelude, unless options say -- not to let ps = ps_exp -- imp "Builtins" : imp "Prelude" : ps_exp return ((mdoc, mname, ps, mrk'), annots, i) imp m = ImportInfo False (toPath m) Nothing [] NoFC NoFC ns = Spl.splitOn "." toPath = foldl1' (</>) . ns addPath :: [(FC, OutputAnnotation)] -> FilePath -> [(FC, OutputAnnotation)] addPath [] _ = [] addPath ((fc, AnnNamespace ns Nothing) : annots) path = (fc, AnnNamespace ns (Just path)) : addPath annots path addPath (annot:annots) path = annot : addPath annots path -- | There should be a better way of doing this... findFC :: Doc -> (FC, String) findFC x = let s = show (plain x) in findFC' s where findFC' s = case span (/= ':') s of -- Horrid kludge to prevent crashes on Windows (prefix, ':':'\\':rest) -> case findFC' rest of (NoFC, msg) -> (NoFC, msg) (FileFC f, msg) -> (FileFC (prefix ++ ":\\" ++ f), msg) (FC f start end, msg) -> (FC (prefix ++ ":\\" ++ f) start end, msg) (failname, ':':rest) -> case span isDigit rest of (line, ':':rest') -> case span isDigit rest' of (col, ':':msg) -> let pos = (read line, read col) in (FC failname pos pos, msg) -- | Check if the coloring matches the options and corrects if necessary fixColour :: Bool -> ANSI.Doc -> ANSI.Doc fixColour False doc = ANSI.plain doc fixColour True doc = doc -- | A program is a list of declarations, possibly with associated -- documentation strings. parseProg :: SyntaxInfo -> FilePath -> String -> Maybe Delta -> Idris [PDecl] parseProg syn fname input mrk = do i <- getIState case runparser mainProg i fname input of Failure (ErrInfo doc _) -> do -- FIXME: Get error location from trifecta -- this can't be the solution! -- Issue #1575 on the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1575 let (fc, msg) = findFC doc i <- getIState case idris_outputmode i of RawOutput h -> iputStrLn (show $ fixColour (idris_colourRepl i) doc) IdeMode n h -> iWarn fc (P.text msg) putIState (i { errSpan = Just fc }) return [] Success (x, i) -> do putIState i reportParserWarnings return $ collect x where mainProg :: IdrisParser ([PDecl], IState) mainProg = case mrk of Nothing -> do i <- get; return ([], i) Just mrk -> do release mrk ds <- prog syn i' <- get return (ds, i') {-| Load idris module and show error if something wrong happens -} loadModule :: FilePath -> IBCPhase -> Idris (Maybe String) loadModule f phase = idrisCatch (loadModule' f phase) (\e -> do setErrSpan (getErrSpan e) ist <- getIState iWarn (getErrSpan e) $ pprintErr ist e return Nothing) {-| Load idris module -} loadModule' :: FilePath -> IBCPhase -> Idris (Maybe String) loadModule' f phase = do i <- getIState let file = takeWhile (/= ' ') f ibcsd <- valIBCSubDir i ids <- allImportDirs fp <- findImport ids ibcsd file if file `elem` imported i then do logParser 1 $ "Already read " ++ file return Nothing else do putIState (i { imported = file : imported i }) case fp of IDR fn -> loadSource False fn Nothing LIDR fn -> loadSource True fn Nothing IBC fn src -> idrisCatch (loadIBC True phase fn) (\c -> do logParser 1 $ fn ++ " failed " ++ pshow i c case src of IDR sfn -> loadSource False sfn Nothing LIDR sfn -> loadSource True sfn Nothing) return $ Just file {-| Load idris code from file -} loadFromIFile :: Bool -> IBCPhase -> IFileType -> Maybe Int -> Idris () loadFromIFile reexp phase i@(IBC fn src) maxline = do logParser 1 $ "Skipping " ++ getSrcFile i idrisCatch (loadIBC reexp phase fn) (\err -> ierror $ LoadingFailed fn err) where getSrcFile (IDR fn) = fn getSrcFile (LIDR fn) = fn getSrcFile (IBC f src) = getSrcFile src loadFromIFile _ _ (IDR fn) maxline = loadSource' False fn maxline loadFromIFile _ _ (LIDR fn) maxline = loadSource' True fn maxline {-| Load idris source code and show error if something wrong happens -} loadSource' :: Bool -> FilePath -> Maybe Int -> Idris () loadSource' lidr r maxline = idrisCatch (loadSource lidr r maxline) (\e -> do setErrSpan (getErrSpan e) ist <- getIState case e of At f e' -> iWarn f (pprintErr ist e') _ -> iWarn (getErrSpan e) (pprintErr ist e)) {-| Load Idris source code-} loadSource :: Bool -> FilePath -> Maybe Int -> Idris () loadSource lidr f toline = do logParser 1 ("Reading " ++ f) i <- getIState let def_total = default_total i file_in <- runIO $ readSource f file <- if lidr then tclift $ unlit f file_in else return file_in (mdocs, mname, imports_in, pos) <- parseImports f file ai <- getAutoImports let imports = map (\n -> ImportInfo True n Nothing [] NoFC NoFC) ai ++ imports_in ids <- allImportDirs ibcsd <- valIBCSubDir i mapM_ (\(re, f, ns, nfc) -> do fp <- findImport ids ibcsd f case fp of LIDR fn -> ifail $ "No ibc for " ++ f IDR fn -> ifail $ "No ibc for " ++ f IBC fn src -> do loadIBC True IBC_Building fn let srcFn = case src of IDR fn -> Just fn LIDR fn -> Just fn _ -> Nothing srcFnAbs <- case srcFn of Just fn -> fmap Just (runIO $ Dir.makeAbsolute fn) Nothing -> return Nothing sendHighlighting [(nfc, AnnNamespace ns srcFnAbs)]) [(re, fn, ns, nfc) | ImportInfo re fn _ ns _ nfc <- imports] reportParserWarnings sendParserHighlighting -- process and check module aliases let modAliases = M.fromList [ (prep alias, prep realName) | ImportInfo { import_reexport = reexport , import_path = realName , import_rename = Just (alias, _) , import_location = fc } <- imports ] prep = map T.pack . reverse . Spl.splitOn [pathSeparator] aliasNames = [ (alias, fc) | ImportInfo { import_rename = Just (alias, _) , import_location = fc } <- imports ] histogram = groupBy ((==) `on` fst) . sortBy (comparing fst) $ aliasNames case map head . filter ((/= 1) . length) $ histogram of [] -> logParser 3 $ "Module aliases: " ++ show (M.toList modAliases) (n,fc):_ -> throwError . At fc . Msg $ "import alias not unique: " ++ show n i <- getIState putIState (i { default_access = Private, module_aliases = modAliases }) clearIBC -- start a new .ibc file -- record package info in .ibc imps <- allImportDirs mapM_ addIBC (map IBCImportDir imps) mapM_ (addIBC . IBCImport) [ (reexport, realName) | ImportInfo { import_reexport = reexport , import_path = realName } <- imports ] let syntax = defaultSyntax{ syn_namespace = reverse mname, maxline = toline } ist <- getIState -- Save the span from parsing the module header, because -- an empty program parse might obliterate it. let oldSpan = idris_parsedSpan ist ds' <- parseProg syntax f file pos case (ds', oldSpan) of ([], Just fc) -> -- If no program elements were parsed, we dind't -- get a loaded region in the IBC file. That -- means we need to add it back. do ist <- getIState putIState ist { idris_parsedSpan = oldSpan , ibc_write = IBCParsedRegion fc : ibc_write ist } _ -> return () sendParserHighlighting -- Parsing done, now process declarations let ds = namespaces mname ds' logParser 3 (show $ showDecls verbosePPOption ds) i <- getIState logLvl 10 (show (toAlist (idris_implicits i))) logLvl 3 (show (idris_infixes i)) -- Now add all the declarations to the context v <- verbose when v $ iputStrLn $ "Type checking " ++ f -- we totality check after every Mutual block, so if -- anything is a single definition, wrap it in a -- mutual block on its own elabDecls (toplevelWith f) (map toMutual ds) i <- getIState -- simplify every definition do give the totality checker -- a better chance mapM_ (\n -> do logLvl 5 $ "Simplifying " ++ show n ctxt' <- do ctxt <- getContext tclift $ simplifyCasedef n (getErasureInfo i) ctxt setContext ctxt') (map snd (idris_totcheck i)) -- build size change graph from simplified definitions logLvl 1 "Totality checking" i <- getIState mapM_ buildSCG (idris_totcheck i) mapM_ checkDeclTotality (idris_totcheck i) mapM_ verifyTotality (idris_totcheck i) -- Redo totality check for deferred names let deftots = idris_defertotcheck i logLvl 2 $ "Totality checking " ++ show deftots mapM_ (\x -> do tot <- getTotality x case tot of Total _ -> do let opts = case lookupCtxtExact x (idris_flags i) of Just os -> os Nothing -> [] when (AssertTotal `notElem` opts) $ setTotality x Unchecked _ -> return ()) (map snd deftots) mapM_ buildSCG deftots mapM_ checkDeclTotality deftots logLvl 1 ("Finished " ++ f) ibcsd <- valIBCSubDir i logLvl 1 "Universe checking" iucheck let ibc = ibcPathNoFallback ibcsd f i <- getIState addHides (hide_list i) -- Save module documentation if applicable i <- getIState case mdocs of Nothing -> return () Just docs -> addModDoc syntax mname docs -- Finally, write an ibc and highlights if checking was successful ok <- noErrors when ok $ do idrisCatch (do writeIBC f ibc; clearIBC) (\c -> return ()) -- failure is harmless hl <- getDumpHighlighting when hl $ idrisCatch (writeHighlights f) (const $ return ()) -- failure is harmless clearHighlights i <- getIState putIState (i { default_total = def_total, hide_list = emptyContext }) return () where namespaces :: [String] -> [PDecl] -> [PDecl] namespaces [] ds = ds namespaces (x:xs) ds = [PNamespace x NoFC (namespaces xs ds)] toMutual :: PDecl -> PDecl toMutual m@(PMutual _ d) = m toMutual (PNamespace x fc ds) = PNamespace x fc (map toMutual ds) toMutual x = let r = PMutual (fileFC "single mutual") [x] in case x of PClauses{} -> r PClass{} -> r PData{} -> r PInstance{} -> r _ -> x addModDoc :: SyntaxInfo -> [String] -> Docstring () -> Idris () addModDoc syn mname docs = do ist <- getIState docs' <- elabDocTerms (toplevelWith f) (parsedDocs ist) let modDocs' = addDef docName docs' (idris_moduledocs ist) putIState ist { idris_moduledocs = modDocs' } addIBC (IBCModDocs docName) where docName = NS modDocName (map T.pack (reverse mname)) parsedDocs ist = annotCode (tryFullExpr syn ist) docs {-| Adds names to hide list -} addHides :: Ctxt Accessibility -> Idris () addHides xs = do i <- getIState let defh = default_access i mapM_ doHide (toAlist xs) where doHide (n, a) = do setAccessibility n a addIBC (IBCAccess n a)
ozgurakgun/Idris-dev
src/Idris/Parser.hs
bsd-3-clause
73,180
483
26
30,373
15,473
8,415
7,058
1,271
27
{-# LANGUAGE DuplicateRecordFields #-} module Jerimum.Environment -- * Types ( Key , Environment , ReplDatabaseEnvironment(..) , SnapshotDatabaseEnvironment(..) , StorageDriverEnvironment(..) , StorageServerEnvironment(..) , SnapshotServerEnvironment(..) -- * Combinators , envString , envStringDefault -- * Constructors , getReplDatabaseEnvironment , getStorageDriverEnvironment , getStorageServerEnvironment , getSnapshotServerEnvironment -- * High-level API , storageServerSystemEnv , snapshotServerSystemEnv ) where import Control.Monad.Logger import Control.Monad.Reader import Data.String import System.Environment type Key = String type Environment = [(Key, String)] type EnvironmentR a = Reader Environment (Either String a) data ReplDatabaseEnvironment = ReplDatabaseEnvironment { slot :: String , dburl :: String } deriving (Eq, Show) newtype SnapshotDatabaseEnvironment = SnapshotDatabaseEnvironment { dburl :: String } deriving (Eq, Show) data StorageDriverEnvironment = PostgresDriverEnvironment { dburl :: String } | DevNullDriverEnvironment deriving (Eq, Show) data StorageServerEnvironment = StorageServerEnvironment { replDatabaseEnvironment :: ReplDatabaseEnvironment , storageDriverEnvironment :: StorageDriverEnvironment , loggingLevel :: LogLevel } deriving (Eq, Show) data SnapshotServerEnvironment = SnapshotServerEnvironment { replDatabaseEnvironment :: ReplDatabaseEnvironment , storageDriverEnvironment :: StorageDriverEnvironment , snapshotDatabaseEnvironment :: SnapshotDatabaseEnvironment } noKeyError :: Key -> Either String a noKeyError key = Left ("env `" ++ fromString key ++ "' is missing") badValueError :: Key -> String -> Either String a badValueError key val = Left ("bad value: `" ++ fromString val ++ "' for env `" ++ fromString key ++ "'") envString :: Key -> EnvironmentR String envString key = ask >>= \env -> pure $ maybe (noKeyError key) Right (lookup key env) envStringDefault :: Key -> String -> EnvironmentR String envStringDefault key defvalue = either (const $ Right defvalue) Right <$> envString key getSnapshotDatabaseEnvironment :: EnvironmentR SnapshotDatabaseEnvironment getSnapshotDatabaseEnvironment = do dburl <- envString "jerimum_snapshot_dburl" pure $ SnapshotDatabaseEnvironment <$> dburl getReplDatabaseEnvironment :: EnvironmentR ReplDatabaseEnvironment getReplDatabaseEnvironment = do slot <- envString "jerimum_repl_slot" dburl <- envString "jerimum_repl_dburl" pure $ ReplDatabaseEnvironment <$> slot <*> dburl getSnapshotReplDatabaseEnvironment :: EnvironmentR ReplDatabaseEnvironment getSnapshotReplDatabaseEnvironment = do slot <- envString "jerimum_snapshot_repl_slot" dburl <- envString "jerimum_snapshot_repl_dburl" pure $ ReplDatabaseEnvironment <$> slot <*> dburl getStorageDriverEnvironment :: EnvironmentR StorageDriverEnvironment getStorageDriverEnvironment = do let driverKey = "jerimum_storage_driver" mdriver <- envString driverKey case mdriver of Right "postgres" -> do dburl <- envString "jerimum_storage_postgres_dburl" pure (PostgresDriverEnvironment <$> dburl) Right "devnull" -> pure $ Right DevNullDriverEnvironment Right driver -> pure $ badValueError driverKey driver Left e -> pure (Left e) getLogLevel :: EnvironmentR LogLevel getLogLevel = readLogLevel <$> envString "jerimum_loglevel" where readLogLevel (Right "debug") = Right LevelDebug readLogLevel (Right "info") = Right LevelInfo readLogLevel (Right "warn") = Right LevelWarn readLogLevel (Right "warning") = Right LevelWarn readLogLevel (Right "error") = Right LevelError readLogLevel (Right badvalue) = badValueError "jerimum_loglevel" badvalue readLogLevel (Left e) = Left e getStorageServerEnvironment :: EnvironmentR StorageServerEnvironment getStorageServerEnvironment = do replDbEnv <- getReplDatabaseEnvironment storageEnv <- getStorageDriverEnvironment loglevel <- getLogLevel pure $ StorageServerEnvironment <$> replDbEnv <*> storageEnv <*> loglevel storageServerSystemEnv :: IO (Either String StorageServerEnvironment) storageServerSystemEnv = runReader getStorageServerEnvironment <$> getEnvironment getSnapshotServerEnvironment :: EnvironmentR SnapshotServerEnvironment getSnapshotServerEnvironment = do snapshotDbEnv <- getSnapshotDatabaseEnvironment replDbEnv <- getSnapshotReplDatabaseEnvironment storageEnv <- getStorageDriverEnvironment pure $ SnapshotServerEnvironment <$> replDbEnv <*> storageEnv <*> snapshotDbEnv snapshotServerSystemEnv :: IO (Either String SnapshotServerEnvironment) snapshotServerSystemEnv = runReader getSnapshotServerEnvironment <$> getEnvironment
dgvncsz0f/nws
src/Jerimum/Environment.hs
bsd-3-clause
4,798
0
14
746
1,046
542
504
109
7
module Language.CIL.Types ( Name , Type (..) , Expr (..) , Init (..) , Apply (..) ) where import Language.C hiding (Name) -- | Identifiers. type Name = String -- | Types. data Type = Void | Array Int Type | Ptr Type | Volatile Type -- ^ A volatile qualified type. | Typedef Type | Struct [(Name, Type)] | Union [(Name, Type)] | Enum [(Name, Int)] | BitField Type [(Name, Int)] | StructRef Name -- ^ Reference to a struct type. | UnionRef Name -- ^ Reference to a union type. | EnumRef Name -- ^ Reference to an enum type. | TypedefRef Name -- ^ Reference to a previously defined typedef. | Function Type [Type] | Int8 | Int16 | Int32 | Word8 | Word16 | Word32 | Float | Double deriving (Show, Eq) -- | Expressions. data Expr = ConstInt Int Position | ConstFloat Double Position | ConstChar Char Position | ConstString String Position | Var Name Position -- ^ Variable reference. | Mul Expr Expr Position -- ^ a * b | Div Expr Expr Position -- ^ a / b | Rmd Expr Expr Position -- ^ a % b | Add Expr Expr Position -- ^ a + b | Sub Expr Expr Position -- ^ a - b | Shl Expr Expr Position -- ^ a << b | Shr Expr Expr Position -- ^ a >> b | Lt Expr Expr Position -- ^ a < b | Gt Expr Expr Position -- ^ a > b | Le Expr Expr Position -- ^ a <= b | Ge Expr Expr Position -- ^ a >= b | Eq Expr Expr Position -- ^ a == b | Neq Expr Expr Position -- ^ a != b | And Expr Expr Position -- ^ a & b | Xor Expr Expr Position -- ^ a ^ b | Or Expr Expr Position -- ^ a | b | Adr Expr Position -- ^ &a | Ind Expr Position -- ^ \*a | Minus Expr Position -- ^ \-a | Comp Expr Position -- ^ ~a | Neg Expr Position -- ^ !a | Cast Type Expr Position -- ^ (...) a | Index Expr Expr Position -- ^ a[b] | Mem Expr Name Position -- ^ a.name | MemInd Expr Name Position -- ^ a->name | SizeT Type Position -- ^ sizeof(type) | SizeE Expr Position -- ^ sizeof(expr) deriving (Show, Eq) -- | Initialization expressions. data Init = Init Expr | InitList [Init] deriving (Show, Eq) -- | Function application. data Apply = Apply Expr [Expr] deriving (Show, Eq) instance Pos Expr where posOf a = case a of ConstInt _ p -> p ConstFloat _ p -> p ConstChar _ p -> p ConstString _ p -> p Var _ p -> p Mul _ _ p -> p Div _ _ p -> p Rmd _ _ p -> p Add _ _ p -> p Sub _ _ p -> p Shl _ _ p -> p Shr _ _ p -> p Lt _ _ p -> p Gt _ _ p -> p Le _ _ p -> p Ge _ _ p -> p Eq _ _ p -> p Neq _ _ p -> p And _ _ p -> p Xor _ _ p -> p Or _ _ p -> p Adr _ p -> p Ind _ p -> p Minus _ p -> p Comp _ p -> p Neg _ p -> p Cast _ _ p -> p Index _ _ p -> p Mem _ _ p -> p MemInd _ _ p -> p SizeT _ p -> p SizeE _ p -> p
tomahawkins/cil
Language/CIL/Types.hs
bsd-3-clause
3,173
0
9
1,243
991
547
444
105
0
-- DrawHilbertCurve.hs {-# OPTIONS_GHC -Wall #-} module Main where import System.Environment(getArgs) import Lab2.HilbertCurve imageSize :: Num a => a imageSize = 500 main :: IO () main = do args <- getArgs let nLevels | length args > 0 = read (head args) | otherwise = 3 :: Int drawHilbertCurve imageSize nLevels
ghorn/cs240h-class
Lab2/DrawHilbertCurve.hs
bsd-3-clause
347
0
14
85
111
56
55
13
1
module BP.InferSpec where import BP.Ast import BP.Type import BP.Infer import BP.Env import State (resetId, resetUniqueName) import Control.Monad (foldM) import qualified Text.PrettyPrint as PP import qualified Data.Set as S import Test.Hspec runInferSpecCase :: Term -> String -> IO () runInferSpecCase expr expect = do assumps <- assumptions (_, t) <- analyze expr assumps S.empty resetId resetUniqueName (PP.text . show $ t) `shouldBe` PP.text expect runInferSpecCases :: [Term] -> [String] -> IO () runInferSpecCases exprs expects = do assumps <- assumptions (_, types) <- foldM (\(env, types) expr -> do (env', ty) <- analyze expr env S.empty return (env', types ++ [ty])) (assumps, []) exprs resetId resetUniqueName (map (PP.text . show) types) `shouldBe` map PP.text expects failInferSpecCase :: Term -> String -> IO () failInferSpecCase expr error = do assumps <- assumptions analyze expr assumps S.empty `shouldThrow` errorCall error resetId resetUniqueName spec :: Spec spec = describe "inference test" $ it "should inference type of given term" $ do -- recursive type runInferSpecCase (LetRec "factorial" (Lambda "n" $ Apply (Apply (Apply (Ident "cond") $ Apply (Ident "zero?") $ Ident "n") $ Ident "1") (Apply (Apply (Ident "times") $ Ident "n") $ Apply (Ident "factorial") $ Apply (Ident "pred") $ Ident "n")) $ Apply (Ident "factorial") $ Ident "5") "int" failInferSpecCase (Lambda "x" $ Apply (Apply (Ident "pair") $ Apply (Ident "x") $ Ident "3") $ Apply (Ident "x") $ Ident "true") "Type mismatch bool ≠ int" failInferSpecCase (Apply (Apply (Ident "pair") $ Apply (Ident "g") $ Ident "3") $ Apply (Ident "g") $ Ident "true") "Undefined symbol g" runInferSpecCase (Lambda "x" $ Ident "x") "(α → α)" runInferSpecCase (Apply (Ident "zero?") $ Ident "3") "bool" -- let polymorphism runInferSpecCase (Let "f" (Lambda "x" $ Ident "x") pairE) "(int * bool)" failInferSpecCase (Lambda "f" $ Apply (Ident "f") $ Ident "f") "Recusive unification" runInferSpecCase (Let "g" (Lambda "f" $ Ident"5") $ Apply (Ident "g") $ Ident "g") "int" -- bound variable of lambda expression is non-generic and bound variable of let expression is generic runInferSpecCase (Lambda "g" $ Let "f" (Lambda "x" $ Ident "g") $ Apply (Apply (Ident "pair") $ Apply (Ident "f") $ Ident "3") $ Apply (Ident "f") $ Ident "true") "(α → (α * α))" -- function composition maybe the inferred types should be normalized runInferSpecCase (Lambda "f" $ Lambda "g" $ Lambda "arg" $ Apply (Ident "f") $ Apply (Ident "g") $ Ident "arg") "((α → β) → ((γ → α) → (γ → β)))" runInferSpecCase pairE "(int * bool)" runInferSpecCase (Apply (Ident "f") $ Ident "3") "int" runInferSpecCase (Apply (Ident "f") $ Ident "true") "bool" runInferSpecCase (Let "f" (Lambda "x" $ Ident "x") $ Apply (Ident "f") $ Ident "3") "int" runInferSpecCase (Function "implicitParamType" [Param "x" Nothing] (Ident "x") Nothing) "(α → α)" runInferSpecCase (Function "explicitParamType" [Param "x" (Just intT)] (Ident "x") Nothing) "(int → int)" runInferSpecCase (Function "explicitReturnType" [Param "x" Nothing] (Ident "x") (Just intT)) "(int → int)" tvarA <- makeVariable -- not support higher rank types like FCP does runInferSpecCase (Function "explicitParamType" [Param "id" (Just $ functionT tvarA tvarA)] (Apply (Ident "id") $ Ident "3") Nothing) "((int → int) → int)" failInferSpecCase (Function "explicitParamType" [Param "id" (Just $ functionT tvarA tvarA)] (Apply (Apply (Ident "pair") $ Apply (Ident "id") $ Ident "3") $ Apply (Ident "id") $ Ident "true") Nothing) "Type mismatch bool ≠ int" -- support parametric polymorphism (basic polymorphism) runInferSpecCases [LetBinding "a" (Ident "10") (Just intT), LetBinding "b" (Ident "true") Nothing, LetBinding "id" (Lambda "x" $ Ident "x") Nothing, Call (Ident "id") [Ident "a"], Call (Ident "id") [Ident "b"]] ["int", "bool", "(α → α)", "int", "bool"] runInferSpecCases [LetBinding "a" (Ident "10") (Just intT), LetBinding "id" (Lambda "x" $ Ident "x") Nothing, Call (Ident "id") [Ident "a"]] ["int", "(α → α)", "int"] runInferSpecCases [LetBinding "a" (Ident "10") (Just intT), LetBinding "id" (Lambda "x" $ Ident "x") (Just $ functionT intT intT), Call (Ident "id") [Ident "a"]] ["int", "(int → int)", "int"] runInferSpecCases [LetBinding "a" (Ident "10") Nothing, LetBinding "id" (Lambda "x" $ Ident "x") (Just $ functionT intT intT), Call (Ident "id") [Ident "a"]] ["int", "(int → int)", "int"] runInferSpecCases [LetBinding "a" (Ident "10") Nothing, LetBinding "id" (Lambda "x" $ Ident "x") (Just $ functionMT [intT] intT), Call (Ident "id") [Ident "a"]] ["int", "(int → int)", "int"]
zjhmale/HMF
test/BP/InferSpec.hs
bsd-3-clause
5,614
0
25
1,670
1,894
918
976
78
1
-- | Convenience functions for some common operations with teams. Execute the result of these -- functions using 'runGitHub' or 'runGitHub'' module Network.Octohat ( addUserToTeam , membersOfTeamInOrganization , keysOfTeamInOrganization , teamForTeamNameInOrg) where import Control.Error.Safe (tryHead) import Control.Monad (liftM) import qualified Data.Text as T import Network.Octohat.Keys import Network.Octohat.Members import Network.Octohat.Types -- | Gets all the members of the organization membersOfTeamInOrganization :: OrganizationName -- ^ GitHub organization name -> TeamName -- ^ GitHub team name -> GitHub [Member] membersOfTeamInOrganization nameOfOrg nameOfTeam = teamId `liftM` teamForTeamNameInOrg nameOfOrg nameOfTeam >>= membersForTeam -- | Adds a user with @nameOfUser@ to the team named @nameOfTeam@ within the organization named `nameOfOrg` addUserToTeam :: T.Text -- ^ GitHub username -> OrganizationName -- ^ GitHub organization name -> TeamName -- ^ GitHub team name -> GitHub StatusInTeam addUserToTeam nameOfUser nameOfOrg nameOfTeam = teamId `liftM` teamForTeamNameInOrg nameOfOrg nameOfTeam >>= addMemberToTeam nameOfUser -- | Retrieves a list of members in a given team within an organization together with their public keys keysOfTeamInOrganization :: OrganizationName -- ^ GitHub organization name -> TeamName -- ^ GitHub team name -> GitHub [MemberWithKey] keysOfTeamInOrganization nameOfOrg nameOfTeam = do members <- membersOfTeamInOrganization nameOfOrg nameOfTeam pubKeys <- mapM keysForMember members let memberFingerprints = publicKeySetToFingerprints pubKeys return $ makeMembersWithKey members pubKeys memberFingerprints teamForTeamNameInOrg :: OrganizationName -- ^ Organization name -> TeamName -- ^ Team name -> GitHub Team teamForTeamNameInOrg nameOfOrg nameOfTeam = do teams <- teamsForOrganization nameOfOrg tryHead NotFound (teamsWithName (unTeamName nameOfTeam) teams) teamsWithName :: T.Text -> [Team] -> [Team] teamsWithName nameOfTeam = filter (hasName nameOfTeam) hasName :: T.Text -> Team -> Bool hasName name team = name == teamName team keysForMember :: Member -> GitHub [PublicKey] keysForMember = publicKeysForUser . memberLogin makeMembersWithKey :: [Member] -> [[PublicKey]] -> [[PublicKeyFingerprint]] -> [MemberWithKey] makeMembersWithKey = zipWith3 MemberWithKey publicKeySetToFingerprints :: [[PublicKey]] -> [[PublicKeyFingerprint]] publicKeySetToFingerprints = (map.map) fingerprintFor
stackbuilders/octohat
src/Network/Octohat.hs
mit
2,772
0
11
615
485
264
221
43
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DuplicateRecordFields #-} module Language.LSP.Types.Command where import Data.Aeson import Data.Aeson.TH import Data.Text import Language.LSP.Types.Common import Language.LSP.Types.Progress import Language.LSP.Types.Utils -- ------------------------------------- data ExecuteCommandClientCapabilities = ExecuteCommandClientCapabilities { _dynamicRegistration :: Maybe Bool -- ^Execute command supports dynamic -- registration. } deriving (Show, Read, Eq) deriveJSON lspOptions ''ExecuteCommandClientCapabilities -- ------------------------------------- makeExtendingDatatype "ExecuteCommandOptions" [''WorkDoneProgressOptions] [("_commands", [t| List Text |])] deriveJSON lspOptions ''ExecuteCommandOptions makeExtendingDatatype "ExecuteCommandRegistrationOptions" [''ExecuteCommandOptions] [] deriveJSON lspOptions ''ExecuteCommandRegistrationOptions -- ------------------------------------- makeExtendingDatatype "ExecuteCommandParams" [''WorkDoneProgressParams] [ ("_command", [t| Text |]) , ("_arguments", [t| Maybe (List Value) |]) ] deriveJSON lspOptions ''ExecuteCommandParams data Command = Command { -- | Title of the command, like @save@. _title :: Text , -- | The identifier of the actual command handler. _command :: Text , -- | Arguments that the command handler should be invoked with. _arguments :: Maybe (List Value) } deriving (Show, Read, Eq) deriveJSON lspOptions ''Command
alanz/haskell-lsp
lsp-types/src/Language/LSP/Types/Command.hs
mit
1,629
0
11
334
275
160
115
30
0
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 1.0//EN" "http://java.sun.com/products/javahelp/helpset_1_0.dtd"> <helpset version="1.0"> <title>Geometria 3.0</title> <maps> <homeID>top</homeID> <mapref location="jhelpmap.jhm"/> </maps> <view> <name>TOC</name> <label>Table Of Contents</label> <type>javax.help.TOCView</type> <data>jhelptoc.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> <presentation default=true> <name>mainWindow</name> <location x="100" y="100"/> <size width="700" height="600"/> <toolbar> <helpaction image="backicon">javax.help.BackAction</helpaction> <helpaction image="forwardicon">javax.help.ForwardAction</helpaction> <helpaction image="homeicon">javax.help.HomeAction</helpaction> <helpaction image="printicon">javax.help.PrintAction</helpaction> </toolbar> </presentation> </helpset>
stelian56/geometria
archive/3.2/javahelp/jhelpset.hs
mit
1,155
87
64
163
464
228
236
-1
-1
module Network.StandardPolicy ( elect , availableWifisWithLogs , alreadyUsedWifisWithLogs , connectWifiWithLogs , scanAndConnectToKnownWifiWithMostPowerfulSignal , availableWifis , alreadyUsedWifis , connectToWifi , connectWifi , electedWifi , createNewWifiConnectionAndConnect , createWifiWithLogs) where ----------------------------------------------------------------------------- -- | -- Module : Network.Main -- Copyright : (c) Commiters -- License : The same as `nmcli` - http://manpages.ubuntu.com/manpages/maverick/man1/nmcli.1.html -- -- Maintainer : massyl, ardumont -- Stability : experimental -- Portability : unportable -- Dependency : nmcli (network-manager package in debian-based platform - http://www.gnome.org/projects/NetworkManager/) -- -- A standard policy connection module. -- Determine the most powerful wifi signal amongst known auto-connect wifi and try and connect to it. -- ----------------------------------------------------------------------------- import Control.Applicative ((<*>)) import Control.Exception (evaluate) import Control.Monad (join) import Data.Functor ((<$>)) import Network.HWifi (alreadyUsed, available, connectToWifi, createNewWifi, runWifiMonad, unsafeElect) import Network.Types (Command (..), Log, Psk, SSID, ThrowsError) -- | Elects wifi safely (runs in `IO` monad) elect :: ThrowsError [SSID] -> ThrowsError [SSID] -> IO (ThrowsError SSID) elect wifis = evaluate . unsafeElect wifis -- | Returns the available network wifi list and records any logged message availableWifisWithLogs :: Command -> IO (ThrowsError [SSID], [Log]) availableWifisWithLogs = runWifiMonad . available -- | Returns already used network wifi list and record any logged message. alreadyUsedWifisWithLogs :: Command -> IO (ThrowsError [SSID], [Log]) alreadyUsedWifisWithLogs = runWifiMonad . alreadyUsed -- | Connect to wifi connectWifiWithLogs :: Command -> ThrowsError SSID -> IO (ThrowsError [SSID], [Log]) connectWifiWithLogs cmd = runWifiMonad . connectToWifi cmd -- | Create a wifi connection and connect to it createWifiWithLogs :: Command -> SSID -> Psk -> IO (ThrowsError [SSID], [Log]) createWifiWithLogs cmd ssid psk = runWifiMonad $ createNewWifi cmd ssid psk -- | Log output output :: [Log]-> IO () output = mapM_ putStrLn -- | Scan and connect to a known wifi with the most powerful signal scanAndConnectToKnownWifiWithMostPowerfulSignal :: Command -> Command -> Command -> IO () scanAndConnectToKnownWifiWithMostPowerfulSignal scanCommand knownCommand conCommand = do (allWifis, msg0) <- availableWifisWithLogs scanCommand output msg0 (knownWifis, msg1) <- alreadyUsedWifisWithLogs knownCommand output msg1 (result, msg2) <- join $ connectWifiWithLogs conCommand <$> elect allWifis knownWifis case result of Left err -> putStrLn $ "\nError: " ++ show err Right _ -> output msg2 -- | Create a new wifi and connection and connect to it createNewWifiConnectionAndConnect :: Command -> SSID -> Psk -> IO () createNewWifiConnectionAndConnect cmd ssid psk = do (_, msg0) <- createWifiWithLogs cmd ssid psk output msg0 -- | Returns available network wifis. It discards any logged message. availableWifis :: Command -> IO (ThrowsError [SSID]) availableWifis scanCommand = fst <$> availableWifisWithLogs scanCommand -- | Returns already used network wifis. It discards any logged message. alreadyUsedWifis :: Command -> IO (ThrowsError [SSID]) alreadyUsedWifis knownCommand = fst <$> alreadyUsedWifisWithLogs knownCommand -- | Connection to a wifi connectWifi :: Command -> ThrowsError SSID -> IO (ThrowsError [SSID]) connectWifi cmd ssid = fst <$> connectWifiWithLogs cmd ssid -- | Returns elected wifi (wifi already known, available, with highest signal). electedWifi :: Command -> Command -> IO (ThrowsError SSID) electedWifi scanCommand knownCommand = join $ elect <$> alreadyUsedWifis knownCommand <*> availableWifis scanCommand
lambdatree/hWifi
Network/StandardPolicy.hs
gpl-2.0
4,396
0
11
1,024
794
429
365
53
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} ----------------------------------------------------------------- -- Autogenerated by Thrift -- -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated ----------------------------------------------------------------- module My.Namespacing.Test.Hsmodule_Types where import Prelude ( Bool(..), Enum, Float, IO, Double, String, Maybe(..), Eq, Show, Ord, concat, error, fromIntegral, fromEnum, length, map, maybe, not, null, otherwise, return, show, toEnum, enumFromTo, Bounded, minBound, maxBound, seq, (.), (&&), (||), (==), (++), ($), (-), (>>=), (>>)) import qualified Control.Applicative as Applicative (ZipList(..)) import Control.Applicative ( (<*>) ) import qualified Control.DeepSeq as DeepSeq import qualified Control.Exception as Exception import qualified Control.Monad as Monad ( liftM, ap, when ) import qualified Data.ByteString.Lazy as BS import Data.Functor ( (<$>) ) import qualified Data.Hashable as Hashable import qualified Data.Int as Int import qualified Data.Maybe as Maybe (catMaybes) import qualified Data.Text.Lazy.Encoding as Encoding ( decodeUtf8, encodeUtf8 ) import qualified Data.Text.Lazy as LT import qualified Data.Typeable as Typeable ( Typeable ) import qualified Data.HashMap.Strict as Map import qualified Data.HashSet as Set import qualified Data.Vector as Vector import qualified Test.QuickCheck.Arbitrary as Arbitrary ( Arbitrary(..) ) import qualified Test.QuickCheck as QuickCheck ( elements ) import qualified Thrift import qualified Thrift.Types as Types import qualified Thrift.Serializable as Serializable import qualified Thrift.Arbitraries as Arbitraries data HsFoo = HsFoo { hsFoo_MyInt :: Int.Int64 } deriving (Show,Eq,Typeable.Typeable) instance Serializable.ThriftSerializable HsFoo where encode = encode_HsFoo decode = decode_HsFoo instance Hashable.Hashable HsFoo where hashWithSalt salt record = salt `Hashable.hashWithSalt` hsFoo_MyInt record instance DeepSeq.NFData HsFoo where rnf _record0 = DeepSeq.rnf (hsFoo_MyInt _record0) `seq` () instance Arbitrary.Arbitrary HsFoo where arbitrary = Monad.liftM HsFoo (Arbitrary.arbitrary) shrink obj | obj == default_HsFoo = [] | otherwise = Maybe.catMaybes [ if obj == default_HsFoo{hsFoo_MyInt = hsFoo_MyInt obj} then Nothing else Just $ default_HsFoo{hsFoo_MyInt = hsFoo_MyInt obj} ] from_HsFoo :: HsFoo -> Types.ThriftVal from_HsFoo record = Types.TStruct $ Map.fromList $ Maybe.catMaybes [ (\_v3 -> Just (1, ("MyInt",Types.TI64 _v3))) $ hsFoo_MyInt record ] write_HsFoo :: (Thrift.Protocol p, Thrift.Transport t) => p t -> HsFoo -> IO () write_HsFoo oprot record = Thrift.writeVal oprot $ from_HsFoo record encode_HsFoo :: (Thrift.Protocol p, Thrift.Transport t) => p t -> HsFoo -> BS.ByteString encode_HsFoo oprot record = Thrift.serializeVal oprot $ from_HsFoo record to_HsFoo :: Types.ThriftVal -> HsFoo to_HsFoo (Types.TStruct fields) = HsFoo{ hsFoo_MyInt = maybe (hsFoo_MyInt default_HsFoo) (\(_,_val5) -> (case _val5 of {Types.TI64 _val6 -> _val6; _ -> error "wrong type"})) (Map.lookup (1) fields) } to_HsFoo _ = error "not a struct" read_HsFoo :: (Thrift.Transport t, Thrift.Protocol p) => p t -> IO HsFoo read_HsFoo iprot = to_HsFoo <$> Thrift.readVal iprot (Types.T_STRUCT typemap_HsFoo) decode_HsFoo :: (Thrift.Protocol p, Thrift.Transport t) => p t -> BS.ByteString -> HsFoo decode_HsFoo iprot bs = to_HsFoo $ Thrift.deserializeVal iprot (Types.T_STRUCT typemap_HsFoo) bs typemap_HsFoo :: Types.TypeMap typemap_HsFoo = Map.fromList [("MyInt",(1,Types.T_I64))] default_HsFoo :: HsFoo default_HsFoo = HsFoo{ hsFoo_MyInt = 0}
sinjar666/fbthrift
thrift/compiler/test/fixtures/namespace/gen-hs/My/Namespacing/Test/Hsmodule_Types.hs
apache-2.0
4,078
0
15
690
1,117
664
453
73
2
module HsLexer {-# DEPRECATED "This module has moved to Language.Haskell.Lexer" #-} (module Language.Haskell.Lexer) where import Language.Haskell.Lexer
FranklinChen/hugs98-plus-Sep2006
fptools/hslibs/hssource/HsLexer.hs
bsd-3-clause
152
0
5
16
20
14
6
4
0
{-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE NoMonoPatBinds #-} {- | Module : Data.ML.Search Description : Optimum search. Copyright : (c) Paweł Nowak License : MIT Maintainer : pawel834@gmail.com Stability : experimental -} module Data.ML.Search where import Data.ML.Cost import Data.ML.Model import Linear -- | Adaptive gradient descent working on batches. adaGrad :: RealFloat a => Model m => Additive m => Traversable m => Foldable f => Functor f => [f (Input m a, Output m a)] -- ^ List of mini batches -> Cost m -- ^ The cost function. -> m a -- ^ Starting point. -> [(a, m a)] -- ^ A list of models with their cost. adaGrad i cost m0 = tail $ fmap (\(j, m, _, _) -> (j, m)) $ scanl step (0, m0, m0, zero) i where -- (prevCost, prevModel, model, historicalGrad) step (_, _, model, historicalGrad) batch = let -- Compute the gradient on this batch. (j, g) = evalCostGrad cost batch model -- Update the accumulated gradient. historicalGrad' = historicalGrad ^+^ liftU2 (*) g g -- Adjust the current gradient. adjustedGrad = liftI2 (/) g (fmap (\x -> sqrt (x + fudgeFactor)) historicalGrad') -- Compute the new model. model' = model ^-^ stepSize *^ adjustedGrad in (j, model, model', historicalGrad') fudgeFactor = 1e-6 stepSize = 1e-1
bitemyapp/machine-learning
src/Data/ML/Search.hs
mit
1,585
0
18
493
346
195
151
27
1
------------------------------------------------------------------------------- -- | -- Module : System.Hardware.Haskino.SamplePrograms.Rewrite.TransRecurLetTestE -- Copyright : (c) University of Kansas -- License : BSD3 -- Stability : experimental -- -- Recursion test example used for rewrite written in shallow version. ------------------------------------------------------------------------------- module System.Hardware.Haskino.SamplePrograms.Rewrite.TransRecurLetTestE(recurProgE) where import Prelude hiding ((<*)) import System.Hardware.Haskino import Control.Monad import Control.Monad.Fix import Data.Word import Data.Boolean data Key = KeyNone | KeyRight | KeyLeft | KeyUp | KeyDown | KeySelect deriving (Enum) keyValue :: Key -> Word8 keyValue k = fromIntegral $ fromEnum k led = 6 button1 = 2 button2 = 3 analogKey :: Arduino (Expr Word8) analogKey = iterateE LitUnit (\x -> do v <- analogReadE button2 ifThenElseEither (v <* 30) (return (ExprRight (lit (keyValue KeyRight)))) (ifThenElseEither (v <* 150) (return (ExprRight (lit (keyValue KeyUp)))) (ifThenElseEither (v <* 350) (return (ExprRight (lit (keyValue KeyDown)))) (ifThenElseEither (v <* 535) (return (ExprRight (lit (keyValue KeyLeft)))) (ifThenElseEither (v <* 760) (return (ExprRight (lit (keyValue KeySelect)))) (return (ExprLeft LitUnit))))))) recurProgE :: Arduino (Expr ()) recurProgE = do setPinModeE led OUTPUT setPinModeE button1 INPUT setPinModeE button2 INPUT wait blink 2 wait blink 3 return LitUnit where wait :: Arduino (Expr ()) wait = iterateE LitUnit (\x -> do b <- digitalReadE button1 ifThenElseEither b (return (ExprRight LitUnit)) (return (ExprLeft LitUnit))) blink :: Expr Word8 -> Arduino ( Expr () ) blink t = iterateE t (\x -> do ifThenElseEither (x `eqE` 0) (return (ExprRight LitUnit)) (do digitalWriteE led true delayMillisE 1000 digitalWriteE led false delayMillisE 1000 return (ExprLeft ( x-1 )) ) )
ku-fpg/kansas-amber
tests/TransTests/TransRecurLetTestE.hs
bsd-3-clause
2,639
0
26
979
663
341
322
50
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="da-DK"> <title>SOAP Support Add-on</title> <maps> <homeID>soap</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>
thc202/zap-extensions
addOns/soap/src/main/javahelp/org/zaproxy/zap/extension/soap/resources/help_da_DK/helpset_da_DK.hs
apache-2.0
965
77
67
157
413
209
204
-1
-1
-- #8806 module T8806 where f :: Int => Int f x = x + 1 g :: (Int => Show a) => Int g = undefined
sdiehl/ghc
testsuite/tests/typecheck/should_fail/T8806.hs
bsd-3-clause
101
0
7
30
51
28
23
-1
-1
-- #2038 import System.Posix.Resource main :: IO () main = do let soft = ResourceLimit 5 hard = ResourceLimit 10 setResourceLimit ResourceCPUTime (ResourceLimits soft hard) r <- getResourceLimit ResourceCPUTime let (ResourceLimit s) = softLimit r let (ResourceLimit h) = hardLimit r putStrLn $ show s putStrLn $ show h
jimenezrick/unix
tests/resourceLimit.hs
bsd-3-clause
359
0
11
88
127
57
70
11
1
{-# LANGUAGE CPP #-} -- ----------------------------------------------------------------------------- -- -- (c) The University of Glasgow 1993-2004 -- -- The native code generator's monad. -- -- ----------------------------------------------------------------------------- module NCGMonad ( NatM_State(..), mkNatM_State, NatM, -- instance Monad initNat, addImportNat, getUniqueNat, mapAccumLNat, setDeltaNat, getDeltaNat, getThisModuleNat, getBlockIdNat, getNewLabelNat, getNewRegNat, getNewRegPairNat, getPicBaseMaybeNat, getPicBaseNat, getDynFlags, getModLoc, getFileId, getDebugBlock, DwarfFiles ) where #include "HsVersions.h" import GhcPrelude import Reg import Format import TargetReg import BlockId import Hoopl.Collections import Hoopl.Label import CLabel ( CLabel ) import Debug import FastString ( FastString ) import UniqFM import UniqSupply import Unique ( Unique ) import DynFlags import Module import Control.Monad ( liftM, ap ) data NatM_State = NatM_State { natm_us :: UniqSupply, natm_delta :: Int, natm_imports :: [(CLabel)], natm_pic :: Maybe Reg, natm_dflags :: DynFlags, natm_this_module :: Module, natm_modloc :: ModLocation, natm_fileid :: DwarfFiles, natm_debug_map :: LabelMap DebugBlock } type DwarfFiles = UniqFM (FastString, Int) newtype NatM result = NatM (NatM_State -> (result, NatM_State)) unNat :: NatM a -> NatM_State -> (a, NatM_State) unNat (NatM a) = a mkNatM_State :: UniqSupply -> Int -> DynFlags -> Module -> ModLocation -> DwarfFiles -> LabelMap DebugBlock -> NatM_State mkNatM_State us delta dflags this_mod = NatM_State us delta [] Nothing dflags this_mod initNat :: NatM_State -> NatM a -> (a, NatM_State) initNat init_st m = case unNat m init_st of { (r,st) -> (r,st) } instance Functor NatM where fmap = liftM instance Applicative NatM where pure = returnNat (<*>) = ap instance Monad NatM where (>>=) = thenNat instance MonadUnique NatM where getUniqueSupplyM = NatM $ \st -> case splitUniqSupply (natm_us st) of (us1, us2) -> (us1, st {natm_us = us2}) getUniqueM = NatM $ \st -> case takeUniqFromSupply (natm_us st) of (uniq, us') -> (uniq, st {natm_us = us'}) thenNat :: NatM a -> (a -> NatM b) -> NatM b thenNat expr cont = NatM $ \st -> case unNat expr st of (result, st') -> unNat (cont result) st' returnNat :: a -> NatM a returnNat result = NatM $ \st -> (result, st) mapAccumLNat :: (acc -> x -> NatM (acc, y)) -> acc -> [x] -> NatM (acc, [y]) mapAccumLNat _ b [] = return (b, []) mapAccumLNat f b (x:xs) = do (b__2, x__2) <- f b x (b__3, xs__2) <- mapAccumLNat f b__2 xs return (b__3, x__2:xs__2) getUniqueNat :: NatM Unique getUniqueNat = NatM $ \ st -> case takeUniqFromSupply $ natm_us st of (uniq, us') -> (uniq, st {natm_us = us'}) instance HasDynFlags NatM where getDynFlags = NatM $ \ st -> (natm_dflags st, st) getDeltaNat :: NatM Int getDeltaNat = NatM $ \ st -> (natm_delta st, st) setDeltaNat :: Int -> NatM () setDeltaNat delta = NatM $ \ st -> ((), st {natm_delta = delta}) getThisModuleNat :: NatM Module getThisModuleNat = NatM $ \ st -> (natm_this_module st, st) addImportNat :: CLabel -> NatM () addImportNat imp = NatM $ \ st -> ((), st {natm_imports = imp : natm_imports st}) getBlockIdNat :: NatM BlockId getBlockIdNat = do u <- getUniqueNat return (mkBlockId u) getNewLabelNat :: NatM CLabel getNewLabelNat = blockLbl <$> getBlockIdNat getNewRegNat :: Format -> NatM Reg getNewRegNat rep = do u <- getUniqueNat dflags <- getDynFlags return (RegVirtual $ targetMkVirtualReg (targetPlatform dflags) u rep) getNewRegPairNat :: Format -> NatM (Reg,Reg) getNewRegPairNat rep = do u <- getUniqueNat dflags <- getDynFlags let vLo = targetMkVirtualReg (targetPlatform dflags) u rep let lo = RegVirtual $ targetMkVirtualReg (targetPlatform dflags) u rep let hi = RegVirtual $ getHiVirtualRegFromLo vLo return (lo, hi) getPicBaseMaybeNat :: NatM (Maybe Reg) getPicBaseMaybeNat = NatM (\state -> (natm_pic state, state)) getPicBaseNat :: Format -> NatM Reg getPicBaseNat rep = do mbPicBase <- getPicBaseMaybeNat case mbPicBase of Just picBase -> return picBase Nothing -> do reg <- getNewRegNat rep NatM (\state -> (reg, state { natm_pic = Just reg })) getModLoc :: NatM ModLocation getModLoc = NatM $ \ st -> (natm_modloc st, st) getFileId :: FastString -> NatM Int getFileId f = NatM $ \st -> case lookupUFM (natm_fileid st) f of Just (_,n) -> (n, st) Nothing -> let n = 1 + sizeUFM (natm_fileid st) fids = addToUFM (natm_fileid st) f (f,n) in n `seq` fids `seq` (n, st { natm_fileid = fids }) getDebugBlock :: Label -> NatM (Maybe DebugBlock) getDebugBlock l = NatM $ \st -> (mapLookup l (natm_debug_map st), st)
ezyang/ghc
compiler/nativeGen/NCGMonad.hs
bsd-3-clause
5,477
0
18
1,609
1,699
927
772
150
2
-- !!! ds028: failable pats in top row module ShouldCompile where -- when the first row of pats doesn't have convenient -- variables to grab... mAp f [] = [] mAp f (x:xs) = f x : mAp f xs True |||| _ = True False |||| x = x
ezyang/ghc
testsuite/tests/deSugar/should_compile/ds028.hs
bsd-3-clause
248
0
7
74
72
37
35
5
1
{-# LANGUAGE RankNTypes, MagicHash, TypeFamilies, PolyKinds #-} module T9357 where import GHC.Exts type family F (a :: k1) :: k2 type instance F Int# = Int type instance F (forall a. a->a) = Int
urbanslug/ghc
testsuite/tests/indexed-types/should_fail/T9357.hs
bsd-3-clause
197
0
7
36
57
36
21
6
0
{- TRANSFORMERZ - Monad Transformer in vanilla Haskell Nothing imported - just code Author: Marco Faustinelli (contacts@faustinelli.net) Web: http://faustinelli.net/ http://faustinelli.wordpress.com/ Version: 1.0 The MIT License - Copyright (c) 2015 Transformerz Project -} module TestNilsson_01 where import Data.Maybe import qualified Data.Map as Map import Text.Show.Functions import Test.HUnit import Nilsson_01 -- Expressions for exercises -- var xxxx, yyyy watIsXxxx = Var "xxxx" watIsYyyy = Var "yyyy" two_vars_env = Map.insert "xxxx" (IntVal 123) (Map.insert "yyyy" (IntVal 234) Map.empty) xPlusY = Plus (Var "xxxx") (Var "yyyy") -- \x -> x lambdina = Lambda "x" (Var "x") lambdona = Lambda "x" (Lambda "y" (Plus (Var "x") (Var "y"))) -- 12 + (\x -> x)(4 + 2) sample = Plus (Lit 12) (App lambdina (Plus (Lit 4) (Lit 2))) -- IntVal 18 samplone = App (App lambdona (Lit 4)) (Var "xxxx") -- IntVal (4 + xxxx) ---------------------------- testEval0WatIsXxxx :: Test testEval0WatIsXxxx = TestCase $ assertEqual "eval0 should lookup a var" (IntVal 123) (eval0 two_vars_env watIsXxxx) testEval0WatIsXPlusY :: Test testEval0WatIsXPlusY = TestCase $ assertEqual "eval0 should sum two vars" (IntVal 357) (eval0 two_vars_env xPlusY) testEval0SimpleApp :: Test testEval0SimpleApp = TestCase $ assertEqual "eval0 should make a simple application" (IntVal 18) (eval0 Map.empty sample) testEval0ComplexApp :: Test testEval0ComplexApp = TestCase $ assertEqual "eval0 should make a complex application" (IntVal 127) (eval0 two_vars_env samplone) testEval0CurriedApp :: Test testEval0CurriedApp = TestCase $ assertEqual "eval0 should make a partial application" (FunVal "y" (Plus (Var "x") (Var "y")) (Map.fromList [("x",IntVal 4)])) (eval0 Map.empty (App lambdona (Lit 4))) ---------------------------- testEval1WatIsXxxx :: Test testEval1WatIsXxxx = TestCase $ assertEqual "eval1 should lookup a var" (I (IntVal 123)) (eval1 two_vars_env watIsXxxx) testEval1WatIsXPlusY :: Test testEval1WatIsXPlusY = TestCase $ assertEqual "eval1 should sum two vars" (IntVal 357) (unI $ eval1 two_vars_env xPlusY) testEval1SimpleApp :: Test testEval1SimpleApp = TestCase $ assertEqual "eval1 should make a simple application" (IntVal 18) (runEval1 $ eval1 Map.empty sample) testEval1ComplexApp :: Test testEval1ComplexApp = TestCase $ assertEqual "eval1 should make a complex application" (IntVal 127) (runEval1 $ eval1 two_vars_env samplone) testEval1CurriedApp :: Test testEval1CurriedApp = TestCase $ assertEqual "eval1 should make a partial application" (FunVal "y" (Plus (Var "x") (Var "y")) (Map.fromList [("x",IntVal 4)])) (runEval1 $ eval1 Map.empty (App lambdona (Lit 4))) ----------------------------------------- testEval2WatIsXxxx :: Test testEval2WatIsXxxx = TestCase $ assertEqual "eval2 should lookup a var" (ET (I (Just (IntVal 4)))) (eval2 (Map.fromList [("x",IntVal 4)]) (Var "x")) testEval2WatIsXxxx2 :: Test testEval2WatIsXxxx2 = TestCase $ assertEqual "eval2 should lookup a var" (Just (IntVal 4)) (runEval2 $ eval2 (Map.fromList [("x",IntVal 4)]) (Var "x")) testEval2WatIsXPlusY :: Test testEval2WatIsXPlusY = TestCase $ assertEqual "eval2 should sum two vars" (Just (IntVal 357)) (runEval2 $ eval2 two_vars_env xPlusY) testEval2WatIsXPlusCrash :: Test testEval2WatIsXPlusCrash = TestCase $ assertEqual "eval2 should fail summing stuff when one ain't IntVal" (Nothing) (runEval2 $ eval2 Map.empty (Plus (Lit 123) lambdina)) testEval2SimpleApp :: Test testEval2SimpleApp = TestCase $ assertEqual "eval2 should make a simple application" (Just (IntVal 18)) (runEval2 $ eval2 Map.empty sample) testEval2ComplexApp :: Test testEval2ComplexApp = TestCase $ assertEqual "eval2 should make a complex application" (Just (IntVal 127)) (runEval2 $ eval2 two_vars_env samplone) testEval2CurriedApp :: Test testEval2CurriedApp = TestCase $ assertEqual "eval2 should make a partial application" (Just (FunVal "y" (Plus (Var "x") (Var "y")) (Map.fromList [("x",IntVal 4)]))) (runEval2 $ eval2 Map.empty (App lambdona (Lit 4))) testEval2CurriedApp2 :: Test testEval2CurriedApp2 = TestCase $ assertEqual "eval2 should spit Nothing in case of errors" (Nothing) (runEval2 $ eval2 Map.empty (App lambdona (Var "inesistente"))) {--} ----------------------------------------- testEval3Lit123a :: Test testEval3Lit123a = TestCase $ assertEqual "eval3 should return a ET(ST) and update state" (I (Just (IntVal 123), 1)) (unST (unET $ eval3 Map.empty (Lit 123)) 0) testEval3Lit123b :: Test testEval3Lit123b = TestCase $ assertEqual "eval3 should evaluate a Literal and update state" (Just (IntVal 123), 1) (runEval3 0 (eval3 Map.empty (Lit 123))) testEval3VarXxxx :: Test testEval3VarXxxx = TestCase $ assertEqual "eval3 should lookup a Var and update state" (Just (IntVal 123), 1) (runEval3 0 (eval3 two_vars_env watIsXxxx)) testEval3VarUndefined :: Test testEval3VarUndefined = TestCase $ assertEqual "eval3 should fail on non-existing vars and update state" (Nothing, 1) (runEval3 0 (eval3 two_vars_env (Var "zzzz"))) testEval3WatIsXPlusY :: Test testEval3WatIsXPlusY = TestCase $ assertEqual "eval3 should sum two vars" (Just (IntVal 357), 3) (runEval3 0 $ eval3 two_vars_env xPlusY) testEval3WatIsXPlusCrash :: Test testEval3WatIsXPlusCrash = TestCase $ assertEqual "eval3 should fail summing stuff when one ain't IntVal" (Nothing, 3) (runEval3 0 $ eval3 Map.empty (Plus (Lit 123) lambdina)) testEval3SimpleApp :: Test testEval3SimpleApp = TestCase $ assertEqual "eval3 should make a simple application" (Just (IntVal 18), 8) (runEval3 0 $ eval3 Map.empty sample) testEval3ComplexApp :: Test testEval3ComplexApp = TestCase $ assertEqual "eval3 should make a complex application" (Just (IntVal 127), 9) (runEval3 0 $ eval3 two_vars_env samplone) testEval3CurriedApp :: Test testEval3CurriedApp = TestCase $ assertEqual "eval3 should make a partial application" (Just (FunVal "y" (Plus (Var "x") (Var "y")) (Map.fromList [("x",IntVal 4)])), 4) (runEval3 0 $ eval3 Map.empty (App lambdona (Lit 4))) testEval3CurriedApp2 :: Test testEval3CurriedApp2 = TestCase $ assertEqual "eval3 should spit Nothing in case of errors" (Nothing, 3) (runEval3 0 $ eval3 Map.empty (App lambdona (Var "inesistente"))) --------------------------------------- main :: IO Counts main = runTestTT $ TestList [ testEval0WatIsXxxx, testEval0WatIsXPlusY, testEval0SimpleApp, testEval0ComplexApp, testEval0CurriedApp, testEval1WatIsXxxx, testEval1WatIsXPlusY, testEval1SimpleApp, testEval1ComplexApp, testEval1CurriedApp, testEval2WatIsXxxx, testEval2WatIsXxxx2, testEval2WatIsXPlusY, testEval2WatIsXPlusCrash, testEval2SimpleApp, testEval2ComplexApp, testEval2CurriedApp, testEval2CurriedApp2, testEval3Lit123a, testEval3Lit123b, testEval3VarXxxx, testEval3VarUndefined, testEval3WatIsXPlusY, testEval3WatIsXPlusCrash, testEval3SimpleApp, testEval3ComplexApp, testEval3CurriedApp, testEval3CurriedApp2 ]
Muzietto/transformerz
haskell/nilsson/TestNilsson_01.hs
mit
8,294
0
15
2,304
1,959
1,030
929
166
1
module Analyzer (analyze) where import Insn import Data.Array import Data.List import Data.Maybe import Text.Printf (printf) objArray :: Object -> Array Int Insn objArray obj = listArray (0, (length obj)) obj data PipelineState = PipelineState { ifetch :: Maybe Int , dcd :: Maybe Int , mem :: Maybe Int , ex :: Maybe Int , wb :: Maybe Int , staleRegs :: [RegSel] } deriving (Show) instance Eq PipelineState where x == y = (ifetch x) == (ifetch y) && (dcd x) == (dcd y) && (mem x) == (mem y) && (ex x) == (ex y) && (wb x) == (wb y) isValidAddr :: Array Int a -> Int -> Bool isValidAddr obja i = (b <= i) && (i < t) where (b, t) = bounds obja isValidAddrM :: Array Int a -> Maybe Int -> Bool isValidAddrM obja (Just i) = isValidAddr obja i isValidAddrM obja Nothing = True isValidState :: Array Int a -> PipelineState -> Bool isValidState _ PipelineState { ifetch = Nothing , dcd = Nothing , mem = Nothing , ex = Nothing , wb = Nothing } = False isValidState obja ps = v (ifetch ps) && v (dcd ps) && v (mem ps) && v (ex ps) && v (wb ps) where v = isValidAddrM obja invalidState :: PipelineState invalidState = PipelineState { ifetch = Just 0 , dcd = Nothing , mem = Nothing , ex = Nothing , wb = Nothing , staleRegs = [] } tryAdvanceAddr :: Array Int a -> Maybe Int -> Maybe Int tryAdvanceAddr obja (Just i) = if isValidAddr obja (i + 1) then Just (i + 1) else Nothing tryAdvanceAddr obja Nothing = Nothing nextState :: Array Int Insn -> PipelineState -> Maybe Int -> PipelineState nextState obja curr ifetchAddr = PipelineState { ifetch = ifetchAddr , dcd = ifetch curr , mem = dcd curr , ex = mem curr , wb = ex curr , staleRegs = newStaleRegs} where staleRegFromAddr addr | isValidAddr obja addr = case (obja!addr) of ArithInsn{memw=MNone, rd=rd} -> rd _ -> Rc0 staleRegFromAddr _ = Rc0 nonStale = fromMaybe Rc0 $ do addr <- wb curr Just $ staleRegFromAddr addr newStale = fromMaybe Rc0 $ do addr <- dcd curr Just $ staleRegFromAddr addr -- delete only deletes the first nonStale, but it is on purpose. There may be multiple stale writes for the same reg in the pipeline. filtered = delete nonStale (staleRegs curr) newStaleRegs = if newStale == Rc0 then filtered else newStale:filtered initialState :: Array Int Insn -> PipelineState initialState obja = nextState obja nullState (Just 0) where nullState = PipelineState { ifetch = Nothing, dcd = Nothing, mem = Nothing, ex = Nothing, wb = Nothing, staleRegs = [] } nextStates :: Array Int Insn -> PipelineState -> [PipelineState] nextStates obja curr = filter (isValidState obja) [bnt, bt] where bnt :: PipelineState bnt = nextState obja curr $ tryAdvanceAddr obja (ifetch curr) btm :: Maybe PipelineState btm = do jex <- ex curr ja <- branchTargetAddr $ obja!jex Just $ nextState obja curr (Just ja) bt = fromMaybe invalidState btm possibleStates :: Array Int Insn -> [PipelineState] possibleStates obja = populateStates obja (initialState obja) [] where populateStates :: Array Int Insn -> PipelineState -> [PipelineState] -> [PipelineState] populateStates obja s ss | (elem s ss) = ss -- Already explored | otherwise = foldr step (s:ss) nexts where nexts :: [PipelineState] nexts = nextStates obja s step :: PipelineState -> [PipelineState] -> [PipelineState] step = populateStates obja checkMemRWConflict :: Array Int Insn -> PipelineState -> Maybe String checkMemRWConflict obja PipelineState{mem=Just mi, wb=Just wbi} = case (minsn, wbinsn) of (_, ArithInsn{memw=MNone}) -> Nothing (ArithInsn{memrs=stgt}, ArithInsn{memw=wtgt}) | stgt == wtgt -> Just (errmsg $ "s = "++(show stgt)) (ArithInsn{memrt=ttgt}, ArithInsn{memw=wtgt}) | ttgt == wtgt -> Just (errmsg $ "t = "++(show ttgt)) (_, _) -> Nothing where minsn = obja!mi wbinsn = obja!wbi errmsg rloc = printf (unlines [ "Found a Memory RW conflict:", " MEM stage reading \"%s\" executing insn:", " %s", " conflicts with WB stage writing to \"%s\" executing insn:", " %s"]) rloc (show minsn) (show $ memw wbinsn) (show wbinsn) checkMemRWConflict _ _ = Nothing checkStaleRegRead :: Array Int Insn -> PipelineState -> Maybe String checkStaleRegRead obja PipelineState{dcd = Just dcdi, staleRegs=staleRegs} | isValidAddr obja dcdi = if null sregs then Nothing else Just $ errmsg sregs where ifinsn = obja!dcdi rsStale = do rs <- maybeRs ifinsn if elem rs staleRegs then Just rs else Nothing rtStale = do rt <- maybeRt ifinsn if elem rt staleRegs then Just rt else Nothing sregs = catMaybes [rsStale, rtStale] errmsg :: [RegSel] -> String errmsg sregs = printf (unlines [ "Found a stale reg read of registers %s:", " %s"]) (show sregs) (show ifinsn) checkStaleRegRead _ _ = Nothing type CheckFunc = Array Int Insn -> PipelineState -> Maybe String -- map show $ reverse states analyze :: Object -> [String] analyze obj = pipelineCheckResults where obja :: Array Int Insn obja = objArray obj states :: [PipelineState] states = possibleStates obja checks :: [CheckFunc] checks = [checkStaleRegRead, checkMemRWConflict] pipelineCheckResults :: [String] pipelineCheckResults = checks >>= (\check -> catMaybes $ map (check obja) states)
nyaxt/dmix
nkmd/as/Analyzer.hs
mit
6,163
0
16
1,988
1,981
1,034
947
127
4
module Ratscrew.Game.Internal.Snapping ( isSnap ) where import Ratscrew.Cards import Control.Applicative isSnap :: Int -> [Card] -> Bool isSnap i = listOr [ darkQueen, normalSnap, sandwichSnap, matchesCount i] listOr :: [[Card] -> Bool] -> [Card] -> Bool listOr fs cs = any (\f -> f cs) fs darkQueen :: [Card] -> Bool darkQueen cs = case cs of (Card Queen Spades : _) -> True _ -> False normalSnap :: [Card] -> Bool normalSnap = nthSnap 0 sandwichSnap :: [Card] -> Bool sandwichSnap = nthSnap 1 nthSnap :: Int -> [Card] -> Bool nthSnap i cs = any f $ zip cs (drop (i+1) cs) where f (Card r1 _,Card r2 _) = r1 == r2 matchesCount :: Int -> [Card] -> Bool matchesCount i (Card r s : _) = case (i, r) of (1, Ace) -> True (2, Two) -> True (3, Three) -> True (4, Four) -> True (5, Five) -> True (6, Six) -> True (7, Seven) -> True (8, Eight) -> True (9, Nine) -> True (10, Ten) -> True (11, Jack) -> True (12, Queen) -> True (13, King) -> True _ -> False matchesCount _ _ = False
smobs/Ratscrew
src/Ratscrew/Game/Internal/Snapping.hs
mit
1,416
0
10
636
508
280
228
37
14
{-# LANGUAGE UndecidableInstances, TypeSynonymInstances, FlexibleInstances, GeneralizedNewtypeDeriving #-} -- Intel Machine Instructions 386 32bit -- we use only -- 32Bit Registers, signed 32Bit values module Risc386Clone.Intel where import Data.Char -- toLower import Data.Int import Data.List -- elemIndex import Text.PrettyPrint import Risc386Clone.GenSym import Risc386Clone.Util -- class Pretty class Register a where eax :: a ebx :: a ecx :: a edx :: a esi :: a edi :: a ebp :: a esp :: a instance Register Int where eax = 0 -- accumulator for MUL and DIV ebx = 1 ecx = 2 edx = 3 -- holds upper half of MUL/DIV result esi = 4 edi = 5 ebp = 6 -- frame pointer esp = 7 -- stack pointer newtype Reg32 = Reg32 Int deriving (Eq, Ord) regNames = ["eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp"] instance Show Reg32 where show (Reg32 r) = regNames !! (fromIntegral r) instance Read Reg32 where readsPrec n s = case (elemIndex name regNames) of Just r -> [(Reg32 $ fromIntegral r,rest)] Nothing -> [] where (name, rest) = splitAt 3 s instance Register Reg32 where eax = Reg32 eax ebx = Reg32 ebx ecx = Reg32 ecx edx = Reg32 edx esi = Reg32 esi edi = Reg32 edi ebp = Reg32 ebp esp = Reg32 esp -- Intel specific implementation callerSave :: Register a => [a] callerSave = [ eax , ecx , edx ] calleeSave :: Register a => [a] calleeSave = [ ebx , esi , edi ] -- temporaries data Reg = Fixed { unFixed :: Reg32 } -- fixed register, cannot be changed | Flex { unFlex :: Temp } -- a register to be assigned later deriving (Eq, Ord) isReg32 :: Reg -> Bool isReg32 (Fixed _) = True isReg32 (Flex _) = False isTemp :: Reg -> Bool isTemp (Fixed _) = False isTemp (Flex _) = True instance Show Reg where show (Fixed r) = show r show (Flex t) = show t instance Temporary Reg where temp = Flex instance Register Reg where eax = Fixed eax ebx = Fixed ebx ecx = Fixed ecx edx = Fixed edx esi = Fixed esi edi = Fixed edi ebp = Fixed ebp esp = Fixed esp data Scale = S1 | S2 | S4 | S8 -- possible scaling values for effective addressing deriving (Eq) toScale :: (Eq a, Num a) => a -> Maybe Scale toScale 1 = Just S1 toScale 2 = Just S2 toScale 4 = Just S4 toScale 8 = Just S8 toScale _ = Nothing -- parts of e.a. type EA = (Reg, Maybe Scale, Maybe Reg, Int32) type BiLinEA = (Reg, Maybe Scale, Maybe Reg) type AffineEA = (Maybe Reg, Maybe Scale, Int32) type LinEA = (Reg, Maybe Scale) data Dest = Reg Reg -- a register -- full effective address | Mem Reg -- index (Maybe Scale) -- * scale (Maybe Reg) -- + base Int32 -- + Displacement (8, 16, or) 32 bit deriving (Eq) instance Temporary Dest where temp = Reg . temp instance Register Dest where eax = Reg eax ebx = Reg ebx ecx = Reg ecx edx = Reg edx esi = Reg esi edi = Reg edi ebp = Reg ebp esp = Reg esp data Src = Imm Int32 -- immediate value | Dest Dest -- or register or eff.addr. deriving (Eq) type Src' = Dest -- src which cannot be immed. instance Temporary Src where temp = Dest . temp instance Register Src where eax = Dest eax ebx = Dest ebx ecx = Dest ecx edx = Dest edx esi = Dest esi edi = Dest edi ebp = Dest ebp esp = Dest esp data Cond = E | NE | L | LE | G | GE deriving (Eq, Show) -- destructive instruction with dest. and source data DS = MOV -- dest := src, at least one of them a register | ADD -- dest += src, flags carry | SUB -- dest -= src | IMUL2 -- dest *= src | SHL -- dest <<= imm | SHR -- dest >>= imm | SAL -- dest <<= imm (synonym to shl) | SAR -- dest >>= imm (arithmetic right shift) | AND -- dest &= src | OR -- dest |= src | XOR -- dest xor= src deriving (Eq, Show) isShift :: DS -> Bool isShift i = i `elem` [SHL,SHR,SAL,SAR] -- destructive instruction with dest only data D = POP -- pop off stack into dest, adding 4 to ESP | NEG -- dest = -dest | NOT -- dest := !dest | INC -- dest++ | DEC -- dest-- deriving (Eq, Show) data Instr = DS DS Dest Src -- dest ?= src, not two mems | D D Dest -- modifies dest | LEA Reg EA -- load effective address into register | CMP Dest Src -- not two mems, non-destructive | PUSH Src -- push src onto stack, subtracting 4 from ESP | IMUL Src' -- (edx, eax) := eax * src | IDIV Src' -- eax := (edx, eax) div src, edx := (edx,eax) mod src | CDQ -- convert between signed 32bit and signed 64bit -- | CQD -- Convert Quadword Doubleword | JMP Label -- jump, resolved by the assembler | J Cond Label -- conditional jump | CALL Label -- function call | RET -- return from function call | ENTER Int32 -- set up local variables | LEAVE -- esp := ebp, pop ebp | NOP -- do nothing | LABEL Label instance Pretty Reg32 where ppr = text . ('%':) . map toLower . show instance Pretty Reg where ppr (Fixed r) = ppr r ppr (Flex t) = ppr t instance Pretty Scale where ppr S1 = text "1" ppr S2 = text "2" ppr S4 = text "4" ppr S8 = text "8" instance Pretty a => Pretty (Maybe a) where ppr Nothing = empty ppr (Just a) = ppr a ppr_displacement n | n == 0 = empty | n > 0 = text "+" <> text (show n) | n < 0 = text "-" <> text (show (-n)) sepBy :: Doc -> Doc -> Doc -> Doc sepBy sep d1 d2 | isEmpty d2 = d1 | isEmpty d1 = d2 | otherwise = d1 <> sep <> d2 instance Pretty EA where ppr (r, ms, mr, n) = (sepBy (text "+") (sepBy (text "*") (ppr r) (ppr ms)) (ppr mr)) <> ppr_displacement n instance Pretty Dest where ppr (Reg r) = ppr r ppr (Mem r ms mr n) = text "DWORD PTR [" <> ppr (r,ms,mr,n) <> text "]" instance Pretty Src where ppr (Dest d) = ppr d ppr (Imm i) = text $ show i instance Pretty Cond where ppr = text . map toLower . show instance Pretty DS where ppr IMUL2 = text "imul" ppr ds = text . map toLower . show $ ds instance Pretty D where ppr = text . map toLower . show instance Pretty Instr where ppr (DS c d s) = nest 8 $ ppr c $$ (nest 8 $ ppr d <> comma <+> ppr s) ppr (D c d) = nest 8 $ ppr c $$ (nest 8 $ ppr d) ppr (LEA r ea) = nest 8 $ text "lea" $$ (nest 8 $ ppr r <> comma <+> (text "DWORD PTR [" <> ppr ea <> text "]")) ppr (CMP d s) = nest 8 $ text "cmp" $$ (nest 8 $ ppr d <> comma <+> ppr s) ppr (PUSH s) = nest 8 $ text "push" $$ (nest 8 $ ppr s) ppr (IMUL s) = nest 8 $ text "imul" $$ (nest 8 $ ppr s) ppr (IDIV s) = nest 8 $ text "idiv" $$ (nest 8 $ ppr s) ppr (CDQ) = nest 8 $ text "cdq" -- ppr (CQD) = nest 8 $ text "cqd" ppr (JMP l) = nest 8 $ text "jmp" $$ (nest 8 $ ppr l) ppr (J c l) = nest 8 $ text "j" <> ppr c $$ (nest 8 $ ppr l) ppr (CALL l) = nest 8 $ text "call" $$ (nest 8 $ ppr l) ppr (RET) = nest 8 $ text "ret" ppr (ENTER i) = nest 8 $ text "enter" $$ (nest 8 $ text (show i) <> comma <+> text "0") ppr (LEAVE) = nest 8 $ text "leave" ppr (NOP) = nest 8 $ text "nop" ppr (LABEL l) = ppr l <> text ":" instance Pretty [Instr] where ppr [] = empty ppr (s:ss) = (ppr s) $$ ppr ss comment :: Doc -> Doc comment d = text "/*" <+> d <+> text "*/" instance Show Instr where show = render . ppr
cirquit/hjc
src/Risc386Clone/Intel.hs
mit
7,739
0
13
2,486
2,750
1,438
1,312
218
1
module Pipes.Kafka.Example where import Control.Monad (void) import Control.Monad.IO.Class (liftIO) import Control.Monad.Logger (runStdoutLoggingT) import qualified Data.ByteString.Char8 as C8 import Data.Monoid ((<>)) import Kafka.Consumer (BrokerAddress (..), ConsumerGroupId (..), OffsetReset (..), Timeout (..), TopicName (..), brokersList, consumerLogLevel, groupId, noAutoCommit, offsetReset, topics) import qualified Kafka.Producer as Producer import Kafka.Types (KafkaLogLevel (..)) import Pipes (runEffect, (>->)) import qualified Pipes as P import Pipes.Kafka import qualified Pipes.Prelude as P import qualified Pipes.Safe as PS main :: IO () main = do PS.runSafeT $ runEffect nums runStdoutLoggingT $ PS.runSafeT $ runEffect $ P.for source $ \msg -> liftIO $ print msg where sink = kafkaSink producerProps (TopicName "testing") producerProps = Producer.brokersList [BrokerAddress "localhost:9093"] <> Producer.logLevel KafkaLogDebug nums = P.each [(1 :: Int) .. 5] >-> P.map (C8.pack . show) >-> void sink source = kafkaSource consumerProps consumerSub (Timeout 1000) consumerProps = brokersList [BrokerAddress "localhost:9093"] <> groupId (ConsumerGroupId "consumer_example_group") <> noAutoCommit <> consumerLogLevel KafkaLogInfo consumerSub = topics [TopicName "testing"] <> offsetReset Earliest
boothead/pipes-kafka
src/Pipes/Kafka/Example.hs
mit
1,732
0
12
575
415
240
175
35
1
{-# htermination (absMyInt :: MyInt -> MyInt) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data MyInt = Pos Nat | Neg Nat ; data Nat = Succ Nat | Zero ; data Ordering = LT | EQ | GT ; primNegInt :: MyInt -> MyInt; primNegInt (Pos x) = Neg x; primNegInt (Neg x) = Pos x; negateMyInt :: MyInt -> MyInt negateMyInt = primNegInt; absReal0 x MyTrue = negateMyInt x; otherwise :: MyBool; otherwise = MyTrue; absReal1 x MyTrue = x; absReal1 x MyFalse = absReal0 x otherwise; fromIntMyInt :: MyInt -> MyInt fromIntMyInt x = x; primCmpNat :: Nat -> Nat -> Ordering; primCmpNat Zero Zero = EQ; primCmpNat Zero (Succ y) = LT; primCmpNat (Succ x) Zero = GT; primCmpNat (Succ x) (Succ y) = primCmpNat x y; primCmpInt :: MyInt -> MyInt -> Ordering; primCmpInt (Pos Zero) (Pos Zero) = EQ; primCmpInt (Pos Zero) (Neg Zero) = EQ; primCmpInt (Neg Zero) (Pos Zero) = EQ; primCmpInt (Neg Zero) (Neg Zero) = EQ; primCmpInt (Pos x) (Pos y) = primCmpNat x y; primCmpInt (Pos x) (Neg y) = GT; primCmpInt (Neg x) (Pos y) = LT; primCmpInt (Neg x) (Neg y) = primCmpNat y x; compareMyInt :: MyInt -> MyInt -> Ordering compareMyInt = primCmpInt; esEsOrdering :: Ordering -> Ordering -> MyBool esEsOrdering LT LT = MyTrue; esEsOrdering LT EQ = MyFalse; esEsOrdering LT GT = MyFalse; esEsOrdering EQ LT = MyFalse; esEsOrdering EQ EQ = MyTrue; esEsOrdering EQ GT = MyFalse; esEsOrdering GT LT = MyFalse; esEsOrdering GT EQ = MyFalse; esEsOrdering GT GT = MyTrue; not :: MyBool -> MyBool; not MyTrue = MyFalse; not MyFalse = MyTrue; fsEsOrdering :: Ordering -> Ordering -> MyBool fsEsOrdering x y = not (esEsOrdering x y); gtEsMyInt :: MyInt -> MyInt -> MyBool gtEsMyInt x y = fsEsOrdering (compareMyInt x y) LT; absReal2 x = absReal1 x (gtEsMyInt x (fromIntMyInt (Pos Zero))); absReal x = absReal2 x; absMyInt :: MyInt -> MyInt absMyInt = absReal;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/abs_3.hs
mit
1,930
0
11
403
803
432
371
55
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Main where import Control.Monad.State import Criterion import Criterion.Main import Data.Acid import Data.Data import Data.Int import qualified Data.IxSet as Set import Data.SafeCopy import Data.Typeable import GHC.Generics newtype EventId = EventId { unEventId :: Int64 } deriving (Eq, Ord, Show, Data, Typeable, Generic, Enum, Num) newtype PosX = PosX { unPosX :: Double } deriving (Eq, Ord, Show, Data, Typeable, Generic, Enum, Num, Fractional) newtype PosY = PosY { unPosY :: Double } deriving (Eq, Ord, Show, Data, Typeable, Generic, Enum, Num, Fractional) data Event = Event EventId PosX PosY deriving (Eq, Ord, Show, Data, Typeable, Generic) instance Set.Indexable Event where empty = Set.ixSet [ Set.ixGen (Set.Proxy :: Set.Proxy EventId) ] data DB = DB { events :: Set.IxSet Event } deriving (Show, Typeable, Data, Generic) insertEvent :: Event -> Update DB () insertEvent (Event i x y) = modify (\(DB es) -> DB $ Set.insert (Event i x y) es) $(deriveSafeCopy 0 'base ''EventId) $(deriveSafeCopy 0 'base ''PosX) $(deriveSafeCopy 0 'base ''PosY) $(deriveSafeCopy 0 'base ''Event) $(deriveSafeCopy 0 'base ''DB) $(makeAcidic ''DB ['insertEvent]) main :: IO () main = do print $ (pop Set.@= (EventId 10)) state <- openLocalState (DB Set.empty) mapM_ (update state . InsertEvent) $ take 10000 $ Set.toList pop defaultMain [ bgroup "IxSet Lookup" [ bench "2463" $ whnf (\p -> (p Set.@= (EventId 2463))) pop , bench "500000" $ whnf (\p -> (p Set.@= (EventId 500000))) pop ] , bgroup "IxSet Insert" [ bench "E1" $ whnf (Set.insert (Event 9987463 234.2 235.2)) pop , bench "E2" $ whnf (Set.insert (Event 2000009 436.36 346.6)) pop ] , bgroup "ACID Insert" [ bench "A1" $ nfIO (update state (InsertEvent (Event (EventId 2355) 235.2 2365.3))) , bench "A2" $ nfIO (update state (InsertEvent (Event (EventId 8363) 46.3 3463.2))) ] ] pop :: Set.IxSet Event pop = Set.fromList $ map (\(i, x, y) -> Event (EventId i) x y) $ zip3 [1..] [startX..maxX] [startY..maxY] where startX = 0.0 maxX = 1000000.0 startY = 1000001.0 maxY = 2000000.0
AndrewRademacher/cyberwolf-test
src/IxSet.hs
mit
2,807
0
20
942
953
498
455
50
1
module Search.Naive.Text ( find , findOne , contains ) where import Data.Text (Text) import qualified Data.Text as T import Prelude hiding (pi) type Corpus = Text type Pattern = Text find :: Corpus -> Pattern -> [Int] find c p = let (_, _, _, is) = T.foldl' match (0, 0, Nothing, []) c in reverse is where pl = T.length p - 1 match (ci, pi, Nothing, is) cv | T.index p pi == cv = case compare pi pl of LT -> (ci + 1, pi + 1, Just ci, is) EQ -> undefined GT -> undefined | otherwise = (ci + 1, 0, Nothing, is) match (ci, pi, Just i, is) cv | T.index p pi == cv = case compare pi pl of LT -> (ci + 1, pi + 1, Just i, is) EQ -> (ci + 1, 0, Nothing, i:is) GT -> undefined | otherwise = (ci + 1, 0, Nothing, is) findOne :: Corpus -> Pattern -> Maybe Int findOne c p = case take 1 (find c p) of [] -> Nothing (i:_) -> Just i contains :: Corpus -> Pattern -> Bool contains c p = case findOne c p of Nothing -> False Just _ -> True
AndrewRademacher/string-search
src/Search/Naive/Text.hs
mit
1,372
0
12
655
514
276
238
31
6
module Discogs.Routes.Artist where import Discogs.Types.Artist import Discogs.Types.Release import Network.API.Builder.Routes getArtist :: ArtistID -> Route getArtist (ArtistID artist) = Route [ "artists", artist ] [] "GET" getArtistReleases :: ArtistID -> Route getArtistReleases (ArtistID artist) = Route [ "artists", artist, "releases" ] [] "GET"
accraze/discogs-haskell
src/Discogs/Routes/Artist.hs
mit
489
0
7
181
105
60
45
12
1
-- | Data types for representing pictures. module Graphics.Gloss.Data.Picture ( Point , Vector , Path , Picture(..) , BitmapData -- * Aliases for Picture constructors , blank , polygon , line , circle, thickCircle , arc, thickArc , text , bitmap , color , translate, rotate, scale , pictures -- * Compound shapes , lineLoop , circleSolid , arcSolid , sectorWire , rectanglePath , rectangleWire , rectangleSolid , rectangleUpperPath , rectangleUpperWire , rectangleUpperSolid -- * Loading Bitmaps , bitmapOfForeignPtr , bitmapOfByteString , bitmapOfBMP , loadBMP) where import Graphics.Gloss.Data.Color import Graphics.Gloss.Data.Point import Graphics.Gloss.Data.Vector import Graphics.Gloss.Geometry.Angle import Graphics.Gloss.Internals.Render.Bitmap import Codec.BMP import Foreign.ForeignPtr import Foreign.Marshal.Alloc import Foreign.Marshal.Utils import Foreign.Ptr import Data.Word import Data.Monoid import Data.ByteString import Data.Data import System.IO.Unsafe import qualified Data.ByteString.Unsafe as BSU import Prelude hiding (map) -- | A path through the x-y plane. type Path = [Point] -- | A 2D picture data Picture -- Primitives ------------------------------------- -- | A blank picture, with nothing in it. = Blank -- | A convex polygon filled with a solid color. | Polygon Path -- | A line along an arbitrary path. | Line Path -- | A circle with the given radius. | Circle Float -- | A circle with the given thickness and radius. -- If the thickness is 0 then this is equivalent to `Circle`. | ThickCircle Float Float -- | A circular arc drawn counter-clockwise between two angles -- (in degrees) at the given radius. | Arc Float Float Float -- | A circular arc drawn counter-clockwise between two angles -- (in degrees), with the given radius and thickness. -- If the thickness is 0 then this is equivalent to `Arc`. | ThickArc Float Float Float Float -- | Some text to draw with a vector font. | Text String -- | A bitmap image with a width, height and some 32-bit RGBA -- bitmap data. -- -- The boolean flag controls whether Gloss should cache the data -- between frames for speed. If you are programatically generating -- the image for each frame then use `False`. If you have loaded it -- from a file then use `True`. | Bitmap Int Int BitmapData Bool -- Color ------------------------------------------ -- | A picture drawn with this color. | Color Color Picture -- Transforms ------------------------------------- -- | A picture translated by the given x and y coordinates. | Translate Float Float Picture -- | A picture rotated clockwise by the given angle (in degrees). | Rotate Float Picture -- | A picture scaled by the given x and y factors. | Scale Float Float Picture -- More Pictures ---------------------------------- -- | A picture consisting of several others. | Pictures [Picture] deriving (Show, Eq, Data, Typeable) -- Instances ------------------------------------------------------------------ instance Monoid Picture where mempty = blank mappend a b = Pictures [a, b] mconcat = Pictures -- Constructors ---------------------------------------------------------------- -- NOTE: The docs here should be identical to the ones on the constructors. -- | A blank picture, with nothing in it. blank :: Picture blank = Blank -- | A convex polygon filled with a solid color. polygon :: Path -> Picture polygon = Polygon -- | A line along an arbitrary path. line :: Path -> Picture line = Line -- | A circle with the given radius. circle :: Float -> Picture circle = Circle -- | A circle with the given thickness and radius. -- If the thickness is 0 then this is equivalent to `Circle`. thickCircle :: Float -> Float -> Picture thickCircle = ThickCircle -- | A circular arc drawn counter-clockwise between two angles (in degrees) -- at the given radius. arc :: Float -> Float -> Float -> Picture arc = Arc -- | A circular arc drawn counter-clockwise between two angles (in degrees), -- with the given radius and thickness. -- If the thickness is 0 then this is equivalent to `Arc`. thickArc :: Float -> Float -> Float -> Float -> Picture thickArc = ThickArc -- | Some text to draw with a vector font. text :: String -> Picture text = Text -- | A bitmap image with a width, height and a Vector holding the -- 32-bit RGBA bitmap data. -- -- The boolean flag controls whether Gloss should cache the data -- between frames for speed. -- If you are programatically generating the image for -- each frame then use `False`. -- If you have loaded it from a file then use `True`. bitmap :: Int -> Int -> BitmapData -> Bool -> Picture bitmap = Bitmap -- | A picture drawn with this color. color :: Color -> Picture -> Picture color = Color -- | A picture translated by the given x and y coordinates. translate :: Float -> Float -> Picture -> Picture translate = Translate -- | A picture rotated clockwise by the given angle (in degrees). rotate :: Float -> Picture -> Picture rotate = Rotate -- | A picture scaled by the given x and y factors. scale :: Float -> Float -> Picture -> Picture scale = Scale -- | A picture consisting of several others. pictures :: [Picture] -> Picture pictures = Pictures -- Bitmaps -------------------------------------------------------------------- -- | O(1). Use a `ForeignPtr` of RGBA data as a bitmap with the given -- width and height. -- The boolean flag controls whether Gloss should cache the data -- between frames for speed. If you are programatically generating -- the image for each frame then use `False`. If you have loaded it -- from a file then use `True`. bitmapOfForeignPtr :: Int -> Int -> ForeignPtr Word8 -> Bool -> Picture bitmapOfForeignPtr width height fptr cacheMe = let len = width * height * 4 bdata = BitmapData len fptr in Bitmap width height bdata cacheMe -- | O(size). Copy a `ByteString` of RGBA data into a bitmap with the given -- width and height. -- -- The boolean flag controls whether Gloss should cache the data -- between frames for speed. If you are programatically generating -- the image for each frame then use `False`. If you have loaded it -- from a file then use `True`. {-# NOINLINE bitmapOfByteString #-} bitmapOfByteString :: Int -> Int -> ByteString -> Bool -> Picture bitmapOfByteString width height bs cacheMe = unsafePerformIO $ do let len = width * height * 4 ptr <- mallocBytes len fptr <- newForeignPtr finalizerFree ptr BSU.unsafeUseAsCString bs $ \cstr -> copyBytes ptr (castPtr cstr) len let bdata = BitmapData len fptr return $ Bitmap width height bdata cacheMe -- | O(size). Copy a `BMP` file into a bitmap. {-# NOINLINE bitmapOfBMP #-} bitmapOfBMP :: BMP -> Picture bitmapOfBMP bmp = unsafePerformIO $ do let (width, height) = bmpDimensions bmp let bs = unpackBMPToRGBA32 bmp let len = width * height * 4 ptr <- mallocBytes len fptr <- newForeignPtr finalizerFree ptr BSU.unsafeUseAsCString bs $ \cstr -> copyBytes ptr (castPtr cstr) len let bdata = BitmapData len fptr reverseRGBA bdata return $ Bitmap width height bdata True -- | Load an uncompressed 24 or 32bit RGBA BMP file as a bitmap. loadBMP :: FilePath -> IO Picture loadBMP filePath = do ebmp <- readBMP filePath case ebmp of Left err -> error $ show err Right bmp -> return $ bitmapOfBMP bmp -- Other Shapes --------------------------------------------------------------- -- | A closed loop along a path. lineLoop :: Path -> Picture lineLoop [] = Line [] lineLoop (x:xs) = Line ((x:xs) ++ [x]) -- Circles and Arcs ----------------------------------------------------------- -- | A solid circle with the given radius. circleSolid :: Float -> Picture circleSolid r = thickCircle (r/2) r -- | A solid arc, drawn counter-clockwise between two angles at the given radius. arcSolid :: Float -> Float -> Float -> Picture arcSolid a1 a2 r = thickArc a1 a2 (r/2) r -- | A wireframe sector of a circle. -- An arc is draw counter-clockwise from the first to the second angle at -- the given radius. Lines are drawn from the origin to the ends of the arc. --- -- NOTE: We take the absolute value of the radius incase it's negative. -- It would also make sense to draw the sector flipped around the -- origin, but I think taking the absolute value will be less surprising -- for the user. -- sectorWire :: Float -> Float -> Float -> Picture sectorWire a1 a2 r_ = let r = abs r_ in Pictures [ Arc a1 a2 r , Line [(0, 0), (r * cos (degToRad a1), r * sin (degToRad a1))] , Line [(0, 0), (r * cos (degToRad a2), r * sin (degToRad a2))] ] -- Rectangles ----------------------------------------------------------------- -- NOTE: Only the first of these rectangle functions has haddocks on the -- arguments to reduce the amount of noise in the extracted docs. -- | A path representing a rectangle centered about the origin rectanglePath :: Float -- ^ width of rectangle -> Float -- ^ height of rectangle -> Path rectanglePath sizeX sizeY = let sx = sizeX / 2 sy = sizeY / 2 in [(-sx, -sy), (-sx, sy), (sx, sy), (sx, -sy)] -- | A wireframe rectangle centered about the origin. rectangleWire :: Float -> Float -> Picture rectangleWire sizeX sizeY = lineLoop $ rectanglePath sizeX sizeY -- | A wireframe rectangle in the y > 0 half of the x-y plane. rectangleUpperWire :: Float -> Float -> Picture rectangleUpperWire sizeX sizeY = lineLoop $ rectangleUpperPath sizeX sizeY -- | A path representing a rectangle in the y > 0 half of the x-y plane. rectangleUpperPath :: Float -> Float -> Path rectangleUpperPath sizeX sy = let sx = sizeX / 2 in [(-sx, 0), (-sx, sy), (sx, sy), (sx, 0)] -- | A solid rectangle centered about the origin. rectangleSolid :: Float -> Float -> Picture rectangleSolid sizeX sizeY = Polygon $ rectanglePath sizeX sizeY -- | A solid rectangle in the y > 0 half of the x-y plane. rectangleUpperSolid :: Float -> Float -> Picture rectangleUpperSolid sizeX sizeY = Polygon $ rectangleUpperPath sizeX sizeY
gscalzo/HaskellTheHardWay
gloss-try/gloss-master/gloss/Graphics/Gloss/Data/Picture.hs
mit
10,606
95
19
2,483
1,861
1,043
818
172
2
{-# OPTIONS_HADDOCK hide, prune #-} module Handler.Home.LoadingSplash ( loadingSplash ) where import Import -- | Rotating circular progress bar; -- exposes one dom id '#loadingSplash'. loadingSplash :: Widget loadingSplash = do redCircle <- newIdent greyCircle <- newIdent rotRed <- newIdent rotGrey <- newIdent toWidgetHead [cassius| #loadingSplash z-index: 777 display: block position: fixed height: 40% padding: 0 top: 50% left: 50% margin: 0 -50% 0 0 transform: translate(-50%, -50%) ##{redCircle} position: relative transform-origin: 36px 36px -ms-transform-origin: 36px 36px -moz-transform-origin: 36px 36px -webkit-transform-origin: 36px 36px -webkit-animation: #{rotRed} 32s linear infinite -moz-animation: #{rotRed} 3s linear infinite -ms-animation: #{rotRed} 3s linear infinite -o-animation: #{rotRed} 3s linear infinite animation: #{rotRed} 3s linear infinite ##{greyCircle} position: relative transform-origin: 36px 36px -ms-transform-origin: 36px 36px -moz-transform-origin: 36px 36px -webkit-transform-origin: 36px 36px -webkit-animation: #{rotGrey} 8s linear infinite -moz-animation: #{rotGrey} 8s linear infinite -ms-animation: #{rotGrey} 8s linear infinite -o-animation: #{rotGrey} 8s linear infinite animation: #{rotGrey} 8s linear infinite @-webkit-keyframes #{rotRed} from -ms-transform: rotate(0deg) -moz-transform: rotate(0deg) -webkit-transform: rotate(0deg) -o-transform: rotate(0deg) transform: rotate(0deg) to -ms-transform: rotate(360deg) -moz-transform: rotate(360deg) -webkit-transform: rotate(360deg) -o-transform: rotate(360deg) transform: rotate(360deg) @keyframes #{rotRed} from -ms-transform: rotate(0deg) -moz-transform: rotate(0deg) -webkit-transform: rotate(0deg) -o-transform: rotate(0deg) transform: rotate(0deg) to -ms-transform: rotate(360deg) -moz-transform: rotate(360deg) -webkit-transform: rotate(360deg) -o-transform: rotate(360deg) transform: rotate(360deg) @-webkit-keyframes #{rotGrey} from -ms-transform: rotate(360deg) -moz-transform: rotate(360deg) -webkit-transform: rotate(360deg) -o-transform: rotate(360deg) transform: rotate(360deg) to -ms-transform: rotate(0deg) -moz-transform: rotate(0deg) -webkit-transform: rotate(0deg) -o-transform: rotate(0deg) transform: rotate(0deg) @keyframes #{rotGrey} from -ms-transform: rotate(360deg) -moz-transform: rotate(360deg) -webkit-transform: rotate(360deg) -o-transform: rotate(360deg) transform: rotate(360deg) to -ms-transform: rotate(0deg) -moz-transform: rotate(0deg) -webkit-transform: rotate(0deg) -o-transform: rotate(0deg) transform: rotate(0deg) |] toWidgetBody [hamlet| <svg fill="none" #loadingSplash version="1.1" viewBox="0 0 72 72" xmlns="http://www.w3.org/2000/svg"> <circle cx="36" cy="36" ##{redCircle} r="28" stroke="#FF5722" stroke-dasharray="10, 5, 50, 40, 30.929188601, 40" stroke-opacity="1" stroke-width="16"> <circle cx="36" cy="36" ##{greyCircle} r="28" stroke="#BF360C" stroke-dasharray="38, 14, 8, 14, 65.929188601, 14, 8, 14" stroke-opacity=".2" stroke-width="8"> |]
mb21/qua-kit
apps/hs/qua-server/src/Handler/Home/LoadingSplash.hs
mit
3,795
0
7
1,089
76
43
33
-1
-1
{-# LANGUAGE GADTs #-} module Text.Regex.Applicative.Compile (compile) where import Control.Monad ((<=<)) import Control.Monad.Trans.State import Data.Foldable import Data.Maybe import Data.Monoid (Any (..)) import qualified Data.IntMap as IntMap import Text.Regex.Applicative.Types compile :: RE s a -> (a -> [Thread s r]) -> [Thread s r] compile e k = compile2 e (SingleCont k) data Cont a = SingleCont !a | EmptyNonEmpty !a !a instance Functor Cont where fmap f k = case k of SingleCont a -> SingleCont (f a) EmptyNonEmpty a b -> EmptyNonEmpty (f a) (f b) emptyCont :: Cont a -> a emptyCont k = case k of SingleCont a -> a EmptyNonEmpty a _ -> a nonEmptyCont :: Cont a -> a nonEmptyCont k = case k of SingleCont a -> a EmptyNonEmpty _ a -> a -- compile2 function takes two continuations: one when the match is empty and -- one when the match is non-empty. See the "Rep" case for the reason. compile2 :: RE s a -> Cont (a -> [Thread s r]) -> [Thread s r] compile2 e = case e of Eps -> \k -> emptyCont k () Symbol i p -> \k -> [t $ nonEmptyCont k] where -- t :: (a -> [Thread s r]) -> Thread s r t k = Thread i $ \s -> case p s of Just r -> k r Nothing -> [] App n1 n2 -> let a1 = compile2 n1 a2 = compile2 n2 in \k -> case k of SingleCont k -> a1 $ SingleCont $ \a1_value -> a2 $ SingleCont $ k . a1_value EmptyNonEmpty ke kn -> a1 $ EmptyNonEmpty -- empty (\a1_value -> a2 $ EmptyNonEmpty (ke . a1_value) (kn . a1_value)) -- non-empty (\a1_value -> a2 $ EmptyNonEmpty (kn . a1_value) (kn . a1_value)) Alt n1 n2 -> let a1 = compile2 n1 a2 = compile2 n2 in \k -> a1 k ++ a2 k Fail -> const [] Fmap f n -> let a = compile2 n in \k -> a $ fmap (. f) k CatMaybes n -> let a = compile2 n in \k -> a $ (<=< toList) <$> k -- This is actually the point where we use the difference between -- continuations. For the inner RE the empty continuation is a -- "failing" one in order to avoid non-termination. Rep g f b n -> let a = compile2 n threads b k = combine g (a $ EmptyNonEmpty (\_ -> []) (\v -> let b' = f b v in threads b' (SingleCont $ nonEmptyCont k))) (emptyCont k b) in threads b Void n | hasCatMaybes n -> compile2 n . fmap (. \ _ -> ()) | otherwise -> compile2_ n . fmap ($ ()) data FSMState = SAccept | STransition !ThreadId type FSMMap s = IntMap.IntMap (s -> Bool, [FSMState]) mkNFA :: RE s a -> ([FSMState], (FSMMap s)) mkNFA e = flip runState IntMap.empty $ go e [SAccept] where go :: RE s a -> [FSMState] -> State (FSMMap s) [FSMState] go e k = case e of Eps -> return k Symbol i@(ThreadId n) p -> do modify $ IntMap.insert n $ (isJust . p, k) return [STransition i] App n1 n2 -> go n1 =<< go n2 k Alt n1 n2 -> (++) <$> go n1 k <*> go n2 k Fail -> return [] Fmap _ n -> go n k CatMaybes _ -> error "mkNFA CatMaybes" Rep g _ _ n -> let entries = findEntries n cont = combine g entries k in -- return value of 'go' is ignored -- it should be a subset of -- 'cont' go n cont >> return cont Void n -> go n k findEntries :: RE s a -> [FSMState] findEntries e = -- A simple (although a bit inefficient) way to find all entry points is -- just to use 'go' evalState (go e []) IntMap.empty hasCatMaybes :: RE s a -> Bool hasCatMaybes = getAny . foldMapPostorder (Any . \ case CatMaybes _ -> True; _ -> False) compile2_ :: RE s a -> Cont [Thread s r] -> [Thread s r] compile2_ e = let (entries, fsmap) = mkNFA e mkThread _ k1 (STransition i@(ThreadId n)) = let (p, cont) = fromMaybe (error "Unknown id") $ IntMap.lookup n fsmap in [Thread i $ \s -> if p s then concatMap (mkThread k1 k1) cont else []] mkThread k0 _ SAccept = k0 in \k -> concatMap (mkThread (emptyCont k) (nonEmptyCont k)) entries combine :: Greediness -> [a] -> [a] -> [a] combine g continue stop = case g of Greedy -> continue ++ stop NonGreedy -> stop ++ continue
feuerbach/regex-applicative
Text/Regex/Applicative/Compile.hs
mit
4,700
0
23
1,741
1,694
851
843
-1
-1
{-# LANGUAGE PackageImports #-} {-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-} -- | Reexports "Data.Bool.Compat" -- from a globally unique namespace. module Data.Bool.Compat.Repl.Batteries ( module Data.Bool.Compat ) where import "this" Data.Bool.Compat
haskell-compat/base-compat
base-compat-batteries/src/Data/Bool/Compat/Repl/Batteries.hs
mit
278
0
5
31
29
22
7
5
0
module Logic.TemporalLogic.Macro where import Types import Macro.MetaMacro import Macro.Text import Logic.AbstractLogic.Macro -- | The 'next' temporal logic operator next :: Note -> Note next = mappend $ comm0 "bigcirc" -- | The 'until' temporal logic operator until :: Note -> Note -> Note until = binop $ commS "," <> mathcal "U" <> commS "," -- | Infix version of the 'until' temporal logic operator (.∪) :: Note -> Note -> Note (.∪) = until -- | Eventually evnt :: Note -> Note evnt = mappend $ comm0 "Diamond" -- | Always alws :: Note -> Note alws = mappend $ comm0 "Box" -- | Satisfies satis :: Note -- Word -> Note -- Position -> Note -- Formula -> Note satis w p = lent $ cs [w, p] -- | Language of a formula languageOf :: Note -- Formula -> Note languageOf = (!:) "L"
NorfairKing/the-notes
src/Logic/TemporalLogic/Macro.hs
gpl-2.0
872
0
8
238
220
126
94
23
1
-- C->Haskell Compiler: CHS file abstraction -- -- Author : Manuel M T Chakravarty -- Created: 16 August 99 -- -- Copyright (c) [1999..2005] Manuel M T Chakravarty -- -- This file is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This file is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- --- DESCRIPTION --------------------------------------------------------------- -- -- Main file for reading CHS files. -- -- Import hooks & .chi files -- ------------------------- -- -- Reading of `.chi' files is interleaved with parsing. More precisely, -- whenever the parser comes across an import hook, it immediately reads the -- `.chi' file and inserts its contents into the abstract representation of -- the hook. The parser checks the version of the `.chi' file, but does not -- otherwise attempt to interpret its contents. This is only done during -- generation of the binding module. The first line of a .chi file has the -- form -- -- C->Haskell Interface Version <version> -- -- where <version> is the three component version number `Version.version'. -- C->Haskell will only accept files whose version number match its own in -- the first two components (ie, major and minor version). In other words, -- it must be guaranteed that the format of .chi files is not altered between -- versions that differ only in their patchlevel. All remaining lines of the -- file are version dependent and contain a dump of state information that -- the binding file generator needs to rescue across modules. -- --- DOCU ---------------------------------------------------------------------- -- -- language: Haskell 98 -- -- The following binding hooks are recognised: -- -- hook -> `{#' inner `#}' -- inner -> `import' ['qualified'] ident -- | `context' ctxt -- | `type' ident -- | `sizeof' ident -- | `enum' idalias trans [`with' prefix] [deriving] -- | `call' [`pure'] [`unsafe'] idalias -- | `fun' [`pure'] [`unsafe'] idalias parms -- | `get' apath -- | `set' apath -- | `pointer' ['*'] idalias ptrkind ['nocode'] -- | `class' [ident `=>'] ident ident -- ctxt -> [`lib' `=' string] [prefix] -- idalias -> ident [`as' (ident | `^')] -- prefix -> `prefix' `=' string -- deriving -> `deriving' `(' ident_1 `,' ... `,' ident_n `)' -- parms -> [verbhs `=>'] `{' parm_1 `,' ... `,' parm_n `}' `->' parm -- parm -> [ident_1 [`*' | `-']] verbhs [`&'] [ident_2 [`*'] [`-']] -- apath -> ident -- | `*' apath -- | apath `.' ident -- | apath `->' ident -- trans -> `{' alias_1 `,' ... `,' alias_n `}' -- alias -> `underscoreToCase' | `upcaseFirstLetter' -- | `downcaseFirstLetter' -- | ident `as' ident -- ptrkind -> [`foreign' | `stable'] ['newtype' | '->' ident] -- -- If `underscoreToCase', `upcaseFirstLetter', or `downcaseFirstLetter' -- occurs in a translation table, it must be the first entry, or if two of -- them occur the first two entries. -- -- Remark: Optional Haskell names are normalised during structure tree -- construction, ie, associations that associated a name with itself -- are removed. (They don't carry semantic content, and make some -- tests more complicated.) -- --- TODO ---------------------------------------------------------------------- -- module C2HS.CHS (CHSModule(..), CHSFrag(..), CHSHook(..), CHSTrans(..), CHSChangeCase(..), CHSParm(..), CHSArg(..), CHSAccess(..), CHSAPath(..), CHSPtrType(..), loadCHS, dumpCHS, hssuffix, chssuffix, loadCHI, dumpCHI, chisuffix, showCHSParm, apathToIdent) where -- standard libraries import Data.Char (isSpace, toUpper, toLower) import Data.List (intersperse) import Control.Monad (when) import System.FilePath ((<.>), (</>)) -- Language.C import Language.C.Data.Ident import Language.C.Data.Position import Data.Errors (interr) -- C->Haskell import C2HS.State (CST, getSwitch, chiPathSB, catchExc, throwExc, raiseError, fatal, errorsPresent, showErrors, Traces(..), putTraceStr) import qualified System.CIO as CIO import C2HS.Version (version) -- friends import C2HS.CHS.Lexer (CHSToken(..), lexCHS, keywordToIdent) -- CHS abstract syntax -- ------------------- -- | representation of a CHS module -- data CHSModule = CHSModule [CHSFrag] -- | a CHS code fragament -- -- * 'CHSVerb' fragments are present throughout the compilation and finally -- they are the only type of fragment (describing the generated Haskell -- code) -- -- * 'CHSHook' are binding hooks, which are being replaced by Haskell code by -- 'GenBind.expandHooks' -- -- * 'CHSCPP' and 'CHSC' are fragements of C code that are being removed when -- generating the custom C header in 'GenHeader.genHeader' -- -- * 'CHSCond' are strutured conditionals that are being generated by -- 'GenHeader.genHeader' from conditional CPP directives ('CHSCPP') -- data CHSFrag = CHSVerb String -- Haskell code Position | CHSHook CHSHook -- binding hook | CHSCPP String -- pre-processor directive Position | CHSLine Position -- line pragma | CHSC String -- C code Position | CHSCond [(Ident, -- C variable repr. condition [CHSFrag])] -- then/elif branches (Maybe [CHSFrag]) -- else branch instance Pos CHSFrag where posOf (CHSVerb _ pos ) = pos posOf (CHSHook hook ) = posOf hook posOf (CHSCPP _ pos ) = pos posOf (CHSLine pos ) = pos posOf (CHSC _ pos ) = pos posOf (CHSCond alts _) = case alts of (_, frag:_):_ -> posOf frag _ -> nopos -- | a CHS binding hook -- data CHSHook = CHSImport Bool -- qualified? Ident -- module name String -- content of .chi file Position | CHSContext (Maybe String) -- library name (Maybe String) -- prefix Position | CHSType Ident -- C type Position | CHSSizeof Ident -- C type Position | CHSAlignof Ident -- C type Position | CHSEnum Ident -- C enumeration type (Maybe Ident) -- Haskell name CHSTrans -- translation table (Maybe String) -- local prefix [Ident] -- instance requests from user Position | CHSEnumDefine Ident -- Haskell name CHSTrans -- translation table [Ident] -- instance requests from user Position | CHSCall Bool -- is a pure function? Bool -- is unsafe? CHSAPath -- C function (Maybe Ident) -- Haskell name Position | CHSFun Bool -- is a pure function? Bool -- is unsafe? CHSAPath -- C function (Maybe Ident) -- Haskell name (Maybe String) -- type context [CHSParm] -- argument marshalling CHSParm -- result marshalling Position | CHSField CHSAccess -- access type CHSAPath -- access path Position | CHSPointer Bool -- explicit '*' in hook Ident -- C pointer name (Maybe Ident) -- Haskell name CHSPtrType -- Ptr, ForeignPtr or StablePtr Bool -- create new type? (Maybe Ident) -- Haskell type pointed to Bool -- emit type decl? Position | CHSClass (Maybe Ident) -- superclass Ident -- class name Ident -- name of pointer type Position instance Pos CHSHook where posOf (CHSImport _ _ _ pos) = pos posOf (CHSContext _ _ pos) = pos posOf (CHSType _ pos) = pos posOf (CHSSizeof _ pos) = pos posOf (CHSAlignof _ pos) = pos posOf (CHSEnum _ _ _ _ _ pos) = pos posOf (CHSEnumDefine _ _ _ pos) = pos posOf (CHSCall _ _ _ _ pos) = pos posOf (CHSFun _ _ _ _ _ _ _ pos) = pos posOf (CHSField _ _ pos) = pos posOf (CHSPointer _ _ _ _ _ _ _ pos) = pos posOf (CHSClass _ _ _ pos) = pos -- | two hooks are equal if they have the same Haskell name and reference the -- same C object -- instance Eq CHSHook where (CHSImport qual1 ide1 _ _) == (CHSImport qual2 ide2 _ _) = qual1 == qual2 && ide1 == ide2 (CHSContext olib1 opref1 _ ) == (CHSContext olib2 opref2 _ ) = olib1 == olib2 && opref1 == opref2 (CHSType ide1 _) == (CHSType ide2 _) = ide1 == ide2 (CHSSizeof ide1 _) == (CHSSizeof ide2 _) = ide1 == ide2 (CHSAlignof ide1 _) == (CHSAlignof ide2 _) = ide1 == ide2 (CHSEnum ide1 oalias1 _ _ _ _) == (CHSEnum ide2 oalias2 _ _ _ _) = oalias1 == oalias2 && ide1 == ide2 (CHSEnumDefine ide1 _ _ _) == (CHSEnumDefine ide2 _ _ _) = ide1 == ide2 (CHSCall _ _ ide1 oalias1 _) == (CHSCall _ _ ide2 oalias2 _) = oalias1 == oalias2 && ide1 == ide2 (CHSFun _ _ ide1 oalias1 _ _ _ _) == (CHSFun _ _ ide2 oalias2 _ _ _ _) = oalias1 == oalias2 && ide1 == ide2 (CHSField acc1 path1 _) == (CHSField acc2 path2 _) = acc1 == acc2 && path1 == path2 (CHSPointer _ ide1 oalias1 _ _ _ _ _) == (CHSPointer _ ide2 oalias2 _ _ _ _ _) = ide1 == ide2 && oalias1 == oalias2 (CHSClass _ ide1 _ _) == (CHSClass _ ide2 _ _) = ide1 == ide2 _ == _ = False -- | translation table -- data CHSTrans = CHSTrans Bool -- underscore to case? CHSChangeCase -- upcase or downcase? [(Ident, Ident)] -- alias list data CHSChangeCase = CHSSameCase | CHSUpCase | CHSDownCase deriving Eq -- | marshalling descriptor for function hooks -- -- * a marshaller consists of a function name and flag indicating whether it -- has to be executed in the IO monad -- data CHSParm = CHSParm (Maybe (Ident, CHSArg)) -- "in" marshaller String -- Haskell type Bool -- C repr: two values? (Maybe (Ident, CHSArg)) -- "out" marshaller Position -- | kinds of arguments in function hooks -- data CHSArg = CHSValArg -- plain value argument | CHSIOArg -- reference argument | CHSVoidArg -- no argument | CHSIOVoidArg -- drops argument, but in monad deriving (Eq) -- | structure member access types -- data CHSAccess = CHSSet -- set structure field | CHSGet -- get structure field deriving (Eq) -- | structure access path -- data CHSAPath = CHSRoot Ident -- root of access path | CHSDeref CHSAPath Position -- dereferencing | CHSRef CHSAPath Ident -- member referencing deriving (Eq,Show) instance Pos CHSAPath where posOf (CHSRoot ide) = posOf ide posOf (CHSDeref _ pos) = pos posOf (CHSRef _ ide) = posOf ide -- | pointer options -- data CHSPtrType = CHSPtr -- standard Ptr from Haskell | CHSForeignPtr -- a pointer with a finalizer | CHSStablePtr -- a pointer into Haskell land deriving (Eq) instance Show CHSPtrType where show CHSPtr = "Ptr" show CHSForeignPtr = "ForeignPtr" show CHSStablePtr = "StablePtr" instance Read CHSPtrType where readsPrec _ ( 'P':'t':'r':rest) = [(CHSPtr, rest)] readsPrec _ ('F':'o':'r':'e':'i':'g':'n':'P':'t':'r':rest) = [(CHSForeignPtr, rest)] readsPrec _ ('S':'t':'a':'b':'l':'e' :'P':'t':'r':rest) = [(CHSStablePtr, rest)] readsPrec p (c:cs) | isSpace c = readsPrec p cs readsPrec _ _ = [] -- load and dump a CHS file -- ------------------------ hssuffix, chssuffix :: String hssuffix = "hs" chssuffix = "chs" -- | load a CHS module -- -- * the file suffix is automagically appended -- -- * in case of a syntactical or lexical error, a fatal error is raised; -- warnings are returned together with the module -- loadCHS :: FilePath -> CST s (CHSModule, String) loadCHS fname = do let fullname = fname <.> chssuffix -- read file -- traceInfoRead fullname contents <- CIO.readFile fullname -- parse -- traceInfoParse mod' <- parseCHSModule (initPos fullname) contents -- check for errors and finalize -- errs <- errorsPresent if errs then do traceInfoErr errmsgs <- showErrors fatal ("CHS module contains \ \errors:\n\n" ++ errmsgs) -- fatal error else do traceInfoOK warnmsgs <- showErrors return (mod', warnmsgs) where traceInfoRead fname' = putTraceStr tracePhasesSW ("Attempting to read file `" ++ fname' ++ "'...\n") traceInfoParse = putTraceStr tracePhasesSW ("...parsing `" ++ fname ++ "'...\n") traceInfoErr = putTraceStr tracePhasesSW ("...error(s) detected in `" ++ fname ++ "'.\n") traceInfoOK = putTraceStr tracePhasesSW ("...successfully loaded `" ++ fname ++ "'.\n") -- | given a file name (no suffix) and a CHS module, the module is printed -- into that file -- -- * the module can be flagged as being pure Haskell -- -- * the correct suffix will automagically be appended -- dumpCHS :: String -> CHSModule -> Bool -> CST s () dumpCHS fname mod' pureHaskell = do let (suffix, kind) = if pureHaskell then (hssuffix , "(Haskell)") else (chssuffix, "(C->HS binding)") CIO.writeFile (fname <.> suffix) (contents version kind) where contents version' kind = "-- GENERATED by " ++ version' ++ " " ++ kind ++ "\n\ \-- Edit the ORIGNAL .chs file instead!\n\n" ++ showCHSModule mod' pureHaskell -- | to keep track of the current state of the line emission automaton -- data LineState = Emit -- emit LINE pragma if next frag is Haskell | Wait -- emit LINE pragma after the next '\n' | NoLine -- no pragma needed deriving (Eq) -- | convert a CHS module into a string -- -- * if the second argument is 'True', all fragments must contain Haskell code -- showCHSModule :: CHSModule -> Bool -> String showCHSModule (CHSModule fragments) pureHaskell = showFrags pureHaskell Emit fragments [] where -- the second argument indicates whether the next fragment (if it is -- Haskell code) should be preceded by a LINE pragma; in particular -- generated fragments and those following them need to be prefixed with a -- LINE pragma -- showFrags :: Bool -> LineState -> [CHSFrag] -> ShowS showFrags _ _ [] = id showFrags pureHs state (CHSVerb s pos : frags) = let (fname,line) = (posFile pos, posRow pos) generated = isBuiltinPos pos emitNow = state == Emit || (state == Wait && not (null s) && head s == '\n') nextState = if generated then Wait else NoLine in (if emitNow then showString ("\n{-# LINE " ++ show (line `max` 0) ++ " " ++ show fname ++ " #-}") else id) . showString s . showFrags pureHs nextState frags showFrags False _ (CHSHook hook : frags) = showString "{#" . showCHSHook hook . showString "#}" . showFrags False Wait frags showFrags False _ (CHSCPP s _ : frags) = showChar '#' . showString s -- . showChar '\n' . showFrags False Emit frags showFrags pureHs _ (CHSLine _s : frags) = showFrags pureHs Emit frags showFrags False _ (CHSC s _ : frags) = showString "\n#c" . showString s . showString "\n#endc" . showFrags False Emit frags showFrags False _ (CHSCond _ _ : _ ) = interr "showCHSFrag: Cannot print `CHSCond'!" showFrags True _ _ = interr "showCHSFrag: Illegal hook, cpp directive, or inline C code!" showCHSHook :: CHSHook -> ShowS showCHSHook (CHSImport isQual ide _ _) = showString "import " . (if isQual then showString "qualified " else id) . showCHSIdent ide showCHSHook (CHSContext olib oprefix _) = showString "context " . (case olib of Nothing -> showString "" Just lib -> showString "lib = " . showString lib . showString " ") . showPrefix oprefix False showCHSHook (CHSType ide _) = showString "type " . showCHSIdent ide showCHSHook (CHSSizeof ide _) = showString "sizeof " . showCHSIdent ide showCHSHook (CHSAlignof ide _) = showString "alignof " . showCHSIdent ide showCHSHook (CHSEnum ide oalias trans oprefix derive _) = showString "enum " . showIdAlias ide oalias . showCHSTrans trans . showPrefix oprefix True . if null derive then id else showString $ "deriving (" ++ concat (intersperse ", " (map identToString derive)) ++ ") " showCHSHook (CHSEnumDefine ide trans derive _) = showString "enum define " . showCHSIdent ide . showCHSTrans trans . if null derive then id else showString $ "deriving (" ++ concat (intersperse ", " (map identToString derive)) ++ ") " showCHSHook (CHSCall isPure isUns ide oalias _) = showString "call " . (if isPure then showString "pure " else id) . (if isUns then showString "unsafe " else id) . showApAlias ide oalias showCHSHook (CHSFun isPure isUns ide oalias octxt parms parm _) = showString "fun " . (if isPure then showString "pure " else id) . (if isUns then showString "unsafe " else id) . showApAlias ide oalias . (case octxt of Nothing -> showChar ' ' Just ctxtStr -> showString ctxtStr . showString " => ") . showString "{" . foldr (.) id (intersperse (showString ", ") (map showCHSParm parms)) . showString "} -> " . showCHSParm parm showCHSHook (CHSField acc path _) = (case acc of CHSGet -> showString "get " CHSSet -> showString "set ") . showCHSAPath path showCHSHook (CHSPointer star ide oalias ptrType isNewtype oRefType emit _) = showString "pointer " . (if star then showString "*" else showString "") . showIdAlias ide oalias . (case ptrType of CHSForeignPtr -> showString " foreign" CHSStablePtr -> showString " stable" _ -> showString "") . (case (isNewtype, oRefType) of (True , _ ) -> showString " newtype" (False, Just ide') -> showString " -> " . showCHSIdent ide' (False, Nothing ) -> showString "") . (case emit of True -> showString "" False -> showString " nocode") showCHSHook (CHSClass oclassIde classIde typeIde _) = showString "class " . (case oclassIde of Nothing -> showString "" Just classIde' -> showCHSIdent classIde' . showString " => ") . showCHSIdent classIde . showString " " . showCHSIdent typeIde showPrefix :: Maybe String -> Bool -> ShowS showPrefix Nothing _ = showString "" showPrefix (Just prefix) withWith = maybeWith . showString "prefix = " . showString prefix . showString " " where maybeWith = if withWith then showString "with " else id showIdAlias :: Ident -> Maybe Ident -> ShowS showIdAlias ide oalias = showCHSIdent ide . (case oalias of Nothing -> id Just ide' -> showString " as " . showCHSIdent ide') showApAlias :: CHSAPath -> Maybe Ident -> ShowS showApAlias apath oalias = showCHSAPath apath . (case oalias of Nothing -> id Just ide -> showString " as " . showCHSIdent ide) showCHSParm :: CHSParm -> ShowS showCHSParm (CHSParm oimMarsh hsTyStr twoCVals oomMarsh _) = showOMarsh oimMarsh . showChar ' ' . showHsVerb hsTyStr . (if twoCVals then showChar '&' else id) . showChar ' ' . showOMarsh oomMarsh where showOMarsh Nothing = id showOMarsh (Just (ide, argKind)) = showCHSIdent ide . (case argKind of CHSValArg -> id CHSIOArg -> showString "*" CHSVoidArg -> showString "-" CHSIOVoidArg -> showString "*-") -- showHsVerb str = showChar '`' . showString str . showChar '\'' showCHSTrans :: CHSTrans -> ShowS showCHSTrans (CHSTrans _2Case chgCase assocs) = showString "{" . (if _2Case then showString ("underscoreToCase" ++ maybeComma) else id) . showCHSChangeCase chgCase . foldr (.) id (intersperse (showString ", ") (map showAssoc assocs)) . showString "}" where maybeComma = if null assocs then "" else ", " -- showAssoc (ide1, ide2) = showCHSIdent ide1 . showString " as " . showCHSIdent ide2 showCHSChangeCase :: CHSChangeCase -> ShowS showCHSChangeCase CHSSameCase = id showCHSChangeCase CHSUpCase = showString "upcaseFirstLetter" showCHSChangeCase CHSDownCase = showString "downcaseFirstLetter" showCHSAPath :: CHSAPath -> ShowS showCHSAPath (CHSRoot ide) = showCHSIdent ide showCHSAPath (CHSDeref path _) = showString "* " . showCHSAPath path showCHSAPath (CHSRef (CHSDeref path _) ide) = showCHSAPath path . showString "->" . showCHSIdent ide showCHSAPath (CHSRef path ide) = showCHSAPath path . showString "." . showCHSIdent ide showCHSIdent :: Ident -> ShowS showCHSIdent = showString . identToString -- load and dump a CHI file -- ------------------------ chisuffix :: String chisuffix = "chi" versionPrefix :: String versionPrefix = "C->Haskell Interface Version " -- | load a CHI file -- -- * the file suffix is automagically appended -- -- * any error raises a syntax exception (see below) -- -- * the version of the .chi file is checked against the version of the current -- executable; they must match in the major and minor version -- loadCHI :: FilePath -> CST s String loadCHI fname = do -- search for .chi files -- paths <- getSwitch chiPathSB let fullnames = [path </> fname <.> chisuffix | path <- paths] fullname <- findFirst fullnames (fatal $ fname <.> chisuffix ++ " not found in:\n"++ unlines paths) -- read file -- traceInfoRead fullname contents <- CIO.readFile fullname -- parse -- traceInfoVersion let ls = lines contents when (null ls) $ errorCHICorrupt fname let versline:chi = ls prefixLen = length versionPrefix when (length versline < prefixLen || take prefixLen versline /= versionPrefix) $ errorCHICorrupt fname let versline' = drop prefixLen versline (major, minor) <- case majorMinor versline' of Nothing -> errorCHICorrupt fname Just majMin -> return majMin let Just (myMajor, myMinor) = majorMinor version when (major /= myMajor || minor /= myMinor) $ errorCHIVersion fname (major ++ "." ++ minor) (myMajor ++ "." ++ myMinor) -- finalize -- traceInfoOK return $ concat chi where traceInfoRead fname' = putTraceStr tracePhasesSW ("Attempting to read file `" ++ fname' ++ "'...\n") traceInfoVersion = putTraceStr tracePhasesSW ("...checking version `" ++ fname ++ "'...\n") traceInfoOK = putTraceStr tracePhasesSW ("...successfully loaded `" ++ fname ++ "'.\n") findFirst [] err = err findFirst (p:aths) err = do e <- CIO.doesFileExist p if e then return p else findFirst aths err -- | given a file name (no suffix) and a CHI file, the information is printed -- into that file -- -- * the correct suffix will automagically be appended -- dumpCHI :: String -> String -> CST s () dumpCHI fname contents = do CIO.writeFile (fname <.> chisuffix) $ versionPrefix ++ version ++ "\n" ++ contents -- | extract major and minor number from a version string -- majorMinor :: String -> Maybe (String, String) majorMinor vers = let (major, rest) = break (== '.') vers (minor, _ ) = break (== '.') . tail $ rest in if null rest then Nothing else Just (major, minor) -- parsing a CHS token stream -- -------------------------- syntaxExc :: String syntaxExc = "syntax" -- | alternative action in case of a syntax exception -- ifError :: CST s a -> CST s a -> CST s a ifError action handler = action `catchExc` (syntaxExc, const handler) -- | raise syntax error exception -- raiseSyntaxError :: CST s a raiseSyntaxError = throwExc syntaxExc "syntax error" -- | parse a complete module -- -- * errors are entered into the compiler state -- parseCHSModule :: Position -> String -> CST s CHSModule parseCHSModule pos cs = do toks <- lexCHS cs pos frags <- parseFrags toks return (CHSModule frags) -- | parsing of code fragments -- -- * in case of an error, all tokens that are neither Haskell nor control -- tokens are skipped; afterwards parsing continues -- -- * when encountering inline-C code we scan forward over all inline-C and -- control tokens to avoid turning the control tokens within a sequence of -- inline-C into Haskell fragments -- parseFrags :: [CHSToken] -> CST s [CHSFrag] parseFrags tokens = do parseFrags0 tokens `ifError` contFrags tokens where parseFrags0 :: [CHSToken] -> CST s [CHSFrag] parseFrags0 [] = return [] parseFrags0 (CHSTokHaskell pos s:toks) = do frags <- parseFrags toks return $ CHSVerb s pos : frags parseFrags0 (CHSTokCtrl pos c:toks) = do frags <- parseFrags toks return $ CHSVerb [c] pos : frags parseFrags0 (CHSTokCPP pos s:toks) = do frags <- parseFrags toks return $ CHSCPP s pos : frags parseFrags0 (CHSTokLine pos :toks) = do frags <- parseFrags toks return $ CHSLine pos : frags parseFrags0 (CHSTokC pos s:toks) = parseC pos s toks parseFrags0 (CHSTokImport pos :toks) = parseImport pos toks parseFrags0 (CHSTokContext pos :toks) = parseContext pos toks parseFrags0 (CHSTokType pos :toks) = parseType pos toks parseFrags0 (CHSTokSizeof pos :toks) = parseSizeof pos toks parseFrags0 (CHSTokAlignof pos :toks) = parseAlignof pos toks parseFrags0 (CHSTokEnum pos :toks) = parseEnum pos toks parseFrags0 (CHSTokCall pos :toks) = parseCall pos toks parseFrags0 (CHSTokFun pos :toks) = parseFun pos toks parseFrags0 (CHSTokGet pos :toks) = parseField pos CHSGet toks parseFrags0 (CHSTokSet pos :toks) = parseField pos CHSSet toks parseFrags0 (CHSTokClass pos :toks) = parseClass pos toks parseFrags0 (CHSTokPointer pos :toks) = parsePointer pos toks parseFrags0 toks = syntaxError toks -- -- skip to next Haskell or control token -- contFrags [] = return [] contFrags toks@(CHSTokHaskell _ _:_ ) = parseFrags toks contFrags toks@(CHSTokCtrl _ _:_ ) = parseFrags toks contFrags (_ :toks) = contFrags toks parseC :: Position -> String -> [CHSToken] -> CST s [CHSFrag] parseC pos s toks = do frags <- collectCtrlAndC toks return $ CHSC s pos : frags where collectCtrlAndC (CHSTokCtrl pos' c :toks') = do frags <- collectCtrlAndC toks' return $ CHSC [c] pos' : frags collectCtrlAndC (CHSTokC pos' s':toks') = do frags <- collectCtrlAndC toks' return $ CHSC s' pos' : frags collectCtrlAndC toks' = parseFrags toks' parseImport :: Position -> [CHSToken] -> CST s [CHSFrag] parseImport pos toks = do (qual, modid, toks') <- case toks of CHSTokIdent _ ide :toks' -> let (ide', toks'') = rebuildModuleId ide toks' in return (False, ide', toks'') CHSTokQualif _: CHSTokIdent _ ide:toks' -> let (ide', toks'') = rebuildModuleId ide toks' in return (True , ide', toks'') _ -> syntaxError toks chi <- loadCHI . moduleNameToFileName . identToString $ modid toks'2 <- parseEndHook toks' frags <- parseFrags toks'2 return $ CHSHook (CHSImport qual modid chi pos) : frags -- | Qualified module names do not get lexed as a single token so we need to -- reconstruct it from a sequence of identifer and dot tokens. -- rebuildModuleId :: Ident -> [CHSToken] -> (Ident, [CHSToken]) rebuildModuleId ide (CHSTokDot _ : CHSTokIdent _ ide' : toks) = let catIdent ide'3 ide'4 = internalIdentAt (posOf ide'3) --FIXME: unpleasant hack (identToString ide'3 ++ '.' : identToString ide'4) in rebuildModuleId (catIdent ide ide') toks rebuildModuleId ide toks = (ide, toks) moduleNameToFileName :: String -> FilePath moduleNameToFileName = map dotToSlash where dotToSlash '.' = '/' dotToSlash c = c parseContext :: Position -> [CHSToken] -> CST s [CHSFrag] parseContext pos toks = do (olib , toks'2 ) <- parseOptLib toks (opref , toks'3) <- parseOptPrefix False toks'2 toks'4 <- parseEndHook toks'3 frags <- parseFrags toks'4 let frag = CHSContext olib opref pos return $ CHSHook frag : frags parseType :: Position -> [CHSToken] -> CST s [CHSFrag] parseType pos (CHSTokIdent _ ide:toks) = do toks' <- parseEndHook toks frags <- parseFrags toks' return $ CHSHook (CHSType ide pos) : frags parseType _ toks = syntaxError toks parseSizeof :: Position -> [CHSToken] -> CST s [CHSFrag] parseSizeof pos (CHSTokIdent _ ide:toks) = do toks' <- parseEndHook toks frags <- parseFrags toks' return $ CHSHook (CHSSizeof ide pos) : frags parseSizeof _ toks = syntaxError toks parseAlignof :: Position -> [CHSToken] -> CST s [CHSFrag] parseAlignof pos (CHSTokIdent _ ide:toks) = do toks' <- parseEndHook toks frags <- parseFrags toks' return $ CHSHook (CHSAlignof ide pos) : frags parseAlignof _ toks = syntaxError toks parseEnum :: Position -> [CHSToken] -> CST s [CHSFrag] -- {#enum define hsid {alias_1,...,alias_n} [deriving (clid_1,...,clid_n)] #} parseEnum pos (CHSTokIdent _ def: CHSTokIdent _ hsid: toks) | identToString def == "define" = do (trans , toks') <- parseTrans toks (derive, toks'') <- parseDerive toks' toks''' <- parseEndHook toks'' frags <- parseFrags toks''' return $ CHSHook (CHSEnumDefine hsid trans derive pos) : frags -- {#enum cid [as hsid] {alias_1,...,alias_n} [with prefix = pref] [deriving (clid_1,...,clid_n)] #} parseEnum pos (CHSTokIdent _ ide:toks) = do (oalias, toks' ) <- parseOptAs ide True toks (trans , toks'') <- parseTrans toks' (oprefix, toks''') <- parseOptPrefix True toks'' (derive, toks'''') <- parseDerive toks''' toks''''' <- parseEndHook toks'''' frags <- parseFrags toks''''' return $ CHSHook (CHSEnum ide (norm oalias) trans oprefix derive pos) : frags where norm Nothing = Nothing norm (Just ide') | ide == ide' = Nothing | otherwise = Just ide' parseEnum _ toks = syntaxError toks parseCall :: Position -> [CHSToken] -> CST s [CHSFrag] parseCall pos toks = do (isPure , toks' ) <- parseIsPure toks (isUnsafe, toks'' ) <- parseIsUnsafe toks' (apath , toks''' ) <- parsePath toks'' (oalias , toks'''') <- parseOptAs (apathToIdent apath) False toks''' toks''''' <- parseEndHook toks'''' frags <- parseFrags toks''''' return $ CHSHook (CHSCall isPure isUnsafe apath oalias pos) : frags parseFun :: Position -> [CHSToken] -> CST s [CHSFrag] parseFun pos toks = do (isPure , toks' ) <- parseIsPure toks (isUnsafe, toks'2) <- parseIsUnsafe toks' (apath , toks'3) <- parsePath toks'2 (oalias , toks'4) <- parseOptAs (apathToIdent apath) False toks'3 (octxt , toks'5) <- parseOptContext toks'4 (parms , toks'6) <- parseParms toks'5 (parm , toks'7) <- parseParm toks'6 toks'8 <- parseEndHook toks'7 frags <- parseFrags toks'8 return $ CHSHook (CHSFun isPure isUnsafe apath oalias octxt parms parm pos) : frags where parseOptContext (CHSTokHSVerb _ ctxt:CHSTokDArrow _:toks') = return (Just ctxt, toks') parseOptContext toks' = return (Nothing , toks') -- parseParms (CHSTokLBrace _:CHSTokRBrace _:CHSTokArrow _:toks') = return ([], toks') parseParms (CHSTokLBrace _ :toks') = parseParms' (CHSTokComma nopos:toks') parseParms toks' = syntaxError toks' -- parseParms' (CHSTokRBrace _:CHSTokArrow _:toks') = return ([], toks') parseParms' (CHSTokComma _ :toks') = do (parm , toks'2 ) <- parseParm toks' (parms, toks'3) <- parseParms' toks'2 return (parm:parms, toks'3) parseParms' (CHSTokRBrace _ :toks') = syntaxError toks' -- gives better error messages parseParms' toks' = syntaxError toks' parseIsPure :: [CHSToken] -> CST s (Bool, [CHSToken]) parseIsPure (CHSTokPure _:toks) = return (True , toks) parseIsPure (CHSTokFun _:toks) = return (True , toks) -- backwards compat. parseIsPure toks = return (False, toks) -- FIXME: eventually, remove `fun'; it's currently deprecated parseIsUnsafe :: [CHSToken] -> CST s (Bool, [CHSToken]) parseIsUnsafe (CHSTokUnsafe _:toks) = return (True , toks) parseIsUnsafe toks = return (False, toks) apathToIdent :: CHSAPath -> Ident apathToIdent (CHSRoot ide) = let lowerFirst (c:cs) = toLower c : cs in internalIdentAt (posOf ide) (lowerFirst $ identToString ide) apathToIdent (CHSDeref apath _) = let ide = apathToIdent apath in internalIdentAt (posOf ide) (identToString ide ++ "_") apathToIdent (CHSRef apath ide') = let ide = apathToIdent apath upperFirst (c:cs) = toLower c : cs sel = upperFirst $ identToString ide' in internalIdentAt (posOf ide) (identToString ide ++ sel) parseParm :: [CHSToken] -> CST s (CHSParm, [CHSToken]) parseParm toks = do (oimMarsh, toks' ) <- parseOptMarsh toks (hsTyStr, twoCVals, pos, toks'2) <- case toks' of (CHSTokHSVerb pos hsTyStr:CHSTokAmp _:toks'2) -> return (hsTyStr, True , pos, toks'2) (CHSTokHSVerb pos hsTyStr :toks'2) -> return (hsTyStr, False, pos, toks'2) _toks -> syntaxError toks' (oomMarsh, toks'3) <- parseOptMarsh toks'2 return (CHSParm oimMarsh hsTyStr twoCVals oomMarsh pos, toks'3) where parseOptMarsh :: [CHSToken] -> CST s (Maybe (Ident, CHSArg), [CHSToken]) parseOptMarsh (CHSTokIdent _ ide:CHSTokStar _ :CHSTokMinus _:toks') = return (Just (ide, CHSIOVoidArg) , toks') parseOptMarsh (CHSTokIdent _ ide:CHSTokStar _ :toks') = return (Just (ide, CHSIOArg) , toks') parseOptMarsh (CHSTokIdent _ ide:CHSTokMinus _:toks') = return (Just (ide, CHSVoidArg), toks') parseOptMarsh (CHSTokIdent _ ide :toks') = return (Just (ide, CHSValArg) , toks') parseOptMarsh toks' = return (Nothing, toks') parseField :: Position -> CHSAccess -> [CHSToken] -> CST s [CHSFrag] parseField pos access toks = do (path, toks') <- parsePath toks toks'' <- parseEndHook toks' frags <- parseFrags toks'' return $ CHSHook (CHSField access path pos) : frags parsePointer :: Position -> [CHSToken] -> CST s [CHSFrag] parsePointer pos toks = do (isStar, ide, toks') <- case toks of CHSTokStar _:CHSTokIdent _ ide:toks' -> return (True , ide, toks') CHSTokIdent _ ide :toks' -> return (False, ide, toks') _ -> syntaxError toks (oalias , toks'2) <- parseOptAs ide True toks' (ptrType, toks'3) <- parsePtrType toks'2 let (isNewtype, oRefType, toks'4) = case toks'3 of CHSTokNewtype _ :toks'' -> (True , Nothing , toks'' ) CHSTokArrow _:CHSTokIdent _ ide':toks'' -> (False, Just ide', toks'' ) _ -> (False, Nothing , toks'3) let (emit, toks'5) = case toks'4 of CHSTokNocode _ :toks'' -> (False, toks'' ) _ -> (True , toks'4 ) toks'6 <- parseEndHook toks'5 frags <- parseFrags toks'6 return $ CHSHook (CHSPointer isStar ide (norm ide oalias) ptrType isNewtype oRefType emit pos) : frags where parsePtrType :: [CHSToken] -> CST s (CHSPtrType, [CHSToken]) parsePtrType (CHSTokForeign _:toks') = return (CHSForeignPtr, toks') parsePtrType (CHSTokStable _ :toks') = return (CHSStablePtr, toks') parsePtrType toks' = return (CHSPtr, toks') norm _ Nothing = Nothing norm ide (Just ide') | ide == ide' = Nothing | otherwise = Just ide' parseClass :: Position -> [CHSToken] -> CST s [CHSFrag] parseClass pos (CHSTokIdent _ sclassIde: CHSTokDArrow _ : CHSTokIdent _ classIde : CHSTokIdent _ typeIde : toks) = do toks' <- parseEndHook toks frags <- parseFrags toks' return $ CHSHook (CHSClass (Just sclassIde) classIde typeIde pos) : frags parseClass pos (CHSTokIdent _ classIde : CHSTokIdent _ typeIde : toks) = do toks' <- parseEndHook toks frags <- parseFrags toks' return $ CHSHook (CHSClass Nothing classIde typeIde pos) : frags parseClass _ toks = syntaxError toks parseOptLib :: [CHSToken] -> CST s (Maybe String, [CHSToken]) parseOptLib (CHSTokLib _ : CHSTokEqual _ : CHSTokString _ str: toks) = return (Just str, toks) parseOptLib (CHSTokLib _:toks ) = syntaxError toks parseOptLib toks = return (Nothing, toks) parseOptPrefix :: Bool -> [CHSToken] -> CST s (Maybe String, [CHSToken]) parseOptPrefix False (CHSTokPrefix _ : CHSTokEqual _ : CHSTokString _ str: toks) = return (Just str, toks) parseOptPrefix True (CHSTokWith _ : CHSTokPrefix _ : CHSTokEqual _ : CHSTokString _ str: toks) = return (Just str, toks) parseOptPrefix _ (CHSTokWith _:toks) = syntaxError toks parseOptPrefix _ (CHSTokPrefix _:toks) = syntaxError toks parseOptPrefix _ toks = return (Nothing, toks) -- first argument is the identifier that is to be used when `^' is given and -- the second indicates whether the first character has to be upper case -- parseOptAs :: Ident -> Bool -> [CHSToken] -> CST s (Maybe Ident, [CHSToken]) parseOptAs _ _ (CHSTokAs _:CHSTokIdent _ ide:toks) = return (Just ide, toks) parseOptAs ide upper (CHSTokAs _:CHSTokHat pos :toks) = return (Just $ underscoreToCase ide upper pos, toks) parseOptAs _ _ (CHSTokAs _ :toks) = syntaxError toks parseOptAs _ _ toks = return (Nothing, toks) -- | convert C style identifier to Haskell style identifier -- underscoreToCase :: Ident -> Bool -> Position -> Ident underscoreToCase ide upper pos = let lexeme = identToString ide ps = filter (not . null) . parts $ lexeme in internalIdentAt pos . adjustHead . concat . map adjustCase $ ps where parts s = let (l, s') = break (== '_') s in l : case s' of [] -> [] (_:s'') -> parts s'' -- adjustCase "" = "" adjustCase (c:cs) = toUpper c : cs -- adjustHead "" = "" adjustHead (c:cs) = if upper then toUpper c : cs else toLower c:cs -- | this is disambiguated and left factored -- parsePath :: [CHSToken] -> CST s (CHSAPath, [CHSToken]) parsePath (CHSTokLParen _pos: toks) = do (inner_path, toks_rest) <- parsePath toks toks_rest' <- case toks_rest of (CHSTokRParen _pos' : ts) -> return ts _ -> syntaxError toks_rest (pathWithHole, toks') <- parsePath' toks_rest' return (pathWithHole inner_path, toks') parsePath (CHSTokStar pos:toks) = do (path, toks') <- parsePath toks return (CHSDeref path pos, toks') parsePath (tok:toks) = case keywordToIdent tok of (CHSTokIdent _ ide) -> do (pathWithHole, toks') <- parsePath' toks return (pathWithHole (CHSRoot ide), toks') _ -> syntaxError (tok:toks) parsePath toks = syntaxError toks -- | @s->m@ is represented by @(*s).m@ in the tree -- parsePath' :: [CHSToken] -> CST s (CHSAPath -> CHSAPath, [CHSToken]) parsePath' tokens@(CHSTokDot _:desig:toks) = do ide <- case keywordToIdent desig of CHSTokIdent _ i -> return i; _ -> syntaxError tokens (pathWithHole, toks') <- parsePath' toks return (pathWithHole . (\hole -> CHSRef hole ide), toks') parsePath' tokens@(CHSTokArrow pos:desig:toks) = do ide <- case keywordToIdent desig of CHSTokIdent _ i -> return i; _ -> syntaxError tokens (pathWithHole, toks') <- parsePath' toks return (pathWithHole . (\hole -> CHSRef (CHSDeref hole pos) ide), toks') parsePath' toks = return (id,toks) parseTrans :: [CHSToken] -> CST s (CHSTrans, [CHSToken]) parseTrans (CHSTokLBrace _:toks) = do (_2Case, chgCase, toks' ) <- parse_2CaseAndChange toks case toks' of (CHSTokRBrace _:toks'2) -> return (CHSTrans _2Case chgCase [], toks'2) _ -> do -- if there was no `underscoreToCase', we add a comma token to meet -- the invariant of `parseTranss' -- (transs, toks'2) <- if (_2Case || chgCase /= CHSSameCase) then parseTranss toks' else parseTranss (CHSTokComma nopos:toks') return (CHSTrans _2Case chgCase transs, toks'2) where parse_2CaseAndChange (CHSTok_2Case _:CHSTokComma _:CHSTokUpper _:toks') = return (True, CHSUpCase, toks') parse_2CaseAndChange (CHSTok_2Case _:CHSTokComma _:CHSTokDown _ :toks') = return (True, CHSDownCase, toks') parse_2CaseAndChange (CHSTok_2Case _ :toks') = return (True, CHSSameCase, toks') parse_2CaseAndChange (CHSTokUpper _:CHSTokComma _:CHSTok_2Case _:toks') = return (True, CHSUpCase, toks') parse_2CaseAndChange (CHSTokUpper _ :toks') = return (False, CHSUpCase, toks') parse_2CaseAndChange (CHSTokDown _:CHSTokComma _:CHSTok_2Case _:toks') = return (True, CHSDownCase, toks') parse_2CaseAndChange (CHSTokDown _ :toks') = return (False, CHSDownCase, toks') parse_2CaseAndChange toks' = return (False, CHSSameCase, toks') -- parseTranss (CHSTokRBrace _:toks') = return ([], toks') parseTranss (CHSTokComma _:toks') = do (assoc, toks'2 ) <- parseAssoc toks' (trans, toks'3) <- parseTranss toks'2 return (assoc:trans, toks'3) parseTranss toks' = syntaxError toks' -- parseAssoc (CHSTokIdent _ ide1:CHSTokAs _:CHSTokIdent _ ide2:toks') = return ((ide1, ide2), toks') parseAssoc (CHSTokIdent _ _ :CHSTokAs _:toks' ) = syntaxError toks' parseAssoc (CHSTokIdent _ _ :toks' ) = syntaxError toks' parseAssoc toks' = syntaxError toks' parseTrans toks = syntaxError toks parseDerive :: [CHSToken] -> CST s ([Ident], [CHSToken]) parseDerive (CHSTokDerive _ :CHSTokLParen _:CHSTokRParen _:toks) = return ([], toks) parseDerive (CHSTokDerive _ :CHSTokLParen _:toks) = parseCommaIdent (CHSTokComma nopos:toks) where parseCommaIdent :: [CHSToken] -> CST s ([Ident], [CHSToken]) parseCommaIdent (CHSTokComma _:CHSTokIdent _ ide:toks') = do (ids, tok') <- parseCommaIdent toks' return (ide:ids, tok') parseCommaIdent (CHSTokRParen _ :toks') = return ([], toks') parseDerive toks = return ([],toks) parseEndHook :: [CHSToken] -> CST s ([CHSToken]) parseEndHook (CHSTokEndHook _:toks) = return toks parseEndHook toks = syntaxError toks syntaxError :: [CHSToken] -> CST s a syntaxError [] = errorEOF syntaxError (tok:_) = errorIllegal tok errorIllegal :: CHSToken -> CST s a errorIllegal tok = do raiseError (posOf tok) ["Syntax error!", "The phrase `" ++ show tok ++ "' is not allowed \ \here."] raiseSyntaxError errorEOF :: CST s a errorEOF = do raiseError nopos ["Premature end of file!", "The .chs file ends in the middle of a binding hook."] raiseSyntaxError errorCHICorrupt :: String -> CST s a errorCHICorrupt ide = do raiseError nopos ["Corrupt .chi file!", "The file `" ++ ide ++ ".chi' is corrupt."] raiseSyntaxError errorCHIVersion :: String -> String -> String -> CST s a errorCHIVersion ide chiVersion myVersion = do raiseError nopos ["Wrong version of .chi file!", "The file `" ++ ide ++ ".chi' is version " ++ chiVersion ++ ", but mine is " ++ myVersion ++ "."] raiseSyntaxError
jrockway/c2hs
src/C2HS/CHS.hs
gpl-2.0
52,005
0
21
19,178
12,473
6,395
6,078
909
22
{-# OPTIONS -fglasgow-exts -fno-monomorphism-restriction #-} ---------------------------------------------------------------------------- -- | -- Module : Text.XML.Schema.Org.Xmlsoap.Schemas.Wsdl -- Copyright : (c) Simon Foster 2004 -- License : GPL version 2 (see COPYING) -- -- Maintainer : aca01sdf@shef.ac.uk -- Stability : experimental -- Portability : non-portable (ghc >= 6 only) -- -- A Haskell representation of the abstract part of a WSDL document. See the long comment in source -- below for details. -- -- This is a work in progress. -- -- @This file is part of HAIFA.@ -- -- @HAIFA is free software; you can redistribute it and\/or modify it under the terms of the -- GNU General Public License as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version.@ -- -- @HAIFA is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without -- even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details.@ -- -- @You should have received a copy of the GNU General Public License along with HAIFA; if not, -- write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA@ ---------------------------------------------------------------------------- module Text.XML.Schema.Org.Xmlsoap.Schemas.Wsdl where {- WSDL is used to define the complete functionality of a particular web-service on the internet. It is highly extensible in nature an can be turned to define web-services of many different types, provided the clients now how to interpret this data. At the lowest level WSDL defines a number of types which can be used by the functions or methods of the web-service. Any conceivable system can be employed to define these types, although atm the most commonly used system is XSD, mainly because most end-points can understand this and map types to their own type system. Once my XSD implementation is useable (I won't say complete, because this implies that it can map an conceivable XSD data-type, and I don't see it ever being capable of this) this will also be true for Haskell. Once a set of types have been defined, these can be encapsulated into a set of abstract messages. When being used for RPC, each message can be seen as a set of input or output parameters from a particular method or function. In Haskell, we a set of data-types should be defined for the messages, one for each. A message will most of the time map to a struct of elements which can then be carried by the messaging protocol as the payload. Once a set of message have been defined, these can be grouped together to form port types, each of which contains a set of abstract operations, suitable for binding to a particular concrete protocol (e.g. SOAP). Each operation defines a message as input and optionally a message as output (NB that operations are not neccessarily procedure calls and are not always 2 way, even in Haskell; a -> IO ()). In Haskell each operation in each portType can be seen as a type definition for a function, so if an operation defines that the input message is MyInput and the output message is MyOutput, any concrete implementations of this operation in Haskell should have the type MyInput -> IO MyOutput, regardless of the concrete protocol being used to execute the operation. Once you have an abstract port type, it is neccessary to actually bind this to a concrete protocol. There are several protocols to which WSDL's operations can be bound (see schemas.xmlsoap.org/*), but for the time being we mainly focus on SOAP. A Binding essentially defines how a particular operation should be encapsulated within the protocol's packet system (e.g. SOAP Envelope) and how faults should be handled. As far as Haskell goes, each binding defines the actual body of the function, how the message data-type should be packaged up and how it should be sent to the end-point (although we don't yet know what this endpoint is). The WSDL SOAP Binding defines what sort of operation is being performed (RPC or Document), the protocol that is being used to "execute" the SOAP Envelope (e.g. HTTP/1.1) and the encoding rules for the SOAP Envelope. A typical Haskell function for performing an operation using SOAP over HTTP would wrap the message in a SOAP Envelope, serialize it to XML, send it over HTTP to the endpoint, wait for a response, deserialize it back to a SOAP Envelope and extract the contents. The process of dealing with binding is non-trivial since it requires a completely extensible system for each binding. This can either be achieved by partially deserializing the WSDL document (i.e. only the parts defined by WSDL) and then storing the remaining elements as XML in the data-type, a hook system can then be used to define how the function body should be built. Or if the type of the service is already known (unlikely so not used) another type-parameter can be added to the definitions data type, with an encoder to extract the protocol's parameters. Either way, once a set of concrete functions has been defined, it is necessary to define the endpoint which this data should be directed at. This is done the service element, which is again extensible, so as to allow different types of address structures to be stored. Although for SOAP/HTTP clearly a URI is stored. -} import qualified Prelude import Prelude -- ((/=), (&&), return, ($), Show, head, show, undefined, (++)) import qualified Text.XML.Schema.Org.W3.N2001.XMLSchema as XSD import Network.URI import Text.XML.Serializer import Data.Generics import Data.Typeable import Data.List import Text.XML.HXT.Parser hiding (trace) import Data.Maybe import Text.XML.HXT.Aliases import Debug.Trace import Text.XML.Schema.TypeMapper import Text.XML.Schema.ModuleGen import Control.Monad import Control.Monad.State import Control.Monad.Error import Utils import Text.Regex thisNamespace = "http://schemas.xmlsoap.org/wsdl" tns = thisNamespace defaultPrefix = "wsdl" hook = this servicePrefix = "Network.Services." data OtherElem = OtherElem{ fromOElem::XmlTrees } deriving (Data, Typeable, Show) {-encodeOtherElem xdb (OtherAttribute l) = Just $ [map (\(k,v) -> let nst = getNST xdb; q = resolveQName nst k in attr (aName q) (mkXText v)) l]-} decoder :: DecFunc decoder d = result where result = (return Nothing) `extR` decodeOtherElem -- FIXME : Get the encodeOtherElem encoder to work. encoder :: EncFunc encoder = encodeNull otherNS :: XmlFilter otherNS = isOfQName (\(QN _ _ x) -> ((x/="")&&(x/=tns))) isOfQName :: (QName -> Prelude.Bool) -> XmlFilter isOfQName p t = case t of NTree (XTag n _) _ -> if (p n) then [t] else [] NTree (XAttr n) _ -> if (p n) then [t] else [] _ -> [] decodeOtherElem = do e <- readXElemFilter otherNS return $ Just $ OtherElem e type TypeHandler = XmlTree -> NamespaceTable -> URI -> FilePath -> IO () processXSD :: TypeHandler processXSD xml nst u p = do let d = deserialize (addNST nst $ newXDB) XSD.decoder xml case (hasLocalPart "schema" xml) of [] -> mzero _ -> case d of Nothing -> return () Just x -> do let tns = case (XSD.a_xs_targetNamespace x) of Nothing -> u Just x -> x --print $ (hierarchyPrefix ++ (concat $ intersperse "." $ backwardURI' tns)) generateTypes nst [soapArrayHook] (XSD.e_xs_complexType x) tns p processWSDL :: Definitions -> [TypeHandler] -> NamespaceTable -> FilePath -> IO () processWSDL d h nst p = do if ((isNothing $ a_def_targetNamespace d) && (isNothing $ a_def_name d)) then fail "There must be either a target namespace or name available in a WSDL document in order to qualify it." else return () let n = (++) servicePrefix $ fromJust $ (do x <- a_def_name d return $ (uri2Hierarchy x) ++ "." `mplus` (if ((==) 1 $ length $ e_def_service d) then (Just $ (a_service_name $ (e_def_service d) !! 0) ++ ".") else Nothing) `mplus` do x <- a_def_targetNamespace d return $ (uri2Hierarchy x) ++ "." `mplus` return "") -- HO HUM! u = case (a_def_targetNamespace d) of Just x -> (hierarchyPrefix++(uri2Hierarchy x)) Nothing -> n print $ length $ (e_def_types d) foldr (mplus . \f -> mapM (\x -> f x nst (fromJust $ a_def_targetNamespace d) p) (e_def_types d)) mzero h createModule u p inst <- getImportNST u p let s = MS { xmlNST = nst , nstable = inst , targetNS = u , hooks = [] , ttable = [] } let (m, s') = runMessMapper s (e_def_message d) mess = catMaybes m o = concat $ intersperse "\n\n" $ map outputHaskellType mess --print m th <- getByRegex (mkRegex "^thisNamespace = .*$") u p print th if (not $ null th) then return () else do hd <- getSection "HEADER" u p let hn = concat [ "thisNamespace = \"", (a_def_targetNamespace d) ?> (show . fromJust, ""), "\"\n" , "tns = thisNamespace\n" , "encoder = encodeNull\n" , "decoder = decodeNull\n" , "hook = hookNull\n" ] setSection (hn++(concat $ intersperse "\n" $ hd ?> (fromJust, []))) "HEADER" u p setSection o "MESSAGES" u p setSection (outImports (nstable s') u) "NS_IMPORT" u p runPortTypeMapper nst u (e_def_portType d) return () --runTypeHandler f (h:t) = do x <- f where runMessMapper s [] = ([], s) runMessMapper m (h:t) = let s = execStateT (mapMessage h) m; (m', s') = runMessMapper (fromJust s) t v = evalStateT (mapMessage h) m in (v:m', s') outImports ((p, ns):t) m = if (ns==m) then outImports t m else concat ["import qualified ", ns, " as ", p, "\n", outImports t m] outImports [] _ = "" -- Write out Port-Type modules. runPortTypeMapper _ _ [] = return () runPortTypeMapper xnst u (h:t) = do let n = (u++"."++(a_portType_name h)) m = MS{ xmlNST=xnst , nstable=[] , targetNS = n , ttable=[] , hooks=[] } o = (evalStateT (mapPortType h) m) s = fromJust $ (execStateT (mapPortType h) m) case o of Nothing -> runPortTypeMapper xnst u t Just x -> do createModule n p setSection (outImports (nstable s) n) "NS_IMPORT" n p let out = concat $ intersperse "\n\n" $ map outOperation x setSection out "FUNCTIONTYPE" n p runPortTypeMapper xnst n t where outOperation (n, (Just (_, i), Nothing)) = concat ["type ", toHaskellName n, " = ", toHaskellName i, " -> IO ()"] outOperation (n, (Just (_, i), Just (_, o))) = concat ["type ", toHaskellName n, " = ", toHaskellName i, " -> IO ", toHaskellName o] outOperation (n, (Nothing, Just (_, o))) = concat ["type ", toHaskellName n, " = IO ", toHaskellName o] {- do let nst' = nst ++ [("soapenc", "urn:SOAP-ENC"), ("soapenv", "urn:SOAP-ENV")] nsm' = nsm += [("t.t.t.", "..... xdb = setFlag "message-style" (RPC (QN ...) | Document) $ addNamespaceMap nsm $ addNST nst $ newXDB x <- (request_response | one_way | solicit_response) (Transport Data-type) e.g. HTTP (\x -> head $ serialize (setFlag "message-encoding" (Encoding (QN ...) | Literal) xdb) encoder hookNamespace "Envelope" x $ emptyRoot) [(deserialize (setFlag "message-encoding" (Encoding (QN ...) | Literal) xdb) decoder)] (SOAPEnvelope [] (Right m) Nothing) case (e_Body x) of Left x -> fail "SOAPFault" Right x -> return x -} data Definitions = Definitions_I { a_def_targetNamespace :: Maybe XSD.AnyURI , a_def_name :: Maybe XSD.AnyURI , e_def_types :: XmlTrees , e_def_message :: [Message] , e_def_portType :: [PortType] , e_def_binding :: [Binding] , e_def_service :: [Service] } deriving (Data, Typeable) data Types a = Types { s_types :: [a] } deriving (Data, Typeable) data Message = Message { a_message_name :: XSD.NCName , e_message_part :: [MessagePart] } deriving (Data, Typeable, Show) data MessagePart = MessagePart { a_part_name :: XSD.NCName , a_part_element :: Maybe XSD.QName , a_part_type :: Maybe XSD.QName } deriving (Data, Typeable, Show) mapMessage :: Message -> StateT MapState Maybe HaskellType mapMessage m = do p <- mapM part (e_message_part m) return $ Record (a_message_name m) p where part p = do t <- lift $ a_part_type p -- FIXME: What do we do with element? n <- getHQN' t return $ (Elem "" (a_part_name p), (n, Single)) -- PortType data-types data PortType = PortType { a_portType_name :: XSD.NCName , e_portType_operation :: [Operation] } deriving (Data, Typeable) mapPortType :: PortType -> StateT MapState Maybe [(String, (Maybe (String, String), Maybe (String, String)))] mapPortType pt = mapM mapOperation $ e_portType_operation pt data Operation = Operation { a_operation_name :: XSD.NCName , a_operation_parameterOrder :: Maybe XSD.NMTOKENS , s_operation_cont :: OperationType } deriving (Data, Typeable) mapOperation op = do ot <- mapOperationType $ s_operation_cont op return (a_operation_name op, ot) mapOperationType (ReqResp i o) = case o of Nothing -> do i <- input return (Just i, Nothing) Just _ -> do i <- input o <- output return (Just i, Just o) where input = do n <- getHQN' $ a_param_message i return (fromMaybe "" $ a_param_name i, n) output = do n <- getHQN' $ a_param_message $ e_output_output $ fromJust o return (fromMaybe "" $ a_param_name $ e_output_output $ fromJust o, n) data OperationType = ReqResp { e_reqresp_input :: Param , s_reqresp_output :: Maybe Output } | SolResp { e_solresp_output :: Param , s_solresp_input :: Maybe Input } deriving (Data, Typeable) data Output = Output { e_output_output :: Param , e_output_fault :: [Fault] } deriving (Data, Typeable) data Input = Input { e_input_input :: Param , e_input_fault :: [Fault] } deriving (Data, Typeable) data Param = Param { a_param_name :: Maybe XSD.NCName , a_param_message :: XSD.QName } deriving (Data, Typeable) data Fault = Fault { a_fault_name :: XSD.NCName , a_fault_message :: XSD.QName } deriving (Data, Typeable) -- Binding Data-types data Binding = Binding_I { a_binding_name :: XSD.NCName , a_binding_type :: XSD.QName , e_binding_operation :: [BindingOperation] , s_binding_otherElem :: OtherElem } deriving (Data, Typeable, Show) data BindingOperation = BindingOperation_I { a_bop_name :: XSD.NCName , e_bop_input :: Maybe BindingOperationMessage , e_bop_output :: Maybe BindingOperationMessage , e_bop_fault :: [BindingOperationFault] , s_bop_otherElem :: OtherElem } deriving (Data, Typeable, Show) data BindingOperationFault = BindingOperationFault { a_bof_name :: XSD.NCName , s_bof_otherElem :: OtherElem } deriving (Data, Typeable, Show) data BindingOperationMessage = BindingOperationMessage { a_bom_name :: XSD.NCName , s_bom_otherElem :: OtherElem } deriving (Data, Typeable, Show) type BindingHook = Binding -> StateT MapState Maybe [BindingFunc] data BindingFunc = BF { funcName :: String -- The name of the function being produced , funcType :: String -- The type of function, the actual binding function will have type Dynamic -> funcType , execFunc :: String -- The prefix of the executor protocol being used, e.g. SOAP , execParam :: [String] -- The further parameters which need to be supplied to the executor , execEnc :: [String] , execDec :: [String] , execHook :: [String] } deriving Show outputBindingFunc :: BindingFunc -> String outputBindingFunc bf = let b = (concat $ [funcName bf, " a = ", execFunc bf, " nst nsm "] ++ (intersperse " " (execParam bf))) ++ " funcEncoder funcDecoder funcHook" t = concat $ [funcName bf, " :: Dynamic -> ", funcType bf] in t ++ "\n" ++ b mapBinding :: Binding -> [BindingHook] -> StateT MapState Maybe (String, [BindingFunc]) mapBinding b bh = do x <- foldr (mplus . \f -> f b) mzero bh s <- get t <- lift $ xsdToHaskellType (a_binding_type b) hierarchyPrefix put s { nstable = ("Pt", t):(nstable s) } o <- zipWithM mapBindingOperation (e_binding_operation b) x return $ (toHaskellName $ a_binding_name b, o) mapBindingOperation :: BindingOperation -> BindingFunc -> StateT MapState Maybe BindingFunc mapBindingOperation bo bf = do let fn = toLHaskellName $ a_bop_name bo; ft = toHaskellName $ a_bop_name bo return $ bf { funcName = fn, funcType = ("Pt."++ft) } data Service = Service { a_service_name :: XSD.NCName , e_service_port :: [Port] , s_service_otherElem :: OtherElem } deriving (Data, Typeable) data Port = Port { a_port_name :: XSD.NCName , a_port_binding :: XSD.QName , s_port_otherElem :: OtherElem } deriving (Data, Typeable)
twopoint718/haifa
src/Text/XML/Schema/Org/Xmlsoap/Schemas/Wsdl.hs
gpl-2.0
21,571
141
24
8,219
3,692
1,973
1,719
259
12
{-# LANGUAGE CPP #-} module Main where import System.Environment import System.Exit import System.IO import Control.Monad.Except import qualified Data.Map as M import Boot.Options import Boot.ParseArgs import Boot import Object main :: IO () main = do (opts,run) <- parseArgs putStrLn $ version opts boot opts run
antarestrader/sapphire
Main.hs
gpl-3.0
325
0
8
56
96
55
41
16
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ForeignFunctionInterface #-} module XMonad.Hooks.DynamicLog.Status.Xft where import Graphics.X11.Xft
Fizzixnerd/xmonad-config
site-haskell/src/XMonad/Hooks/DynamicLog/Status/Xft.hs
gpl-3.0
152
0
4
16
17
13
4
4
0
module TVL.Lexer where import Text.Parsec import qualified Text.Parsec.Token as Tok import Text.Parsec.Language (emptyDef) type Parser st a = Parsec String st a tvlDef :: Tok.LanguageDef st tvlDef = emptyDef { Tok.reservedNames = [ "int", "real", "enum", "bool", "struct" , "const", "true", "false" , "this", "parent", "root" , "group", "oneOf", "someOf", "allOf", "opt", "shared" , "ifin:", "ifout:", "is" , "and", "xor", "or" , "abs", "sum", "mul", "min", "max", "count", "avg" , "data", "selectedchildren", "children" ] , Tok.caseSensitive = False , Tok.identStart = letter , Tok.identLetter = alphaNum <|> oneOf "_" } lexer :: Tok.TokenParser st lexer = Tok.makeTokenParser tvlDef identifier :: Parser st String identifier = Tok.identifier lexer reserved :: String -> Parser st () reserved = Tok.reserved lexer reservedOp :: String -> Parser st () reservedOp = Tok.reservedOp lexer charLiteral :: Parser st Char charLiteral = Tok.charLiteral lexer stringLiteral :: Parser st String stringLiteral = Tok.stringLiteral lexer natural :: Parser st Integer natural = Tok.natural lexer integer :: Parser st Integer integer = Tok.integer lexer float :: Parser st Double float = Tok.float lexer symbol :: String -> Parser st String symbol = Tok.symbol lexer lexeme :: Parser st a -> Parser st a lexeme = Tok.lexeme lexer whiteSpace :: Parser st () whiteSpace = Tok.whiteSpace lexer parens :: Parser st a -> Parser st a parens = Tok.parens lexer braces :: Parser st a -> Parser st a braces = Tok.braces lexer angles :: Parser st a -> Parser st a angles = Tok.angles lexer brackets :: Parser st a -> Parser st a brackets = Tok.brackets lexer semi :: Parser st String semi = Tok.semi lexer comma :: Parser st String comma = Tok.comma lexer colon :: Parser st String colon = Tok.colon lexer dot :: Parser st String dot = Tok.dot lexer semiSep :: Parser st a -> Parser st [a] semiSep = Tok.semiSep lexer semiSep1 :: Parser st a -> Parser st [a] semiSep1 = Tok.semiSep1 lexer commaSep :: Parser st a -> Parser st [a] commaSep = Tok.commaSep lexer commaSep1 :: Parser st a -> Parser st [a] commaSep1 = Tok.commaSep1 lexer
ahmadsalim/p3-tool
p3-tool/TVL/Lexer.hs
gpl-3.0
2,330
0
8
567
792
421
371
66
1
{-| Module: NamedLambda Description: Lambda expressions with named variables License: GPL-3 This package deals with lambda expressions containing named variables instead of DeBruijn indexes. It contains parsing and printing fuctions. -} module NamedLambda ( NamedLambda (LambdaVariable, LambdaAbstraction, LambdaApplication, TypedPair, TypedPi1, TypedPi2, TypedInl, TypedInr, TypedCase, TypedUnit, TypedAbort, TypedAbsurd) , lambdaexp , toBruijn , nameExp , quicknameIndexes , variableNames ) where import Text.ParserCombinators.Parsec import Control.Applicative ((<$>), (<*>)) import qualified Data.Map.Strict as Map import Lambda import MultiBimap import Data.Maybe import Control.Monad type Context = MultiBimap Exp String -- Parsing of Lambda Expressions. -- The user can input a lambda expression with named variables, of -- the form of "\x.x" or "(\a.(\b.a b))". The interpreter will parse -- it into an internal representation. -- | A lambda expression with named variables. data NamedLambda = LambdaVariable String -- ^ variable | LambdaAbstraction String NamedLambda -- ^ lambda abstraction | LambdaApplication NamedLambda NamedLambda -- ^ function application | TypedPair NamedLambda NamedLambda -- ^ pair of expressions | TypedPi1 NamedLambda -- ^ first projection | TypedPi2 NamedLambda -- ^ second projection | TypedInl NamedLambda -- ^ left injection | TypedInr NamedLambda -- ^ right injection | TypedCase NamedLambda NamedLambda NamedLambda -- ^ case of expressions | TypedUnit -- ^ unit | TypedAbort NamedLambda -- ^ abort | TypedAbsurd NamedLambda -- ^ absurd deriving (Eq) -- | Parses a lambda expression with named variables. -- A lambda expression is a sequence of one or more autonomous -- lambda expressions. They are parsed assuming left-associativity. -- -- >>> parse lambdaexp "" "\\f.\\x.f x" -- Right λf.λx.(f x) -- -- Note that double backslashes are neccessary only when we quote strings; -- it will work only with a simple backslash in the interpreter. lambdaexp :: Parser NamedLambda lambdaexp = foldl1 LambdaApplication <$> (spaces >> sepBy1 simpleexp spaces) -- | Parses a simple lambda expression, without function applications -- at the top level. It can be a lambda abstraction, a variable or another -- potentially complex lambda expression enclosed in parentheses. simpleexp :: Parser NamedLambda simpleexp = choice [ try pairParser , try pi1Parser , try pi2Parser , try inlParser , try inrParser , try caseParser , try unitParser , try abortParser , try absurdParser , try lambdaAbstractionParser , try variableParser , try (parens lambdaexp) ] -- | The returned parser parenthesizes the given parser parens :: Parser a -> Parser a parens = between (char '(') (char ')') -- | Parses a variable. Any name can form a lambda variable. variableParser :: Parser NamedLambda variableParser = LambdaVariable <$> nameParser -- | Allowed variable names nameParser :: Parser String nameParser = many1 alphaNum choicest :: [String] -> Parser String choicest sl = choice (try . string <$> sl) -- | Parses a lambda abstraction. The '\' is used as lambda. lambdaAbstractionParser :: Parser NamedLambda lambdaAbstractionParser = LambdaAbstraction <$> (lambdaChar >> nameParser) <*> (char '.' >> lambdaexp) -- | Char used to represent lambda in user's input. lambdaChar :: Parser Char lambdaChar = choice [try $ char '\\', try $ char 'λ'] pairParser :: Parser NamedLambda pairParser = parens (TypedPair <$> lambdaexp <*> (char ',' >> lambdaexp)) pi1Parser, pi2Parser :: Parser NamedLambda pi1Parser = TypedPi1 <$> (choicest namesPi1 >> lambdaexp) pi2Parser = TypedPi2 <$> (choicest namesPi2 >> lambdaexp) inlParser, inrParser :: Parser NamedLambda inlParser = TypedInl <$> (choicest namesInl >> lambdaexp) inrParser = TypedInr <$> (choicest namesInr >> lambdaexp) caseParser :: Parser NamedLambda caseParser = TypedCase <$> (choicest namesCase >> simpleexp) <*> (choicest namesOf >> simpleexp) <*> (choicest namesCaseSep >> simpleexp) unitParser :: Parser NamedLambda unitParser = choicest namesUnit >> return TypedUnit abortParser :: Parser NamedLambda abortParser = TypedAbort <$> (choicest namesAbort >> lambdaexp) absurdParser :: Parser NamedLambda absurdParser = TypedAbsurd <$> (choicest namesAbsurd >> lambdaexp) -- | Shows a lambda expression with named variables. -- Parentheses are ignored; they are written only around applications. showNamedLambda :: NamedLambda -> String showNamedLambda (LambdaVariable c) = c showNamedLambda (LambdaAbstraction c e) = "λ" ++ c ++ "." ++ showNamedLambda e showNamedLambda (LambdaApplication f g) = showNamedLambdaPar f ++ " " ++ showNamedLambdaPar g showNamedLambda (TypedPair a b) = "(" ++ showNamedLambda a ++ "," ++ showNamedLambda b ++ ")" showNamedLambda (TypedPi1 a) = head namesPi1 ++ showNamedLambdaPar a showNamedLambda (TypedPi2 a) = head namesPi2 ++ showNamedLambdaPar a showNamedLambda (TypedInl a) = head namesInl ++ showNamedLambdaPar a showNamedLambda (TypedInr a) = head namesInr ++ showNamedLambdaPar a showNamedLambda (TypedCase a b c) = last namesCase ++ showNamedLambda a ++ last namesOf ++ showNamedLambda b ++ head namesCaseSep ++ showNamedLambda c showNamedLambda TypedUnit = head namesUnit showNamedLambda (TypedAbort a) = head namesAbort ++ showNamedLambdaPar a showNamedLambda (TypedAbsurd a) = head namesAbsurd ++ showNamedLambdaPar a showNamedLambdaPar :: NamedLambda -> String showNamedLambdaPar l@(LambdaVariable _) = showNamedLambda l showNamedLambdaPar l@TypedUnit = showNamedLambda l showNamedLambdaPar l@(TypedPair _ _) = showNamedLambda l showNamedLambdaPar l = "(" ++ showNamedLambda l ++ ")" instance Show NamedLambda where show = showNamedLambda -- Name type constructors namesPi1 :: [String] namesPi1 = ["π₁ ", "FST "] namesPi2 :: [String] namesPi2 = ["π₂ ", "SND "] namesInl :: [String] namesInl = ["ιnl ", "INL "] namesInr :: [String] namesInr = ["ιnr ", "INR "] namesCase :: [String] namesCase = ["CASE ", "Case ", "ᴄᴀꜱᴇ "] namesOf :: [String] namesOf = [" OF ", " Of ", " ᴏꜰ "] namesCaseSep :: [String] namesCaseSep = ["; ", ";"] namesUnit :: [String] namesUnit = ["★", "UNIT"] namesAbort :: [String] namesAbort = ["□ ", "ABORT "] namesAbsurd :: [String] namesAbsurd = ["■ ", "ABSURD "] -- | Translates a named variable expression into a DeBruijn one. -- Uses a dictionary of already binded numbers and variables. tobruijn :: Map.Map String Integer -- ^ dictionary of the names of the variables used -> Context -- ^ dictionary of the names already binded on the scope -> NamedLambda -- ^ initial expression -> Exp -- Every lambda abstraction is inserted in the variable dictionary, -- and every number in the dictionary increases to reflect we are entering -- into a deeper context. tobruijn d context (LambdaAbstraction c e) = Lambda $ tobruijn newdict context e where newdict = Map.insert c 1 (Map.map succ d) -- Translation of applications is trivial. tobruijn d context (LambdaApplication f g) = App (tobruijn d context f) (tobruijn d context g) -- Every variable is checked on the variable dictionary and in the current scope. tobruijn d context (LambdaVariable c) = case Map.lookup c d of Just n -> Var n Nothing -> fromMaybe (Var 0) (MultiBimap.lookupR c context) tobruijn d context (TypedPair a b) = Pair (tobruijn d context a) (tobruijn d context b) tobruijn d context (TypedPi1 a) = Pi1 (tobruijn d context a) tobruijn d context (TypedPi2 a) = Pi2 (tobruijn d context a) tobruijn d context (TypedInl a) = Inl (tobruijn d context a) tobruijn d context (TypedInr a) = Inr (tobruijn d context a) tobruijn d context (TypedCase a b c) = Caseof (tobruijn d context a) (tobruijn d context b) (tobruijn d context c) tobruijn _ _ TypedUnit = Unit tobruijn d context (TypedAbort a) = Abort (tobruijn d context a) tobruijn d context (TypedAbsurd a) = Absurd (tobruijn d context a) -- | Transforms a lambda expression with named variables to a deBruijn index expression. -- Uses only the dictionary of the variables in the current context. toBruijn :: Context -- ^ Variable context -> NamedLambda -- ^ Initial lambda expression with named variables -> Exp toBruijn = tobruijn Map.empty -- | Translates a deBruijn expression into a lambda expression -- with named variables, given a list of used and unused variable names. nameIndexes :: [String] -> [String] -> Exp -> NamedLambda nameIndexes _ _ (Var 0) = LambdaVariable "undefined" nameIndexes used _ (Var n) = LambdaVariable (used !! pred (fromInteger n)) nameIndexes used new (Lambda e) = LambdaAbstraction (head new) (nameIndexes (head new:used) (tail new) e) nameIndexes used new (App f g) = LambdaApplication (nameIndexes used new f) (nameIndexes used new g) nameIndexes used new (Pair a b) = TypedPair (nameIndexes used new a) (nameIndexes used new b) nameIndexes used new (Pi1 a) = TypedPi1 (nameIndexes used new a) nameIndexes used new (Pi2 a) = TypedPi2 (nameIndexes used new a) nameIndexes used new (Inl a) = TypedInl (nameIndexes used new a) nameIndexes used new (Inr a) = TypedInr (nameIndexes used new a) nameIndexes used new (Caseof a b c) = TypedCase (nameIndexes used new a) (nameIndexes used new b) (nameIndexes used new c) nameIndexes _ _ Unit = TypedUnit nameIndexes used new (Abort a) = TypedAbort (nameIndexes used new a) nameIndexes used new (Absurd a) = TypedAbsurd (nameIndexes used new a) quicknameIndexes :: Int -> [String] -> Exp -> NamedLambda quicknameIndexes _ _ (Var 0) = LambdaVariable "undefined" quicknameIndexes n vars (Var m) = LambdaVariable (vars !! (n - fromInteger m)) quicknameIndexes n vars (Lambda e) = LambdaAbstraction (vars !! n) (quicknameIndexes (succ n) vars e) quicknameIndexes n vars (App f g) = LambdaApplication (quicknameIndexes n vars f) (quicknameIndexes n vars g) quicknameIndexes n vars (Pair a b) = TypedPair (quicknameIndexes n vars a) (quicknameIndexes n vars b) quicknameIndexes n vars (Pi1 a) = TypedPi1 (quicknameIndexes n vars a) quicknameIndexes n vars (Pi2 a) = TypedPi2 (quicknameIndexes n vars a) quicknameIndexes n vars (Inl a) = TypedInl (quicknameIndexes n vars a) quicknameIndexes n vars (Inr a) = TypedInr (quicknameIndexes n vars a) quicknameIndexes n vars (Caseof a b c) = TypedCase (quicknameIndexes n vars a) (quicknameIndexes n vars b) (quicknameIndexes n vars c) quicknameIndexes _ _ Unit = TypedUnit quicknameIndexes n vars (Abort a) = TypedAbort (quicknameIndexes n vars a) quicknameIndexes n vars (Absurd a) = TypedAbsurd (quicknameIndexes n vars a) -- | Gives names to every variable in a deBruijn expression using -- alphabetic order. nameExp :: Exp -> NamedLambda nameExp = nameIndexes [] variableNames -- | A list of all possible variable names in lexicographical order. variableNames :: [String] variableNames = concatMap (`replicateM` ['a'..'z']) [1..]
M42/mikrokosmos
source/NamedLambda.hs
gpl-3.0
11,675
0
11
2,577
2,970
1,557
1,413
183
2
module Sandpiles where import Constants import CoordinateSystem
Lexer747/Haskell-Fractals
Core/Sandpiles.hs
gpl-3.0
67
0
3
10
10
7
3
3
0
module Math.Topology.KnotTh.ChordDiagram.Test ( test ) where import Control.Monad (forM_) import Text.Printf import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.HUnit hiding (Test, test) import Math.Topology.KnotTh.ChordDiagram import Math.Topology.KnotTh.ChordDiagram.Lyndon import Math.Topology.KnotTh.Algebra.Dihedral naiveMinShift :: (Ord a) => [a] -> [a] naiveMinShift [] = [] naiveMinShift l = minimum [ let (a, b) = splitAt i l in b ++ a | i <- [0 .. length l]] minShiftIsOk :: [Int] -> Bool minShiftIsOk list = snd (minimumCyclicShift list) == naiveMinShift list test :: Test test = let testGenerator gen list = forM_ list $ \ (n, expected) -> let total = countChordDiagrams (gen n) :: Int in assertEqual (printf "for n = %i" n) expected total in testGroup "Chord Diagrams" [ testCase "Numbers of non-planar chord diagrams" $ testGenerator generateNonPlanarRaw [ (0, 1), (1, 0), (2, 1), (3, 2), (4, 7), (5, 29), (6, 196), (7, 1788), (8, 21994) ] , testCase "Numbers of bicolourable non-planar chord diagrams" $ testGenerator generateBicolourableNonPlanarRaw [ (0, 1), (1, 0), (2, 0), (3, 1), (4, 1), (5, 4), (6, 9), (7, 43), (8, 198), (9, 1435) ] , testCase "Numbers of quasi-tree chord diagrams" $ testGenerator generateQuasiTreesRaw [ (0, 1), (1, 0), (2, 1), (3, 1), (4, 4), (5, 18), (6, 116), (7, 1060), (8, 13019) ] , testCase "Symmetry group information" $ forM_ [1 .. 9] $ \ !n -> forM_ (listChordDiagrams $ generateNonPlanarRaw n) $ \ (cd, (mirror, period)) -> do assertEqual (printf "%s period" (show cd)) (naivePeriodOf cd) period let expectedMirror = mirrorIt cd `elem` map (`rotateBy` cd) [0 .. rotationOrder cd - 1] assertEqual (printf "%s mirror" (show cd)) expectedMirror mirror , testGroup "String combinatorial functions tests" [ testProperty "Minimal cyclic shift" minShiftIsOk , let list = [6, 4, 3, 4, 5, 3, 3, 1] :: [Int] in testCase (printf "Test minimal cyclic shift of %s" $ show list) $ snd (minimumCyclicShift list) @?= naiveMinShift list ] ]
mishun/tangles
test/Math/Topology/KnotTh/ChordDiagram/Test.hs
lgpl-3.0
2,451
0
22
685
872
501
371
43
1