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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# 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.Reseller.Subscriptions.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets a subscription of the customer.
--
-- /See:/ <https://developers.google.com/google-apps/reseller/ Enterprise Apps Reseller API Reference> for @reseller.subscriptions.get@.
module Network.Google.Resource.Reseller.Subscriptions.Get
(
-- * REST Resource
SubscriptionsGetResource
-- * Creating a Request
, subscriptionsGet
, SubscriptionsGet
-- * Request Lenses
, sgCustomerId
, sgSubscriptionId
) where
import Network.Google.AppsReseller.Types
import Network.Google.Prelude
-- | A resource alias for @reseller.subscriptions.get@ method which the
-- 'SubscriptionsGet' request conforms to.
type SubscriptionsGetResource =
"apps" :>
"reseller" :>
"v1" :>
"customers" :>
Capture "customerId" Text :>
"subscriptions" :>
Capture "subscriptionId" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Subscription
-- | Gets a subscription of the customer.
--
-- /See:/ 'subscriptionsGet' smart constructor.
data SubscriptionsGet = SubscriptionsGet'
{ _sgCustomerId :: !Text
, _sgSubscriptionId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'SubscriptionsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sgCustomerId'
--
-- * 'sgSubscriptionId'
subscriptionsGet
:: Text -- ^ 'sgCustomerId'
-> Text -- ^ 'sgSubscriptionId'
-> SubscriptionsGet
subscriptionsGet pSgCustomerId_ pSgSubscriptionId_ =
SubscriptionsGet'
{ _sgCustomerId = pSgCustomerId_
, _sgSubscriptionId = pSgSubscriptionId_
}
-- | Id of the Customer
sgCustomerId :: Lens' SubscriptionsGet Text
sgCustomerId
= lens _sgCustomerId (\ s a -> s{_sgCustomerId = a})
-- | Id of the subscription, which is unique for a customer
sgSubscriptionId :: Lens' SubscriptionsGet Text
sgSubscriptionId
= lens _sgSubscriptionId
(\ s a -> s{_sgSubscriptionId = a})
instance GoogleRequest SubscriptionsGet where
type Rs SubscriptionsGet = Subscription
type Scopes SubscriptionsGet =
'["https://www.googleapis.com/auth/apps.order",
"https://www.googleapis.com/auth/apps.order.readonly"]
requestClient SubscriptionsGet'{..}
= go _sgCustomerId _sgSubscriptionId (Just AltJSON)
appsResellerService
where go
= buildClient
(Proxy :: Proxy SubscriptionsGetResource)
mempty
| rueshyna/gogol | gogol-apps-reseller/gen/Network/Google/Resource/Reseller/Subscriptions/Get.hs | mpl-2.0 | 3,362 | 0 | 15 | 779 | 388 | 233 | 155 | 65 | 1 |
module GCrypt.MPI.Data (
MPI,
) where
import GCrypt.Base
| sw17ch/hsgcrypt | src/GCrypt/MPI/Data.hs | lgpl-3.0 | 63 | 0 | 4 | 14 | 18 | 12 | 6 | 3 | 0 |
-- Hoff -- A gatekeeper for your commits
-- Copyright 2016 Ruud van Asseldonk
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- A copy of the License has been included in the root of the repository.
{-# LANGUAGE OverloadedStrings #-}
module Server (buildServer) where
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TSem (newTSem, signalTSem, waitTSem)
import Control.Monad.IO.Class (liftIO)
import Crypto.Hash (digestFromByteString)
import Crypto.Hash.Algorithms (SHA1)
import Crypto.MAC.HMAC (HMAC (..), hmac)
import Data.ByteString (ByteString)
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import Network.HTTP.Types (badRequest400, notFound404, notImplemented501, serviceUnavailable503)
import Web.Scotty (ActionM, ScottyM, body, get, header, jsonData, notFound, param, post, raw, scottyApp, setHeader, status, text)
import qualified Data.ByteString.Base16 as Base16
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Text as Text
import qualified Data.Text.Lazy as LT
import qualified Network.Wai as Wai
import qualified Network.Wai.Handler.Warp as Warp
import qualified Network.Wai.Handler.WarpTLS as Warp
import Configuration (TlsConfiguration)
import Project (ProjectInfo (ProjectInfo), ProjectState)
import qualified Configuration as Config
import qualified Github
import qualified WebInterface
-- Router for the web server.
router
:: [ProjectInfo]
-> Text
-> (Github.WebhookEvent -> ActionM ())
-> (ProjectInfo -> Maybe (IO ProjectState))
-> ScottyM ()
router infos ghSecret serveEnqueueEvent getProjectState = do
get "/" $ serveIndex infos
post "/hook/github" $ withSignatureCheck ghSecret $ serveGithubWebhook serveEnqueueEvent
get "/hook/github" $ serveWebhookDocs
get "/:owner/:repo" $ serveWebInterface infos getProjectState
notFound $ serveNotFound
-- Checks the signature (encoded as hexadecimal characters in 'hexDigest') of
-- the message, given the secret, and the actual message bytes.
isSignatureValid :: Text -> Text -> ByteString -> Bool
isSignatureValid secret hexDigest message =
let actualHmac = hmac (encodeUtf8 secret) message :: HMAC SHA1
binaryDigest = fst $ Base16.decode $ encodeUtf8 hexDigest
in case digestFromByteString binaryDigest of
-- The HMAC type implements a constant-time comparison.
Just expectedDigest -> (HMAC expectedDigest) == actualHmac
-- If the hexDigest was not a valid hexadecimally-encoded digest,
-- the signature was definitely not valid.
Nothing -> False
-- The X-Hub-Signature header value is prefixed with "sha1=", and then the
-- digest in hexadecimal. Strip off that prefix, and ensure that it has the
-- expected value.
extractHexDigest :: Text -> Maybe Text
extractHexDigest value =
let (prefix, hexDigest) = Text.splitAt 5 value
in case prefix of
"sha1=" -> Just hexDigest
_ -> Nothing
withSignatureCheck :: Text -> ActionM () -> ActionM ()
withSignatureCheck secret bodyAction = do
maybeHubSignature <- header "X-Hub-Signature"
let maybeHexDigest = fmap LT.toStrict maybeHubSignature >>= extractHexDigest
-- Compute the HMAC as from the body, encode as hexadecimal characters in a
-- bytestring. Scotty reads headers as Text, so convert the header to a byte
-- string as well.
case maybeHexDigest of
Nothing -> do
status badRequest400
text "missing or malformed X-Hub-Signature header"
Just hexDigest -> do
bodyBytes <- body
if isSignatureValid secret hexDigest (LBS.toStrict bodyBytes)
then bodyAction
else do
status badRequest400
text "signature does not match, is the secret set up properly?"
serveGithubWebhook :: (Github.WebhookEvent -> ActionM ()) -> ActionM ()
serveGithubWebhook serveEnqueueEvent = do
eventName <- header "X-GitHub-Event"
case eventName of
Just "pull_request" -> do
payload <- jsonData :: ActionM Github.PullRequestPayload
serveEnqueueEvent $ Github.PullRequest payload
Just "issue_comment" -> do
payload <- jsonData :: ActionM Github.CommentPayload
serveEnqueueEvent $ Github.Comment payload
Just "status" -> do
payload <- jsonData :: ActionM Github.CommitStatusPayload
serveEnqueueEvent $ Github.CommitStatus payload
Just "ping" ->
serveEnqueueEvent $ Github.Ping
_ -> do
status notImplemented501
text "hook ignored, the event type is not supported"
-- Handles replying to the client when a GitHub webhook is received.
serveTryEnqueueEvent :: (Github.WebhookEvent -> IO Bool)
-> Github.WebhookEvent
-> ActionM ()
serveTryEnqueueEvent tryEnqueueEvent event = do
-- Enqueue the event if the queue is not full. Don't block if the queue is
-- full: instead we don't want to enqueue the event and tell the client to
-- retry in a while.
enqueued <- liftIO $ tryEnqueueEvent event
if enqueued
then text "hook received"
else do
status serviceUnavailable503
text "webhook event queue full, please try again in a few minutes"
serveWebhookDocs :: ActionM ()
serveWebhookDocs = do
status badRequest400
text "expecting POST request at /hook/github"
serveIndex :: [ProjectInfo] -> ActionM ()
serveIndex infos = do
setHeader "Content-Type" "text/html; charset=utf-8"
let title = "Hoff"
raw $ WebInterface.renderPage title $ WebInterface.viewIndex infos
serveWebInterface :: [ProjectInfo]
-> (ProjectInfo -> Maybe (IO ProjectState))
-> ActionM ()
serveWebInterface infos getProjectState = do
owner <- param "owner"
repo <- param "repo"
let
info = ProjectInfo owner repo
Just getState = getProjectState info
if not (info `elem` infos)
then do
status notFound404
text "not found"
else do
state <- liftIO $ getState
setHeader "Content-Type" "text/html; charset=utf-8"
let title = Text.concat [owner, "/", repo]
raw $ WebInterface.renderPage title $ WebInterface.viewProject info state
serveNotFound :: ActionM ()
serveNotFound = do
status notFound404
text "not found"
warpSettings :: Int -> IO () -> Warp.Settings
warpSettings port beforeMainLoop
= Warp.setPort port
$ Warp.setBeforeMainLoop beforeMainLoop
$ Warp.defaultSettings
warpTlsSettings :: TlsConfiguration -> Warp.TLSSettings
warpTlsSettings config =
Warp.tlsSettings (Config.certFile config) (Config.keyFile config)
-- Runs the a server with TLS if a TLS config was provided, or a normal http
-- server otherwise. Behaves identical to Warp.runSettings after passing the
-- TLS configuration.
runServerMaybeTls :: Maybe TlsConfiguration
-> Warp.Settings
-> Wai.Application
-> IO ()
runServerMaybeTls maybeTlsConfig =
case maybeTlsConfig of
Just tlsConfig -> Warp.runTLS $ warpTlsSettings tlsConfig
Nothing -> Warp.runSettings
-- Runs a webserver at the specified port. When GitHub webhooks are received,
-- an event will be added to the event queue. Returns a pair of two IO
-- operations: (runServer, blockUntilReady). The first should be used to run
-- the server, the second may be used to wait until the server is ready to
-- serve requests.
buildServer :: Int
-> Maybe TlsConfiguration
-> [ProjectInfo]
-> Text
-> (Github.WebhookEvent -> IO Bool)
-> (ProjectInfo -> Maybe (IO ProjectState))
-> IO (IO (), IO ())
buildServer port tlsConfig infos ghSecret tryEnqueueEvent getProjectState = do
-- Create a semaphore that will be signalled when the server is ready.
readySem <- atomically $ newTSem 0
let signalReady = atomically $ signalTSem readySem
blockUntilReady = atomically $ waitTSem readySem
let
-- Make Warp signal the semaphore when it is ready to serve requests.
settings = warpSettings port signalReady
serveEnqueueEvent :: Github.WebhookEvent -> ActionM ()
serveEnqueueEvent = serveTryEnqueueEvent tryEnqueueEvent
-- Build the Scotty app, but do not start serving yet, as that would never
-- return, so we wouldn't have the opportunity to return the 'blockUntilReady'
-- function to the caller.
app <- scottyApp $ router infos ghSecret serveEnqueueEvent getProjectState
let runServer = runServerMaybeTls tlsConfig settings app
-- Return two IO actions: one that will run the server (and never return),
-- and one that blocks until 'readySem' is signalled from the server.
return (runServer, blockUntilReady)
| ruuda/hoff | src/Server.hs | apache-2.0 | 8,686 | 0 | 16 | 1,779 | 1,751 | 898 | 853 | 158 | 5 |
module Lycopene.Core.Resource
( Resource(..)
, runResource
, file
, connection
) where
import System.IO
import Database.HDBC (IConnection, disconnect)
import Control.Monad.Trans
import Control.Exception (bracket, onException)
-- | Generic Resource
-- http://www.haskellforall.com/2013/06/the-resource-applicative.html
newtype Resource a = Resource { acquire :: IO (a, IO ()) }
runResource :: Resource a -> (a -> IO b) -> IO b
runResource resource k = bracket (acquire resource)
snd
(\(a, _) -> k a)
instance Functor Resource where
fmap f resource = Resource $ do
(a, release) <- acquire resource
return (f a, release)
instance Applicative Resource where
pure a = Resource (pure (a, pure ()))
resource1 <*> resource2 = Resource $ do
(f, release1) <- acquire resource1
(x, release2) <- acquire resource2 `onException` release1
return (f x, release2 >> release1)
instance Monad Resource where
return a = Resource (return (a, return ()))
m >>= f = Resource $ do
(m', release1) <- acquire m
(x , release2) <- acquire (f m') `onException` release1
return (x, release2 >> release1)
instance MonadIO Resource where
liftIO m = Resource $ m >>= (\x -> return (x, return ()))
file :: IOMode -> FilePath -> Resource Handle
file mode path = Resource $ do
handle <- openFile path mode
return (handle, hClose handle)
connection :: (IConnection conn) => IO conn -> Resource conn
connection c = Resource $ c >>= (\x -> return (x, disconnect x))
| utky/lycopene | src/Lycopene/Core/Resource.hs | apache-2.0 | 1,660 | 0 | 13 | 459 | 596 | 312 | 284 | 38 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Main(main) where
import DNA.Channel.File (readDataMMap)
import DNA
import DDP
import DDP_Slice_CUDA
----------------------------------------------------------------
-- Distributed dot product
--
-- Note that actors which do not spawn actors on other nodes do not
-- receive CAD.
----------------------------------------------------------------
ddpCollector :: CollectActor Double Double
ddpCollector = collectActor
(\s a -> return $! s + a)
(return 0)
(return)
remotable [ 'ddpCollector
]
-- | Actor for calculating dot product
ddpDotProduct :: Actor Slice Double
ddpDotProduct = actor $ \size -> do
res <- selectMany (Frac 1) (NNodes 1) [UseLocal]
r <- select Local (N 0)
shell <- startGroup res Failout $(mkStaticClosure 'ddpProductSlice)
shCol <- startCollector r $(mkStaticClosure 'ddpCollector)
sendParam size $ broadcast shell
connect shell shCol
res <- delay Remote shCol
await res
main :: IO ()
main = dnaRun rtable $ do
let n = 10*1000*1000
expected = fromIntegral n*(fromIntegral n-1)/2 * 0.1
-- Show configuration
nodes <- groupSize
let size = n * 8; sizePerNode = size `div` fromIntegral nodes
liftIO $ putStrLn $ concat
[ "Data: ", show (size `div` 1000000), " MB total, "
, show (sizePerNode `div` 1000000), " MB per node"]
b <- eval ddpDotProduct (Slice 0 n)
liftIO $ putStrLn $ concat
[ "RESULT: ", show b
, " EXPECTED: ", show expected
, if b == expected then " -- ok" else " -- WRONG!"
]
where
rtable = DDP.__remoteTable
. DDP_Slice_CUDA.__remoteTable
. Main.__remoteTable
| SKA-ScienceDataProcessor/RC | MS2/dna-programs/ddp-in-memory-cuda.hs | apache-2.0 | 1,706 | 0 | 16 | 408 | 494 | 255 | 239 | 39 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-deprecations #-}
#include "version-compatibility-macros.h"
-- | This module shows how to write a custom prettyprinter backend, based on
-- directly converting a 'SimpleDocStream' to an output format using a stack
-- machine. For a tree serialization approach, which may be more suitable for
-- certain output formats, see
-- "Prettyprinter.Render.Tutorials.TreeRenderingTutorial".
--
-- Rendering to ANSI terminal with colors is an important use case for stack
-- machine based rendering.
--
-- The module is written to be readable top-to-bottom in both Haddock and raw
-- source form.
module Prettyprinter.Render.Tutorials.StackMachineTutorial
{-# DEPRECATED "Writing your own stack machine is probably more efficient and customizable; also consider using »renderSimplyDecorated(A)« instead" #-}
where
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TLB
import Prettyprinter
import Prettyprinter.Internal
import Prettyprinter.Render.Util.Panic
import Prettyprinter.Render.Util.StackMachine
#if !(APPLICATIVE_MONAD)
import Control.Applicative
#endif
-- * The type of available markup
--
-- $standalone-text
--
-- First, we define a set of valid annotations must be defined, with the goal of
-- defining a @'Doc' 'SimpleHtml'@. We will later define how to convert this to
-- the output format ('TL.Text').
data SimpleHtml = Bold | Italics | Color Color | Paragraph | Headline
data Color = Red | Green | Blue
-- ** Convenience definitions
bold, italics, paragraph, headline :: Doc SimpleHtml -> Doc SimpleHtml
bold = annotate Bold
italics = annotate Italics
paragraph = annotate Paragraph
headline = annotate Headline
color :: Color -> Doc SimpleHtml -> Doc SimpleHtml
color c = annotate (Color c)
-- * The rendering algorithm
--
-- $standalone-text
--
-- With the annotation definitions out of the way, we can now define a
-- conversion function from 'SimpleDocStream' annotated with our 'SimpleHtml' to the
-- final 'TL.Text' representation.
--
-- There are two ways to render this; the simpler one is just using
-- 'renderSimplyDecorated'. However, some output formats require more
-- complicated functionality, so we explore this explicitly with a simple
-- example below. An example for something more complicated is ANSI terminal
-- rendering, where on popping we need to regenerate the previous style,
-- requiring a pop (discard current style) followed by a peek (regenerate
-- previous style).
-- | The 'StackMachine' type defines a stack machine suitable for many rendering
-- needs. It has two auxiliary parameters: the type of the end result, and the
-- type of the document’s annotations.
--
-- Most 'StackMachine' creations will look like this definition: a recursive
-- walk through the 'SimpleDocStream', pushing styles on the stack and popping
-- them off again, and writing raw output.
--
-- The equivalent to this in the tree based rendering approach is
-- 'Prettyprinter.Render.Tutorials.TreeRenderingTutorial.renderTree'.
renderStackMachine :: SimpleDocStream SimpleHtml -> StackMachine TLB.Builder SimpleHtml ()
renderStackMachine = \sds -> case sds of
SFail -> panicUncaughtFail
SEmpty -> pure ()
SChar c x -> do
writeOutput (TLB.singleton c)
renderStackMachine x
SText _l t x -> do
writeOutput (TLB.fromText t)
renderStackMachine x
SLine i x -> do
writeOutput (TLB.singleton '\n')
writeOutput (TLB.fromText (textSpaces i))
renderStackMachine x
SAnnPush s x -> do
pushStyle s
writeOutput (fst (htmlTag s))
renderStackMachine x
SAnnPop x -> do
s <- unsafePopStyle
writeOutput (snd (htmlTag s))
renderStackMachine x
-- | Convert a 'SimpleHtml' annotation to a pair of opening and closing tags.
-- This is where the translation of style to raw output happens.
htmlTag :: SimpleHtml -> (TLB.Builder, TLB.Builder)
htmlTag = \sh -> case sh of
Bold -> ("<strong>", "</strong>")
Italics -> ("<em>", "</em>")
Color c -> ("<span style=\"color: " <> hexCode c <> "\">", "</span>")
Paragraph -> ("<p>", "</p>")
Headline -> ("<h1>", "</h1>")
where
hexCode :: Color -> TLB.Builder
hexCode = \c -> case c of
Red -> "#f00"
Green -> "#0f0"
Blue -> "#00f"
-- | We can now wrap our stack machine definition from 'renderStackMachine' in a
-- nicer interface; on successful conversion, we run the builder to give us the
-- final 'TL.Text', and before we do that we check that the style stack is empty
-- (i.e. there are no unmatched style applications) after the machine is run.
--
-- This function does only a bit of plumbing around 'renderStackMachine', and is
-- the main API function of a stack machine renderer. The tree renderer
-- equivalent to this is
-- 'Prettyprinter.Render.Tutorials.TreeRenderingTutorial.render'.
render :: SimpleDocStream SimpleHtml -> TL.Text
render doc
= let (resultBuilder, remainingStyles) = execStackMachine [] (renderStackMachine doc)
in if null remainingStyles
then TLB.toLazyText resultBuilder
else error ("There are "
<> show (length remainingStyles)
<> " unpaired styles! Please report this as a bug.")
-- * Example invocation
--
-- $standalone-text
--
-- We can now render an example document using our definitions:
--
-- >>> :set -XOverloadedStrings
-- >>> import qualified Data.Text.Lazy.IO as TL
-- >>> :{
-- >>> let go = TL.putStrLn . render . layoutPretty defaultLayoutOptions
-- >>> in go (vsep
-- >>> [ headline "Example document"
-- >>> , paragraph ("This is a" <+> color Red "paragraph" <> comma)
-- >>> , paragraph ("and" <+> bold "this text is bold.")
-- >>> ])
-- >>> :}
-- <h1>Example document</h1>
-- <p>This is a <span style="color: #f00">paragraph</span>,</p>
-- <p>and <strong>this text is bold.</strong></p>
| quchen/prettyprinter | prettyprinter/src/Prettyprinter/Render/Tutorials/StackMachineTutorial.hs | bsd-2-clause | 6,009 | 0 | 15 | 1,178 | 752 | 426 | 326 | 63 | 7 |
-- |
-- Module : Text.Megaparsec.Byte.Lexer
-- Copyright : © 2015–2017 Megaparsec contributors
-- License : FreeBSD
--
-- Maintainer : Mark Karpov <[email protected]>
-- Stability : experimental
-- Portability : portable
--
-- Stripped-down version of "Text.Megaparsec.Char.Lexer" for streams of
-- bytes.
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
module Text.Megaparsec.Byte.Lexer
( -- * White space
C.space
, C.lexeme
, C.symbol
, C.symbol'
, skipLineComment
, skipBlockComment
, skipBlockCommentNested
-- * Numbers
, decimal
, octal
, hexadecimal
, scientific
, float
, signed )
where
import Control.Applicative
import Data.Functor (void)
import Data.List (foldl')
import Data.Proxy
import Data.Scientific (Scientific)
import Data.Word (Word8)
import Text.Megaparsec
import Text.Megaparsec.Byte
import qualified Data.Scientific as Sci
import qualified Text.Megaparsec.Char.Lexer as C
----------------------------------------------------------------------------
-- White space
-- | Given comment prefix this function returns a parser that skips line
-- comments. Note that it stops just before the newline character but
-- doesn't consume the newline. Newline is either supposed to be consumed by
-- 'space' parser or picked up manually.
skipLineComment :: (MonadParsec e s m, Token s ~ Word8)
=> Tokens s -- ^ Line comment prefix
-> m ()
skipLineComment prefix =
string prefix *> void (takeWhileP (Just "character") (/= 10))
{-# INLINEABLE skipLineComment #-}
-- | @'skipBlockComment' start end@ skips non-nested block comment starting
-- with @start@ and ending with @end@.
skipBlockComment :: (MonadParsec e s m, Token s ~ Word8)
=> Tokens s -- ^ Start of block comment
-> Tokens s -- ^ End of block comment
-> m ()
skipBlockComment start end = p >> void (manyTill anyChar n)
where
p = string start
n = string end
{-# INLINEABLE skipBlockComment #-}
-- | @'skipBlockCommentNested' start end@ skips possibly nested block
-- comment starting with @start@ and ending with @end@.
--
-- @since 5.0.0
skipBlockCommentNested :: (MonadParsec e s m, Token s ~ Word8)
=> Tokens s -- ^ Start of block comment
-> Tokens s -- ^ End of block comment
-> m ()
skipBlockCommentNested start end = p >> void (manyTill e n)
where
e = skipBlockCommentNested start end <|> void anyChar
p = string start
n = string end
{-# INLINEABLE skipBlockCommentNested #-}
----------------------------------------------------------------------------
-- Numbers
-- | Parse an integer in decimal representation according to the format of
-- integer literals described in the Haskell report.
--
-- If you need to parse signed integers, see 'signed' combinator.
decimal
:: forall e s m a. (MonadParsec e s m, Token s ~ Word8, Integral a)
=> m a
decimal = decimal_ <?> "integer"
{-# INLINEABLE decimal #-}
-- | A non-public helper to parse decimal integers.
decimal_
:: forall e s m a. (MonadParsec e s m, Token s ~ Word8, Integral a)
=> m a
decimal_ = mkNum <$> takeWhile1P (Just "digit") isDigit
where
mkNum = foldl' step 0 . chunkToTokens (Proxy :: Proxy s)
step a w = a * 10 + fromIntegral (w - 48)
-- | Parse an integer in octal representation. Representation of octal
-- number is expected to be according to the Haskell report except for the
-- fact that this parser doesn't parse “0o” or “0O” prefix. It is a
-- responsibility of the programmer to parse correct prefix before parsing
-- the number itself.
--
-- For example you can make it conform to the Haskell report like this:
--
-- > octal = char '0' >> char' 'o' >> L.octal
octal
:: forall e s m a. (MonadParsec e s m, Token s ~ Word8, Integral a)
=> m a
octal = mkNum
<$> takeWhile1P Nothing isOctDigit
<?> "octal integer"
where
mkNum = foldl' step 0 . chunkToTokens (Proxy :: Proxy s)
step a w = a * 8 + fromIntegral (w - 48)
isOctDigit w = w - 48 < 8
{-# INLINEABLE octal #-}
-- | Parse an integer in hexadecimal representation. Representation of
-- hexadecimal number is expected to be according to the Haskell report
-- except for the fact that this parser doesn't parse “0x” or “0X” prefix.
-- It is a responsibility of the programmer to parse correct prefix before
-- parsing the number itself.
--
-- For example you can make it conform to the Haskell report like this:
--
-- > hexadecimal = char '0' >> char' 'x' >> L.hexadecimal
hexadecimal
:: forall e s m a. (MonadParsec e s m, Token s ~ Word8, Integral a)
=> m a
hexadecimal = mkNum
<$> takeWhile1P Nothing isHexDigit
<?> "hexadecimal integer"
where
mkNum = foldl' step 0 . chunkToTokens (Proxy :: Proxy s)
step a w
| w >= 48 && w <= 57 = a * 16 + fromIntegral (w - 48)
| w >= 97 = a * 16 + fromIntegral (w - 87)
| otherwise = a * 16 + fromIntegral (w - 55)
isHexDigit w =
(w >= 48 && w <= 57) ||
(w >= 97 && w <= 102) ||
(w >= 65 && w <= 70)
{-# INLINEABLE hexadecimal #-}
-- | Parse a floating point value as a 'Scientific' number. 'Scientific' is
-- great for parsing of arbitrary precision numbers coming from an untrusted
-- source. See documentation in "Data.Scientific" for more information.
--
-- The parser can be used to parse integers or floating point values. Use
-- functions like 'Data.Scientific.floatingOrInteger' from "Data.Scientific"
-- to test and extract integer or real values.
--
-- This function does not parse sign, if you need to parse signed numbers,
-- see 'signed'.
scientific
:: forall e s m. (MonadParsec e s m, Token s ~ Word8)
=> m Scientific
scientific = do
let pxy = Proxy :: Proxy s
c' <- decimal_
SP c e' <- option (SP c' 0) $ do
void (char 46)
let mkNum = foldl' step (SP c' 0) . chunkToTokens pxy
step (SP a e') w = SP
(a * 10 + fromIntegral (w - 48))
(e' - 1)
mkNum <$> takeWhile1P (Just "digit") isDigit
e <- option e' $ do
void (char' 101)
(+ e') <$> signed (return ()) decimal_
return (Sci.scientific c e)
{-# INLINEABLE scientific #-}
data SP = SP !Integer {-# UNPACK #-} !Int
-- | Parse a floating point number without sign. There are differences
-- between the syntax for floating point literals described in the Haskell
-- report and what this function accepts. In particular, it does not quire
-- fractional part and accepts inputs like @\"3\"@ returning @3.0@.
--
-- This is a simple short-cut defined as:
--
-- > float = Sci.toRealFloat <$> scientific <?> "floating point number"
--
-- This function does not parse sign, if you need to parse signed numbers,
-- see 'signed'.
float :: (MonadParsec e s m, Token s ~ Word8, RealFloat a) => m a
float = Sci.toRealFloat <$> scientific <?> "floating point number"
{-# INLINEABLE float #-}
-- | @'signed' space p@ parser parses an optional sign, then if there is a
-- sign it will consume optional white space (using @space@ parser), then it
-- runs parser @p@ which should return a number. Sign of the number is
-- changed according to previously parsed sign.
--
-- For example, to parse signed integer you can write:
--
-- > lexeme = L.lexeme spaceConsumer
-- > integer = lexeme L.decimal
-- > signedInteger = L.signed spaceConsumer integer
signed :: (MonadParsec e s m, Token s ~ Word8, Num a)
=> m () -- ^ How to consume white space after the sign
-> m a -- ^ How to parse the number itself
-> m a -- ^ Parser for signed numbers
signed spc p = ($) <$> option id (C.lexeme spc sign) <*> p
where
sign = (char 43 *> return id) <|> (char 45 *> return negate)
{-# INLINEABLE signed #-}
----------------------------------------------------------------------------
-- Helpers
-- | A fast predicate to check if given 'Word8' is a digit in ASCII.
isDigit :: Word8 -> Bool
isDigit w = w - 48 < 10
{-# INLINE isDigit #-}
| recursion-ninja/megaparsec | Text/Megaparsec/Byte/Lexer.hs | bsd-2-clause | 8,006 | 0 | 19 | 1,786 | 1,573 | 856 | 717 | 112 | 1 |
{-# LANGUAGE Haskell2010 #-}
module NamedDoc where
-- $foo bar
| haskell/haddock | html-test/src/NamedDoc.hs | bsd-2-clause | 65 | 0 | 2 | 12 | 6 | 5 | 1 | 2 | 0 |
-- |
-- Module: $Header$
-- Description: Top-level application mode
-- Copyright: (c) 2018-2020 Peter Trško
-- License: BSD3
--
-- Maintainer: [email protected]
-- Stability: experimental
-- Portability: GHC specific language extensions.
--
-- Top-level application mode. It provides the ability for us to handle help
-- without interference from option parsing library.
module CommandWrapper.Core.Options.GlobalMode
( GlobalMode(..)
, switchGlobalMode
, runGlobalMode
)
where
import Data.Function ((.))
import Data.Functor (Functor, fmap)
import Data.Monoid (Endo(Endo))
import Control.Comonad (Comonad(extend, extract))
-- | This allows global options parser to change application mode, but in a
-- very limited way.
data GlobalMode a
= HelpMode a
-- ^ Switch to internal @help@ command.
| VersionMode a
-- ^ Switch to internal @version@ command.
| PreserveMode a
deriving stock (Functor)
instance Comonad GlobalMode where
extract :: GlobalMode a -> a
extract = \case
HelpMode a -> a
VersionMode a -> a
PreserveMode a -> a
extend :: (GlobalMode a -> b) -> GlobalMode a -> GlobalMode b
extend f mode = case mode of
HelpMode _ -> HelpMode b
VersionMode _ -> VersionMode b
PreserveMode _ -> PreserveMode b
where
b = f mode
switchGlobalMode
:: (forall a. a -> GlobalMode a)
-> GlobalMode config
-> GlobalMode config
switchGlobalMode f = f . extract
runGlobalMode
:: Functor mode
=> (forall b. Endo b -> Endo (mode b))
-- ^ Switch to \"help\" mode.
-> (forall b. Endo b -> Endo (mode b))
-- ^ Switch to \"version\" mode.
-> GlobalMode (Endo a)
-> Endo (mode a)
runGlobalMode helpMode versionMode = \case
HelpMode f -> helpMode f
VersionMode f -> versionMode f
PreserveMode (Endo f) -> Endo (fmap f)
| trskop/command-wrapper | command-wrapper-core/src/CommandWrapper/Core/Options/GlobalMode.hs | bsd-3-clause | 1,914 | 0 | 13 | 485 | 464 | 248 | 216 | -1 | -1 |
module Annales.Buildings (
buildBuilding
,destroyBuilding
) where
import TextGen (
TextGen
,word
,choose
,remove
,list
)
import Annales.Empire (
TextGenCh
,Empire
,buildings
,generate
,randRemove
)
import Annales.Descriptions (
descNewBuilding
,descBuildingName
,descModifyBuilding
,descBuildingGone
)
import Annales.Omens (
omen
)
import Data.List (isInfixOf)
buildBuilding :: Empire -> IO ( Empire, TextGenCh )
buildBuilding e = do
b <- return $ descBuildingName e
dup <- existsBuilding e b
case dup of
False -> do
e' <- return $ e { buildings = b:(buildings e) }
return ( e', descNewBuilding e b )
True -> do
return ( e, descModifyBuilding e b )
existsBuilding :: Empire -> TextGenCh -> IO Bool
existsBuilding e b = do
bname <- generate b
bnames <- generate $ list $ buildings e
return ( bname `isInfixOf` bnames )
destroyBuilding :: Empire -> IO ( Empire, TextGenCh )
destroyBuilding e = do
( bgone, buildings' ) <- randRemove $ buildings e
case bgone of
[] -> omen e
(gone:b) -> do
e' <- return $ e { buildings = buildings' }
return ( e', descBuildingGone e gone )
| spikelynch/annales | app/Annales/Buildings.hs | bsd-3-clause | 1,195 | 0 | 18 | 304 | 411 | 215 | 196 | 46 | 2 |
{-# LANGUAGE PatternGuards #-}
-- | This module does command line completion
module System.Console.CmdArgs.Explicit.Complete(
Complete(..), complete,
completeBash, completeZsh
) where
import System.Console.CmdArgs.Explicit.Type
import Control.Monad
import Data.List
import Data.Maybe
-- | How to complete a command line option.
-- The 'Show' instance is suitable for parsing from shell scripts.
data Complete
= CompleteValue String -- ^ Complete to a particular value
| CompleteFile String FilePath -- ^ Complete to a prefix, and a file
| CompleteDir String FilePath -- ^ Complete to a prefix, and a directory
deriving (Eq,Ord)
instance Show Complete where
show (CompleteValue a) = "VALUE " ++ a
show (CompleteFile a b) = "FILE " ++ a ++ " " ++ b
show (CompleteDir a b) = "DIR " ++ a ++ " " ++ b
showList xs = showString $ unlines (map show xs)
prepend :: String -> Complete -> Complete
prepend a (CompleteFile b c) = CompleteFile (a++b) c
prepend a (CompleteDir b c) = CompleteDir (a++b) c
prepend a (CompleteValue b) = CompleteValue (a++b)
-- | Given a current state, return the set of commands you could type now, in preference order.
complete
:: Mode a -- ^ Mode specifying which arguments are allowed
-> [String] -- ^ Arguments the user has already typed
-> (Int,Int) -- ^ 0-based index of the argument they are currently on, and the position in that argument
-> [Complete]
-- Roll forward looking at modes, and if you match a mode, enter it
-- If the person just before is a flag without arg, look at how you can complete that arg
-- If your prefix is a complete flag look how you can complete that flag
-- If your prefix looks like a flag, look for legitimate flags
-- Otherwise give a file/dir if they are arguments to this mode, and all flags
-- If you haven't seen any args/flags then also autocomplete to any child modes
complete mode_ args_ (i,_) = nub $ followArgs mode args now
where
(seen,next) = splitAt i args_
now = head $ next ++ [""]
(mode,args) = followModes mode_ seen
-- | Given a mode and some arguments, try and drill down into the mode
followModes :: Mode a -> [String] -> (Mode a, [String])
followModes m (x:xs) | Just m2 <- pickBy modeNames x $ modeModes m = followModes m2 xs
followModes m xs = (m,xs)
pickBy :: (a -> [String]) -> String -> [a] -> Maybe a
pickBy f name xs = find (\x -> name `elem` f x) xs `mplus`
find (\x -> any (name `isPrefixOf`) (f x)) xs
-- | Follow args deals with all seen arguments, then calls on to deal with the next one
followArgs :: Mode a -> [String] -> (String -> [Complete])
followArgs m = first
where
first [] = expectArgFlagMode (modeModes m) (argsPick 0) (modeFlags m)
first xs = norm 0 xs
-- i is the number of arguments that have gone past
norm i [] = expectArgFlag (argsPick i) (modeFlags m)
norm i ("--":xs) = expectArg $ argsPick (i + length xs)
norm i (('-':'-':x):xs) | null b, flagInfo flg == FlagReq = val i flg xs
| otherwise = norm i xs
where (a,b) = break (== '=') x
flg = getFlag a
norm i (('-':x:y):xs) = case flagInfo flg of
FlagReq | null y -> val i flg xs
| otherwise -> norm i xs
FlagOpt{} -> norm i xs
_ | "=" `isPrefixOf` y -> norm i xs
| null y -> norm i xs
| otherwise -> norm i (('-':y):xs)
where flg = getFlag [x]
norm i (x:xs) = norm (i+1) xs
val i flg [] = expectVal flg
val i flg (x:xs) = norm i xs
argsPick i = let (lst,end) = modeArgs m in if i < length lst then Just $ lst !! i else end
-- if you can't find the flag, pick one that is FlagNone (has all the right fallback)
getFlag x = fromMaybe (flagNone [] id "") $ pickBy flagNames x $ modeFlags m
expectArgFlagMode :: [Mode a] -> Maybe (Arg a) -> [Flag a] -> String -> [Complete]
expectArgFlagMode mode arg flag x =
(if "-" `isPrefixOf` x then [] else expectMode mode x) ++
expectArgFlag arg flag x
expectArgFlag :: Maybe (Arg a) -> [Flag a] -> String -> [Complete]
expectArgFlag arg flag x
| "-" `isPrefixOf` x = expectFlag flag x ++ [CompleteValue "-" | x == "-", isJust arg]
| otherwise = expectArg arg x ++ expectFlag flag x
expectMode :: [Mode a] -> String -> [Complete]
expectMode mode = expectStrings (map modeNames mode)
expectArg :: Maybe (Arg a) -> String -> [Complete]
expectArg Nothing x = []
expectArg (Just arg) x = expectFlagHelp (argType arg) x
expectFlag :: [Flag a] -> String -> [Complete]
expectFlag flag x
| (a,_:b) <- break (== '=') x = case pickBy (map f . flagNames) a flag of
Nothing -> []
Just flg -> map (prepend (a ++ "=")) $ expectVal flg b
| otherwise = expectStrings (map (map f . flagNames) flag) x
where f x = "-" ++ ['-' | length x > 1] ++ x
expectVal :: Flag a -> String -> [Complete]
expectVal flg = expectFlagHelp (flagType flg)
expectStrings :: [[String]] -> String -> [Complete]
expectStrings xs x = map CompleteValue $ concatMap (take 1 . filter (x `isPrefixOf`)) xs
expectFlagHelp :: FlagHelp -> String -> [Complete]
expectFlagHelp typ x = case typ of
"FILE" -> [CompleteFile "" x]
"DIR" -> [CompleteDir "" x]
"FILE/DIR" -> [CompleteFile "" x, CompleteDir "" x]
"DIR/FILE" -> [CompleteDir "" x, CompleteFile "" x]
'[':s | "]" `isSuffixOf` s -> expectFlagHelp (init s) x
_ -> []
---------------------------------------------------------------------
-- BASH SCRIPT
completeBash :: String -> [String]
completeBash prog =
["# Completion for " ++ prog
,"# Generated by CmdArgs: http://community.haskell.org/~ndm/cmdargs/"
,"_" ++ prog ++ "()"
,"{"
," # local CMDARGS_DEBUG=1 # uncomment to debug this script"
,""
," COMPREPLY=()"
," function add { COMPREPLY[((${#COMPREPLY[@]} + 1))]=$1 ; }"
," IFS=$'\\n\\r'"
,""
," export CMDARGS_COMPLETE=$((${COMP_CWORD} - 1))"
," result=`" ++ prog ++ " ${COMP_WORDS[@]:1}`"
,""
," if [ -n $CMDARGS_DEBUG ]; then"
," echo Call \\(${COMP_WORDS[@]:1}, $CMDARGS_COMPLETE\\) > cmdargs.tmp"
," echo $result >> cmdargs.tmp"
," fi"
," unset CMDARGS_COMPLETE"
," unset CMDARGS_COMPLETE_POS"
,""
," for x in $result ; do"
," case $x in"
," VALUE\\ *)"
," add ${x:6}"
," ;;"
," FILE\\ *)"
," local prefix=`expr match \"${x:5}\" '\\([^ ]*\\)'`"
," local match=`expr match \"${x:5}\" '[^ ]* \\(.*\\)'`"
," for x in `compgen -f -- \"$match\"`; do"
," add $prefix$x"
," done"
," ;;"
," DIR\\ *)"
," local prefix=`expr match \"${x:4}\" '\\([^ ]*\\)'`"
," local match=`expr match \"${x:4}\" '[^ ]* \\(.*\\)'`"
," for x in `compgen -d -- \"$match\"`; do"
," add $prefix$x"
," done"
," ;;"
," esac"
," done"
," unset IFS"
,""
," if [ -n $CMDARGS_DEBUG ]; then"
," echo echo COMPREPLY: ${#COMPREPLY[@]} = ${COMPREPLY[@]} >> cmdargs.tmp"
," fi"
,"}"
,"complete -o bashdefault -F _" ++ prog ++ " " ++ prog
]
---------------------------------------------------------------------
-- ZSH SCRIPT
completeZsh :: String -> [String]
completeZsh _ = ["echo TODO: help add Zsh completions to cmdargs programs"]
| ndmitchell/cmdargs | System/Console/CmdArgs/Explicit/Complete.hs | bsd-3-clause | 7,708 | 0 | 15 | 2,197 | 2,161 | 1,136 | 1,025 | 144 | 10 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Rank2Types #-}
module Server.SVUser where
import Control.Lens ((.=), preuse, ix, use, (^.), zoom, (-=), (+=), (&), (.~))
import Control.Monad (unless, when, liftM, void)
import Data.Bits ((.&.))
import Data.Maybe (fromJust)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.Vector as V
import Game.CVarT
import Game.EdictT
import Game.EntityStateT
import QCommon.SizeBufT
import Server.ClientFrameT
import QCommon.NetChanT
import Server.ServerT
import Server.ServerStaticT
import Server.ClientT
import Types
import Game.UserCmdT
import QuakeState
import CVarVariables
import QuakeRef
import QCommon.XCommandT
import Server.UCmdT
import qualified Constants
import {-# SOURCE #-} qualified Game.Cmd as Cmd
import qualified Game.Info as Info
import qualified Game.PlayerClient as PlayerClient
import qualified QCommon.CBuf as CBuf
import {-# SOURCE #-} qualified QCommon.CVar as CVar
import {-# SOURCE #-} qualified QCommon.FS as FS
import qualified QCommon.MSG as MSG
import qualified QCommon.Com as Com
import qualified Server.SVMain as SVMain
import qualified Util.Lib as Lib
maxStringCmds :: Int
maxStringCmds = 8
nextServer :: Quake ()
nextServer = do
state <- use $ svGlobals.svServer.sState
coopValue <- CVar.variableValue "coop"
-- ZOID, ss_pic can be nextserver'd in coop mode
-- can't nextserver while playing a normal game
unless (state == Constants.ssGame || (state == Constants.ssPic && coopValue == 0)) $ do
svGlobals.svServerStatic.ssSpawnCount += 1 -- make sure another doesn't sneak in
v <- CVar.variableString "nextserver"
if B.length v == 0
then
CBuf.addText "killserver\n"
else do
CBuf.addText v
CBuf.addText "\n"
void $ CVar.set "nextserver" ""
nullCmd :: UserCmdT
nullCmd = newUserCmdT
nullState :: EntityStateT
nullState = newEntityStateT Nothing
uCmds :: V.Vector UCmdT
uCmds =
V.fromList [ UCmdT "new" newF
, UCmdT "configstrings" configStringsF
, UCmdT "baselines" baselinesF
, UCmdT "begin" beginF
, UCmdT "nextserver" nextServerF
, UCmdT "disconnect" disconnectF
-- issued by hand at client consoles
, UCmdT "info" showServerInfoF
, UCmdT "download" beginDownloadF
, UCmdT "nextdl" nextDownloadF
]
executeClientMessage :: Ref ClientT -> Quake ()
executeClientMessage clientRef@(Ref clientIdx) = do
svGlobals.svClient .= Just clientRef
Just edictRef <- preuse $ svGlobals.svServerStatic.ssClients.ix clientIdx.cEdict
svGlobals.svPlayer .= edictRef
-- only allow one move command
executeMessage False 0
where executeMessage :: Bool -> Int -> Quake ()
executeMessage moveIssued stringCmdCount = do
nm <- use $ globals.gNetMessage
if (nm^.sbReadCount) > (nm^.sbCurSize)
then do
Com.printf "SV_ReadClientMessage: bad read:\n"
-- Com.Printf(Lib.hexDump(Globals.net_message.data, 32, false));
SVMain.dropClient clientRef
else do
c <- liftM fromIntegral $ MSG.readByte (globals.gNetMessage)
(done, moveIssued', stringCmdCount') <- execute c moveIssued stringCmdCount
unless done $
executeMessage moveIssued' stringCmdCount'
execute :: Int -> Bool -> Int -> Quake (Bool, Bool, Int)
execute c moveIssued stringCmdCount = do
if c == -1
then return (True, moveIssued, stringCmdCount)
else do
if | c == Constants.clcNop -> return (True, moveIssued, stringCmdCount)
| c == Constants.clcUserInfo -> do
io (putStrLn "SVUser.executeClientMessage#executeMessage#clcUserInfo") >> undefined -- TODO
| c == Constants.clcMove -> do
if moveIssued
then return (True, moveIssued, stringCmdCount) -- someone is trying to cheat...
else do
Just client <- preuse $ svGlobals.svServerStatic.ssClients.ix clientIdx
checksumIndex <- use $ globals.gNetMessage.sbReadCount
checksum <- MSG.readByte (globals.gNetMessage)
lastFrame <- MSG.readLong (globals.gNetMessage)
when (lastFrame /= (client^.cLastFrame)) $ do
svGlobals.svServerStatic.ssClients.ix clientIdx.cLastFrame .= lastFrame
when (lastFrame > 0) $ do
realTime <- use $ svGlobals.svServerStatic.ssRealTime
let idx = lastFrame .&. (Constants.latencyCounts - 1)
svGlobals.svServerStatic.ssClients.ix clientIdx.cFrameLatency.ix idx .= realTime - (((client^.cFrames) V.! (lastFrame .&. Constants.updateMask))^.cfSentTime)
oldest <- MSG.readDeltaUserCmd (globals.gNetMessage) nullCmd
oldcmd <- MSG.readDeltaUserCmd (globals.gNetMessage) oldest
newcmd <- MSG.readDeltaUserCmd (globals.gNetMessage) oldcmd
if (client^.cState) /= Constants.csSpawned
then do
svGlobals.svServerStatic.ssClients.ix clientIdx.cLastFrame .= -1
return (False, True, stringCmdCount)
else do
-- if the checksum fails, ignore the rest of the packet
nm <- use $ globals.gNetMessage
calculatedChecksum <- Com.blockSequenceCRCByte (nm^.sbData) (checksumIndex + 1) ((nm^.sbReadCount) - checksumIndex - 1) (client^.cNetChan.ncIncomingSequence)
if fromIntegral (calculatedChecksum .&. 0xFF) /= checksum
then do
Com.dprintf $ "Failed checksum for ..." -- TODO: add more info
return (True, True, stringCmdCount)
else do
pausedValue <- liftM (^.cvValue) svPausedCVar
when (pausedValue == 0) $ do
let netDrop = client^.cNetChan.ncDropped
when (netDrop < 20) $ do
netDrop' <- execCmd clientRef (client^.cLastCmd) netDrop
when (netDrop' > 1) $
clientThink clientRef oldest
when (netDrop' > 0) $
clientThink clientRef oldcmd
clientThink clientRef newcmd
svGlobals.svServerStatic.ssClients.ix clientIdx.cLastCmd .= newcmd
return (False, True, stringCmdCount)
| c == Constants.clcStringCmd -> do
s <- MSG.readString (globals.gNetMessage)
-- malicious users may try using too many string commands
let stringCmdCount' = stringCmdCount + 1
when (stringCmdCount' < maxStringCmds) $
executeUserCommand s
Just state <- preuse $ svGlobals.svServerStatic.ssClients.ix clientIdx.cState
if state == Constants.csZombie
then return (True, moveIssued, stringCmdCount')
else return (False, moveIssued, stringCmdCount')
| otherwise -> do
io (putStrLn "SVUser.executeClientMessage#executeMessage") >> undefined -- TODO
execCmd :: Ref ClientT -> UserCmdT -> Int -> Quake Int
execCmd cr lastcmd netDrop
| netDrop > 2 = do
clientThink cr lastcmd
execCmd cr lastcmd (netDrop - 1)
| otherwise = return netDrop
clientThink :: Ref ClientT -> UserCmdT -> Quake ()
clientThink (Ref clientIdx) cmd = do
svGlobals.svServerStatic.ssClients.ix clientIdx.cCommandMsec -= (fromIntegral (cmd^.ucMsec) .&. 0xFF)
Just client <- preuse $ svGlobals.svServerStatic.ssClients.ix clientIdx
enforceTimeValue <- liftM (^.cvValue) svEnforceTimeCVar
if (client^.cCommandMsec) < 0 && enforceTimeValue /= 0
then Com.dprintf ("commandMsec underflow from " `B.append` (client^.cName) `B.append` "\n")
else PlayerClient.clientThink (fromJust $ client^.cEdict) cmd
executeUserCommand :: B.ByteString -> Quake ()
executeUserCommand str = do
Com.dprintf $ "SV_ExecuteUserCommand:" `B.append` str `B.append` "\n"
Cmd.tokenizeString str True
Just (Ref clientIdx) <- use $ svGlobals.svClient
Just (Just edictRef) <- preuse $ svGlobals.svServerStatic.ssClients.ix clientIdx.cEdict
svGlobals.svPlayer .= Just edictRef
v0 <- Cmd.argv 0
let foundCmd = V.find (\c -> (c^.ucName) == v0) uCmds
case foundCmd of
Just (UCmdT _ func) -> (func)^.xcCmd
Nothing -> do
state <- use $ svGlobals.svServer.sState
when (state == Constants.ssGame) $
Cmd.clientCommand edictRef
{-
- ================ SV_New_f
-
- Sends the first message from the server to a connected client. This will
- be sent on the initial connection and upon each server load.
- ================
-}
newF :: XCommandT
newF =
XCommandT "SVUser.newF" (do
Just (Ref clientIdx) <- use $ svGlobals.svClient
Just client <- preuse $ svGlobals.svServerStatic.ssClients.ix clientIdx
state <- use $ svGlobals.svServer.sState
Com.dprintf ("New() from " `B.append` (client^.cName) `B.append` "\n")
if | (client^.cState) /= Constants.csConnected ->
Com.printf "New not valid -- already spawned\n"
-- demo servers just dump the file message
| state == Constants.ssDemo -> beginDemoServer
| otherwise -> do
-- serverdata needs to go over for all types of servers
-- to make sure the protocol is right, and to set the gamedir
gameDir <- CVar.variableString "gamedir"
-- send the serverdata
MSG.writeByteI (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) Constants.svcServerData
MSG.writeInt (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) Constants.protocolVersion
spawnCount <- use $ svGlobals.svServerStatic.ssSpawnCount
MSG.writeLong (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) spawnCount
attractLoop <- use $ svGlobals.svServer.sAttractLoop
MSG.writeByteI (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) (if attractLoop then 1 else 0)
MSG.writeString (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) gameDir
let playerNum = if state == Constants.ssCinematic || state == Constants.ssPic
then -1
else client^.cServerIndex
MSG.writeShort (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) playerNum
-- send full levelname
Just levelName <- preuse $ svGlobals.svServer.sConfigStrings.ix (Constants.csName)
MSG.writeString (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) levelName
-- game server
when (state == Constants.ssGame) $ do
io $ print "STATE = CONSTANTS.SSGAME"
-- set up the entity for the client
let edictRef = Ref (playerNum + 1)
modifyRef edictRef (\v -> v & eEntityState.esNumber .~ playerNum + 1)
zoom (svGlobals.svServerStatic.ssClients.ix clientIdx) $ do
cEdict .= Just edictRef
cLastCmd .= newUserCmdT
-- begin fetching configstrings
MSG.writeByteI (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) Constants.svcStuffText
MSG.writeString (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) ("cmd configstrings " `B.append` (BC.pack $ show spawnCount) `B.append` " 0\n") -- IMPROVE?
)
configStringsF :: XCommandT
configStringsF =
XCommandT "SVUser.configStringsF" (do
Just clientRef@(Ref clientIdx) <- use $ svGlobals.svClient
Just client <- preuse $ svGlobals.svServerStatic.ssClients.ix clientIdx
Com.dprintf $ "Configstrings() from " `B.append` (client^.cName) `B.append` "\n"
if (client^.cState) /= Constants.csConnected
then Com.printf "configstrings not valid -- already spawned\n"
else do
-- handle the case of a level changing while a client was connecting
v1 <- Cmd.argv 1
spawnCount <- use $ svGlobals.svServerStatic.ssSpawnCount
if Lib.atoi v1 /= spawnCount
then do
Com.printf "SV_Configstrings_f from different level\n"
(newF)^.xcCmd
else do
v2 <- Cmd.argv 2
let start = Lib.atoi v2
-- write a packet full of data
configStrings <- use $ svGlobals.svServer.sConfigStrings
start' <- writeConfigStringsPacket configStrings clientRef start
-- send next command
if start' == Constants.maxConfigStrings
then do
MSG.writeByteI (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) Constants.svcStuffText
MSG.writeString (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) ("cmd baselines " `B.append` BC.pack (show spawnCount) `B.append` " 0\n");
else do
MSG.writeByteI (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) Constants.svcStuffText
MSG.writeString (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) ("cmd configstrings " `B.append` BC.pack (show spawnCount) `B.append` " " `B.append` BC.pack (show start') `B.append` "\n") -- IMPROVE?
)
where writeConfigStringsPacket :: V.Vector B.ByteString -> Ref ClientT -> Int -> Quake Int
writeConfigStringsPacket configStrings clientRef@(Ref clientIdx) start = do
Just curSize <- preuse $ svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage.sbCurSize
if curSize < Constants.maxMsgLen `div` 2 && start < Constants.maxConfigStrings
then do
let cs = configStrings V.! start
when (B.length cs /= 0) $ do
MSG.writeByteI (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) Constants.svcConfigString
MSG.writeShort (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) start
MSG.writeString (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) cs
writeConfigStringsPacket configStrings clientRef (start + 1)
else
return start
baselinesF :: XCommandT
baselinesF =
XCommandT "SVUser.baselinesF" (do
Just clientRef@(Ref clientIdx) <- use $ svGlobals.svClient
Just client <- preuse $ svGlobals.svServerStatic.ssClients.ix clientIdx
Com.dprintf $ "Baselines() from " `B.append` (client^.cName) `B.append` "\n"
if (client^.cState) /= Constants.csConnected
then
Com.printf "baselines not valid -- already spawned\n"
else do
-- handle the case of a level changing while a client was connecting
spawnCount <- use $ svGlobals.svServerStatic.ssSpawnCount
v1 <- Cmd.argv 1
if Lib.atoi v1 /= spawnCount
then do
Com.printf "SV_Baselines_f from different level\n"
(newF)^.xcCmd
else do
v2 <- Cmd.argv 2
let start = Lib.atoi v2
-- write a packet full of data
baselines <- use $ svGlobals.svServer.sBaselines
start' <- writeBaselinePacket baselines clientRef start
-- send next command
if start' == Constants.maxEdicts
then do
MSG.writeByteI (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) Constants.svcStuffText
MSG.writeString (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) ("precache " `B.append` BC.pack (show spawnCount) `B.append` "\n") -- IMPROVE?
else do
MSG.writeByteI (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) Constants.svcStuffText
MSG.writeString (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) ("cmd baselines " `B.append` BC.pack (show spawnCount) `B.append` " " `B.append` BC.pack (show start') `B.append` "\n") -- IMPROVE?
)
where writeBaselinePacket :: V.Vector EntityStateT -> Ref ClientT -> Int -> Quake Int
writeBaselinePacket baselines clientRef@(Ref clientIdx) start = do
Just curSize <- preuse $ svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage.sbCurSize
if curSize < Constants.maxMsgLen `div` 2 && start < Constants.maxEdicts
then do
let base = baselines V.! start
when ((base^.esModelIndex) /= 0 || (base^.esSound) /= 0 || (base^.esEffects) /= 0) $ do
MSG.writeByteI (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) Constants.svcSpawnBaseline
MSG.writeDeltaEntity nullState base (svGlobals.svServerStatic.ssClients.ix clientIdx.cNetChan.ncMessage) True True
writeBaselinePacket baselines clientRef (start + 1)
else
return start
beginF :: XCommandT
beginF =
XCommandT "SVUser.beginF" (do
Just (Ref clientIdx) <- use $ svGlobals.svClient
Just client <- preuse $ svGlobals.svServerStatic.ssClients.ix clientIdx
Com.dprintf $ "Begin() from " `B.append` (client^.cName) `B.append` "\n"
-- handle the case of a level changing while a client was connecting
v1 <- Cmd.argv 1
spawnCount <- use $ svGlobals.svServerStatic.ssSpawnCount
if Lib.atoi v1 /= spawnCount
then do
Com.printf "SV_Begin_f from different level\n"
(newF)^.xcCmd
else do
svGlobals.svServerStatic.ssClients.ix clientIdx.cState .= Constants.csSpawned
-- call the game begin function
Just edictRef <- use $ svGlobals.svPlayer
PlayerClient.clientBegin edictRef
CBuf.insertFromDefer
)
{-
- ================== SV_Nextserver_f ==================
-
- A cinematic has completed or been aborted by a client, so move to the
- next server
-}
nextServerF :: XCommandT
nextServerF =
XCommandT "SVUser.nextServerF" (do
c <- Cmd.argv 1
spawnCount <- use $ svGlobals.svServerStatic.ssSpawnCount
Just (Ref clientIdx) <- use $ svGlobals.svClient
Just name <- preuse $ svGlobals.svServerStatic.ssClients.ix clientIdx.cName
if Lib.atoi c /= spawnCount
then
Com.dprintf ("Nextserver() from wrong level, from " `B.append` name `B.append` "\n")
-- leftover from last server
else do
Com.dprintf ("Nextserver() from " `B.append` name `B.append` "\n")
nextServer
)
{-
- ================= SV_Disconnect_f =================
-
- The client is going to disconnect, so remove the connection immediately
-
-}
disconnectF :: XCommandT
disconnectF =
XCommandT "SVUser.disconnectF" (do
Just client <- use $ svGlobals.svClient
SVMain.dropClient client
)
{-
- ================== SV_ShowServerinfo_f ==================
-
- Dumps the serverinfo info string
-}
showServerInfoF :: XCommandT
showServerInfoF = XCommandT "SVUser.showServerInfoF" (CVar.serverInfo >>= Info.print)
beginDownloadF :: XCommandT
beginDownloadF =
XCommandT "SVUser.beginDownloadF" (do
io (putStrLn "SVUser.beginDownloadF") >> undefined -- TODO
)
nextDownloadF :: XCommandT
nextDownloadF =
XCommandT "SVUser.nextDownloadF" (do
io (putStrLn "SVUser.nextDownloadF") >> undefined -- TODO
)
beginDemoServer :: Quake ()
beginDemoServer = do
name <- use $ svGlobals.svServer.sName
let name' = "demos/" `B.append` name
demoFile <- FS.fOpenFile name'
case demoFile of
Nothing -> Com.comError Constants.errDrop ("Couldn't open " `B.append` name' `B.append` "\n")
Just _ -> svGlobals.svServer.sDemoFile .= demoFile
| ksaveljev/hake-2 | src/Server/SVUser.hs | bsd-3-clause | 20,683 | 0 | 34 | 5,791 | 5,059 | 2,545 | 2,514 | -1 | -1 |
module TestLoadBucket (tests) where
import Asserts
import Bucket.Import
import Bucket.Load
import Bucket.Types
import Data.Maybe
import Fixtures
import System.FilePath
import Test.Hspec.HUnit()
import Test.Hspec.Monadic
import Test.HUnit
tests = describe "loading bucket" $ do
it "loading non-existent bucket returns nothing" $ do
bucket <- loadBucketFrom "/a/non/existing/path"
assertBool "" (isNothing bucket)
describe "loading empty bucket" $ do
it "returns bucket with path" $ withBucket $ \((tmpDir, bucket)) -> do
Just loadedBucket <- loadBucketFrom $ bucketPath bucket
bucketPath loadedBucket @?= bucketPath bucket
it "returns bucket with no items" $ withBucket $ \((tmpDir, bucket)) -> do
Just loadedBucket <- loadBucketFrom $ bucketPath bucket
loadedBucket `assertHasItems` []
describe "loading non-empty bucket" $ do
it "loads all items" $ withBucket $ \((tmpDir, bucket)) -> do
createItemAt (bucketPath bucket </> "one-item") "item1.png"
createItemAt (bucketPath bucket </> "another-item") "item2.png"
Just loadedBucket <- loadBucketFrom (bucketPath bucket)
loadedBucket `assertHasItems` [bucketPath bucket </> "one-item", bucketPath bucket </> "another-item"]
it "loads items in subdirectories" $ withBucket $ \((tmpDir, bucket)) -> do
createItemAt (bucketPath bucket </> "subdir" </> "one-item") "item1.png"
Just loadedBucket <- loadBucketFrom (bucketPath bucket)
loadedBucket `assertHasItems` [bucketPath bucket </> "subdir" </> "one-item"]
it "skips files which are not items" $ withBucket $ \((tmpDir, bucket)) -> do
createEmptyFile (bucketPath bucket </> "not-an-item.png")
Just loadedBucket <- loadBucketFrom (bucketPath bucket)
loadedBucket `assertHasItems` []
it "loads meta back" $ withBucket $ \((tmpDir, bucket)) -> do
file <- createEmptyFile $ tmpDir </> "file1.png"
importFile bucket file
Just loadedBucket <- loadBucketFrom (bucketPath bucket)
let item = head (bucketItems loadedBucket)
fileName item @?= "file1.png"
| rickardlindberg/orgapp | tests/TestLoadBucket.hs | bsd-3-clause | 2,262 | 0 | 20 | 563 | 616 | 301 | 315 | 42 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedLists #-}
module Day10 where
import Protolude hiding (try)
import Prelude (read)
import Control.Lens
import Text.Megaparsec hiding (State)
import Text.Megaparsec.Text
import Data.MultiMap (MultiMap)
import Data.Map (Map)
import qualified Data.MultiMap as MMap
import qualified Data.Map as Map
import Data.Vector (Vector)
type BotId = Int
type OutputBinId = Int
type ChipId = Int
data BotsState = BotsState
{ _bots :: MultiMap BotId ChipId
, _bins :: MultiMap OutputBinId ChipId
, _history :: Vector (BotId, ChipId, ChipId)
, _policies :: Map BotId (ChipRecipient, ChipRecipient)
}
data BotInstruction
= ReceiveChip ChipId BotId
| SplitChips BotId ChipRecipient ChipRecipient
deriving (Show)
data ChipRecipient
= OutputBin OutputBinId
| Bot BotId
deriving (Show)
makeLenses ''BotsState
runBotSimulation :: [BotInstruction] -> BotsState
runBotSimulation is = execState simulate s
where
s = BotsState MMap.empty MMap.empty [] Map.empty
simulate = do
setupState is
enactPolicies
enactPolicies :: State BotsState ()
enactPolicies = do
botIds <- uses policies Map.keys
changed <- any identity <$> traverse enactBot botIds
when changed enactPolicies
where
enactBot botId = uses bots (MMap.lookup botId) >>= \case
(a:b:_) -> do
let (lo:hi:_) = sort [a, b]
bots %= MMap.delete botId
Just (recLo, recHi) <- uses policies (Map.lookup botId)
giveChip lo recLo
giveChip hi recHi
history <>= [(botId, lo, hi)]
return True
_ -> return False
setupState :: [BotInstruction] -> State BotsState ()
setupState = traverse_ followBotInstruction
where
followBotInstruction = \case
ReceiveChip chipId botId -> bots %= MMap.insert botId chipId
SplitChips botId recLo recHi -> policies %= Map.insert botId (recLo, recHi)
giveChip :: ChipId -> ChipRecipient -> State BotsState ()
giveChip c = \case
OutputBin binId -> bins %= MMap.insert binId c
Bot botId -> bots %= MMap.insert botId c
parseDay10 :: Text -> [BotInstruction]
parseDay10 t = is
where
Right is = parse botInstructionsP "" t
botInstructionsP :: Parser [BotInstruction]
botInstructionsP = botInstructionP `sepBy` eol
botInstructionP = receiveChipP <|> splitChipsP
receiveChipP = do
try $ string "value "
chipId <- numP
string " goes to bot "
botId <- numP
return $ ReceiveChip chipId botId
splitChipsP = do
string "bot "
botId <- numP
string " gives low to "
recLo <- chipRecipientP
string " and high to "
recHi <- chipRecipientP
return $ SplitChips botId recLo recHi
chipRecipientP = outputBinP <|> botP
outputBinP = do
try $ string "output "
binId <- numP
return $ OutputBin binId
botP = do
string "bot "
botId <- numP
return $ Bot botId
numP = read <$> some digitChar
| patrickherrmann/advent2016 | src/Day10.hs | bsd-3-clause | 2,977 | 0 | 18 | 716 | 932 | 472 | 460 | -1 | -1 |
module Data.TTask.Pretty.Contents
( ppActive
, ppStory
, ppStoryI
, ppStoryList
, ppSprint
, ppSprintList
, ppProjectPbl
, ppProjectSprintList
, ppProjectSprint
, ppProjectSprintDetail
, ppSprintHeaderDetail
, ppProjectStory
, ppProjectTask
, ppStatusRecord
) where
import Control.Applicative
import Control.Lens
import Data.TTask.Types
import Data.List
ppActive :: String -> Project -> String
ppActive pid pj = let
activeSprints :: Project -> [Sprint]
activeSprints = filter ((^.isRunning) . _sprintStatus) . _projectSprints
in concat
[ ppProjectHeader pid pj
, if activeSprints pj /= [] then "\n\nActive sprint(s) :\n" else "\nRunning sprint is nothing"
, intercalate "\n" . map ppSprintDetail $ activeSprints pj
, if _projectBacklog pj /= [] then "\n\nProduct backlog :\n" else ""
, ppProjectPbl pj
]
----
ppTask :: Task -> String
ppTask t = formatRecord "TASK"
(t^.taskId) (t^.taskPoint)
(t^.taskStatus) (t^.taskDescription)
ppStoryHeader :: UserStory -> String
ppStoryHeader s = formatRecord "STORY"
(s^.storyId) (s^.point)
(s^.storyStatus) (s^.storyDescription)
ppStory :: UserStory -> String
ppStory story = ppStoryI 1 story
ppStoryI :: Int -> UserStory -> String
ppStoryI r story = formatFamily r story ppStoryHeader _storyTasks ppTask
ppStoryList :: [UserStory] -> String
ppStoryList = intercalate "\n" . map ppStoryHeader
ppSprintHeader :: Sprint -> String
ppSprintHeader s = formatRecord "SPRINT"
(s^.sprintId) (s^.point)
(s^.sprintStatus) (s^.sprintDescription)
ppSprint :: Sprint -> String
ppSprint sprint = formatFamily 1 sprint ppSprintHeader _sprintStorys ppStoryHeader
ppSprintList :: [Sprint] -> String
ppSprintList = intercalate "\n" . map ppSprintHeader
ppProjectHeader :: String -> Project -> String
ppProjectHeader pid pj =
formatRecordShowedId "PROJECT" pid (pj^.point) (pj^.projectStatus) (pj^.projectName)
----
ppSprintDetail :: Sprint -> String
ppSprintDetail s
= formatFamily 1 s ppSprintHeaderDetail _sprintStorys $ \s -> ppStoryI 2 s
ppSprintHeaderDetail :: Sprint -> String
ppSprintHeaderDetail s = ppSprintHeader s ++ "\n" ++ ppStatus (_sprintStatus s)
----
ppProjectPbl :: Project -> String
ppProjectPbl = ppStoryList . _projectBacklog
ppProjectSprintList :: Project -> String
ppProjectSprintList = ppSprintList . _projectSprints
ppProjectSprint :: Id -> Project -> Maybe String
ppProjectSprint i pj = ppSprint <$> pj^?sprint i
ppProjectSprintDetail :: Id -> Project -> Maybe String
ppProjectSprintDetail i pj = ppSprintDetail <$> pj^?sprint i
ppProjectStory :: Id -> Project -> Maybe String
ppProjectStory i pj = ppStory <$> pj^?story i
ppProjectTask :: Id -> Project -> Maybe String
ppProjectTask i pj = ppTask <$> pj^?task i
----
formatRecord :: String -> Id -> Point -> TStatus -> String -> String
formatRecord htype i point st description =
formatRecordShowedId htype (show i) point st description
formatRecordShowedId :: String -> String -> Point -> TStatus -> String -> String
formatRecordShowedId htype i point st description = concat
[ htype ++ " - " , i , " : " , show $ point
, "pt [ " , ppStatusRecord $ st^.getLastStatus , " ] " , description
]
formatFamily :: Eq b => Int -> a -> (a -> String) -> (a -> [b]) -> (b -> String) -> String
formatFamily r x f g h = concat
[ f x , if g x /= [] then "\n" else "" , intercalate "\n" . map (indent . h) $ g x ]
where indent = ((concat $ replicate r " ")++)
----
ppStatusRecord :: TStatusRecord -> String
ppStatusRecord (StatusWait _) = "Wait"
ppStatusRecord (StatusRunning _) = "Running"
ppStatusRecord (StatusFinished _) = "Finished"
ppStatusRecord (StatusNotAchieved _) = "Not Achieved"
ppStatusRecord (StatusReject _) = "Reject"
ppStatus :: TStatus -> String
ppStatus s = intercalate "\n" . map pps . reverse $ s^.statusToList
where
pps :: TStatusRecord -> String
pps r =
let st = take 15 $ ppStatusRecord r ++ concat (replicate 16 " ")
in "To " ++ st ++ " at " ++ show (r^.getStatusTime)
| tokiwoousaka/ttask | src/Data/TTask/Pretty/Contents.hs | bsd-3-clause | 4,059 | 0 | 14 | 762 | 1,329 | 695 | 634 | 94 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : Api.hs
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- ReviewBoard API
--
-- This module provides the basic ReviewBoard API calls.
-- All calls are executed inside the 'RBAction' monad that represents
-- a session to the ReviewBoard server. A login to the server is performed
-- in the 'RBAction' run method 'runRBAction'.
--
-- All actions return the 'RBResponse' object that can be a 'RBok' with
-- the response 'JSValue' or 'RBerr' containing the error message and
-- the encoded response, if received. Errors are handled in
-- two ways:
--
-- * Network errors, for example connection errors throw an exception.
--
-- * Response errors resulting in for example invalid request parameters are
-- handled using the 'rbErrHandler' (by default print to stdin).
--
-- For API details see ReviewBoard project page <http://code.google.com/p/reviewboard/>
--
-----------------------------------------------------------------------------
-- TODO: find a generic way to build API calls based on path
module ReviewBoard.Api (
-- Modules
module ReviewBoard.Core,
module ReviewBoard.Request,
-- * API calls
-- ** Users and groups
userList,
groupList,
groupStar,
groupUnstar,
-- ** Review request
reviewRequest,
reviewRequestByChangenum,
reviewRequestNew,
reviewRequestDelete,
reviewRequestSet,
reviewRequestSetField,
reviewRequestSaveDraft,
reviewRequestDiscardDraft,
reviewRequestStar,
reviewRequestUnstar,
reviewRequestDiffNew,
reviewRequestScreenshotNew,
reviewRequestListAll,
reviewRequestListToGroup,
reviewRequestListToUser,
reviewRequestListFromUser,
-- ** Review
reviewAll,
reviewSaveDraft,
reviewDeleteDraft,
reviewPublishDraft,
-- ** Others
repositoryList,
-- * Util functions
execRBAction,
-- * Example
-- $example1
) where
import Prelude hiding (all)
import ReviewBoard.Core
import ReviewBoard.Request
import Control.Monad.Error
-- ---------------------------------------------------------------------------
-- User handling API calls
-- | Search for a user or list all users if user is Nothing
--
userList :: RBAction RBResponse
userList = apiGet users []
-- | Search for a group or list all group if Nothing
--
groupList :: Maybe String -> RBAction RBResponse
groupList (Just g) = apiGet (groups Nothing) [textField "query" g]
groupList Nothing = apiGet (groups Nothing) []
-- | Star group for group name
--
groupStar :: String -> RBAction RBResponse
groupStar g = apiGet (groups (Just g) . star) []
-- | Unstar group for group name
--
groupUnstar :: String -> RBAction RBResponse
groupUnstar g = apiGet (groups (Just g) . unstar) []
-- ---------------------------------------------------------------------------
-- Review request API calls
-- | Create new review request using the provided repository path and an optional
-- submit_as user. The returned response contains the @id@ of the new created
-- review request that can be accessed using 'rrId' helper function.
--
reviewRequestNew :: String -> Maybe String -> RBAction RBResponse
reviewRequestNew p (Just u) = apiPost (reviewrequests Nothing . new) $ [textField "repository_path" p, textField "submit_as" u]
reviewRequestNew p Nothing = apiPost (reviewrequests Nothing . new) [textField "repository_path" p]
-- | Delete review request with request @id@.
--
reviewRequestDelete :: Integer -> RBAction RBResponse
reviewRequestDelete id = apiPost (reviewrequests (Just id) . delete) []
-- | Get review request by @id@.
--
reviewRequest :: Integer -> RBAction RBResponse
reviewRequest id = apiPost (reviewrequests (Just id)) []
-- | Get review request by repository @id@ and changenum @id@
--
reviewRequestByChangenum :: Integer -> Integer -> RBAction RBResponse
reviewRequestByChangenum rId cId = apiPost (reviewrequests Nothing . repository rId . changenum cId) []
-- | Discard review request draft for @id@.
--
reviewRequestSaveDraft :: Integer -> RBAction RBResponse
reviewRequestSaveDraft id = apiPost (reviewrequests (Just id) . draft . save) []
-- | Save review request draft whith @id@.
--
reviewRequestDiscardDraft :: Integer -> RBAction RBResponse
reviewRequestDiscardDraft id = apiPost (reviewrequests (Just id) . draft . discard) []
-- | Set fields to review request draft with @id@.
--
reviewRequestSet :: Integer -> [(RRField, String)] -> RBAction RBResponse
reviewRequestSet id fs = apiPost (reviewrequests (Just id) . draft . set Nothing) (map (\(f, v) -> textField (show f) v) fs)
-- | Set one field for review request draft with @id@.
--
reviewRequestSetField :: Integer -> RRField -> String -> RBAction RBResponse
reviewRequestSetField id f v = apiPost (reviewrequests (Just id) . draft . set (Just f)) $ [textField "value" v]
-- | Star review request for id
--
reviewRequestStar :: Integer -> RBAction RBResponse
reviewRequestStar id = apiGet (reviewrequests (Just id) . star) []
-- | Star review request for id
--
reviewRequestUnstar :: Integer -> RBAction RBResponse
reviewRequestUnstar id = apiGet (reviewrequests (Just id) . unstar) []
-- | Add a new diff to a review request with @id@, file path and the basedir parameter.
--
reviewRequestDiffNew :: Integer -> String -> FilePath -> RBAction RBResponse
reviewRequestDiffNew id bd fp =
apiPost (reviewrequests (Just id) . diff . new) [fileUpload "path" fp "text/plain", textField "basedir" bd]
-- | Add a new screenshot with @file path@ to a review request with @id@
--
reviewRequestScreenshotNew :: Integer -> FilePath -> RBAction RBResponse
reviewRequestScreenshotNew id fp =
apiPost (reviewrequests (Just id) . screenshot . new) [fileUpload "path" fp ((contentType . extension) fp)]
where
extension = reverse . takeWhile (/= '.') . reverse
contentType "png" = "image/png"
contentType "gif" = "image/gif"
contentType "jpg" = "image/jpeg"
contentType "jpeg" = "image/jpeg"
contentType _ = "text/plain" -- fallback
-- | List all review requests with an optional status
--
reviewRequestListAll :: Maybe String -> RBAction RBResponse
reviewRequestListAll (Just s) = apiGet (reviewrequests Nothing . all) [textField (show STATUS) s]
reviewRequestListAll Nothing = apiGet (reviewrequests Nothing . all) []
-- | List review request assigned to a group with an optional status
--
reviewRequestListToGroup :: String -> Maybe String -> RBAction RBResponse
reviewRequestListToGroup g (Just s) = apiGet (reviewrequests Nothing . to . group (Just g)) [textField (show STATUS) s]
reviewRequestListToGroup g Nothing = apiGet (reviewrequests Nothing . to . group (Just g)) []
-- | List review request assigned to a user, directly or not with an optional status
--
reviewRequestListToUser :: String -> Bool -> Maybe String -> RBAction RBResponse
reviewRequestListToUser u True (Just s) = apiGet (rr2u u . directly) [textField (show STATUS) s]
reviewRequestListToUser u True Nothing = apiGet (rr2u u . directly) []
reviewRequestListToUser u False (Just s) = apiGet (rr2u u) [textField (show STATUS) s]
reviewRequestListToUser u False Nothing = apiGet (rr2u u) []
rr2u u = reviewrequests Nothing . to . user (Just u)
-- | List review request from a user with an optional status
--
reviewRequestListFromUser :: String -> Maybe String -> RBAction RBResponse
reviewRequestListFromUser u (Just s) = apiGet (reviewrequests Nothing . from . user (Just u)) [textField (show STATUS) s]
reviewRequestListFromUser u Nothing = apiGet (reviewrequests Nothing . from . user (Just u)) []
-- ---------------------------------------------------------------------------
-- Review API calls
-- | List all reviews for review request @id@
--
reviewAll :: Integer -> RBAction RBResponse
reviewAll id = apiGet (reviewrequests (Just id) . reviews Nothing) []
-- | Publish review request draft for id
--
reviewPublishDraft :: Integer -> RBAction RBResponse
reviewPublishDraft id = apiPost (reviewrequests (Just id) . reviews Nothing . draft . publish) [checkBox "shipit" False]
-- | Save review draft for review request @id@
--
reviewSaveDraft :: Integer -> RBAction RBResponse
reviewSaveDraft id = apiPost (reviewrequests (Just id) . reviews Nothing . draft . save) []
-- | Delete review draft for review request @id@
--
reviewDeleteDraft :: Integer -> RBAction RBResponse
reviewDeleteDraft id = apiPost (reviewrequests (Just id) . reviews Nothing . draft . delete) []
-- ---------------------------------------------------------------------------
-- Other API calls
-- | List repositories
--
repositoryList :: RBAction RBResponse
repositoryList = apiGet repositories []
-- ---------------------------------------------------------------------------
-- API uitl functions
-- | Execute a ReviewBoard action using the provided URL, user
-- and password.
--
execRBAction :: String -> String -> String -> (RBAction a) -> IO a
execRBAction url user password action = do
r <- runRBAction url user password action
either error return $ fst r
{- $example1
The following RBAction creates a new review request draft, sets some fields
and uploads a diff file:
> import ReviewBoard.Api
> import qualified ReviewBoard.Response as R
> newRRAction :: RBAction ()
> newRRAction = do
> rsp <- reviewRequestNew "repository" Nothing
> case rsp of
> RBok r -> do
> let id = R.id . R.review_request $ r
> reviewRequestsSetField id TARGET_PEOPLE "reviewers"
> reviewRequestsSetField id DESCRIPTION "Request description"
> reviewRequestsDiffNew id "basedir" "diffFileName"
> reviewRequestSaveDraft id
> liftIO $ print "Done."
> RBerr s -> throwError s
To run this action, execute:
> execRBAction "url" "user" "password" newRRAction
-}
| asmyczek/hreviewboard | ReviewBoard/Api.hs | bsd-3-clause | 10,015 | 0 | 12 | 1,830 | 2,024 | 1,061 | 963 | 104 | 5 |
-- Copyright (c) 2015 Eric McCorkle. All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS''
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
-- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
-- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.
{-# OPTIONS_GHC -Wall -Werror #-}
module IR.Common.Rename(
Rename(..)
) where
import IR.Common.Rename.Class
| emc2/iridium | src/IR/Common/Rename.hs | bsd-3-clause | 1,680 | 0 | 5 | 295 | 53 | 46 | 7 | 4 | 0 |
-- Compiler Toolkit: some basic definitions used all over the place
--
-- Author : Manuel M. T. Chakravarty
-- Created: 16 February 95
--
-- Version $Revision: 1.44 $ from $Date: 2000/10/05 07:51:28 $
--
-- Copyright (c) [1995..2000] Manuel M. T. Chakravarty
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Library General Public
-- License as published by the Free Software Foundation; either
-- version 2 of the License, or (at your option) any later version.
--
-- This library 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
-- Library General Public License for more details.
--
--- DESCRIPTION ---------------------------------------------------------------
--
-- This module provides some definitions used throughout all modules of a
-- compiler.
--
--- DOCU ----------------------------------------------------------------------
--
-- language: Haskell 98
--
-- * May not import anything apart from `Config'.
--
--- TODO ----------------------------------------------------------------------
--
module Text.CTK.Common (
-- error code
--
errorCodeError, errorCodeFatal,
--
-- source text positions
--
Position, Pos (posOf), nopos, isNopos, dontCarePos, isDontCarePos,
builtinPos, isBuiltinPos, internalPos, isInternalPos,
incPos, tabPos, retPos,
--
-- pretty printing
--
PrettyPrintMode(..), dftOutWidth, dftOutRibbon,
--
-- support for debugging
--
assert
) where
import Text.CTK.Config (assertEnabled)
-- error codes
-- -----------
-- error code when a compilation spotted program errors (EXPORTED)
--
errorCodeError :: Int
errorCodeError = 1
-- error code for fatal errors aborting the run of the toolkit (EXPORTED)
--
errorCodeFatal :: Int
errorCodeFatal = 2
-- Miscellaneous stuff for parsing
-- -------------------------------
-- uniform representation of source file positions; the order of the arguments
-- is important as it leads to the desired ordering of source positions
-- (EXPORTED)
--
type Position = (String, -- file name
Int, -- row
Int) -- column
-- no position (for unknown position information) (EXPORTED)
--
nopos :: Position
nopos = ("<no file>", -1, -1)
isNopos :: Position -> Bool
isNopos (_, -1, -1) = True
isNopos _ = False
-- don't care position (to be used for invalid position information) (EXPORTED)
--
dontCarePos :: Position
dontCarePos = ("<invalid>", -2, -2)
isDontCarePos :: Position -> Bool
isDontCarePos (_, -2, -2) = True
isDontCarePos _ = False
-- position attached to objects that are hard-coded into the toolkit (EXPORTED)
--
builtinPos :: Position
builtinPos = ("<built into the compiler>", -3, -3)
isBuiltinPos :: Position -> Bool
isBuiltinPos (_, -3, -3) = True
isBuiltinPos _ = False
-- position used for internal errors (EXPORTED)
--
internalPos :: Position
internalPos = ("<internal error>", -4, -4)
isInternalPos :: Position -> Bool
isInternalPos (_, -4, -4) = True
isInternalPos _ = False
-- instances of the class `Pos' are associated with some source text position
-- don't care position (to be used for invalid position information) (EXPORTED)
--
class Pos a where
posOf :: a -> Position
-- advance column
--
incPos :: Position -> Int -> Position
incPos (fname, row, col) n = (fname, row, col + n)
-- advance column to next tab positions (tabs are at every 8th column)
--
tabPos :: Position -> Position
tabPos (fname, row, col) = (fname, row, (col + 8 - (col - 1) `mod` 8))
-- advance to next line
--
retPos :: Position -> Position
retPos (fname, row, col) = (fname, row + 1, 1)
-- Miscellaneous stuff for pretty printing
-- ---------------------------------------
-- pretty printing modes (EXPORTED)
--
data PrettyPrintMode = PPMRaw -- display raw structure only
| PPMVerbose -- display all available info
-- default parameters used for pretty printing (EXPORTED)
--
dftOutWidth :: Int
dftOutWidth = 79
dftOutRibbon :: Int
dftOutRibbon = 50
-- support for debugging
-- ---------------------
-- assert is used to catch internal inconsistencies and raises a fatal internal
-- error if such an inconsistency is spotted (EXPORTED)
--
-- an inconsistency occured when the first argument to `assert' is `False'; in
-- a distribution version, the checks can be disabled by setting
-- `assertEnabled' to `False'---to favour speed
--
assert :: Bool -> String -> a -> a
assert p msg v = if assertEnabled
then
if p then v else error (premsg ++ msg ++ "\n")
else
v
where
premsg = "INTERNAL COMPILER ERROR: Assertion failed:\n"
| mwotton/ctkl | src/Text/CTK/Common.hs | bsd-3-clause | 4,962 | 0 | 10 | 1,108 | 713 | 458 | 255 | 56 | 3 |
module Data.ROS.Service ( Service(..) ) where
import Data.ROS.Service.Definition
import Data.ROS.Service.Internal
| ROSVendor/msg_dbg | lib/Data/ROS/Service.hs | bsd-3-clause | 116 | 0 | 5 | 12 | 30 | 21 | 9 | 3 | 0 |
{-# LANGUAGE TemplateHaskell #-}
-- | Instance of 'Lift' for 'SimpleCon'
module Data.Unboxed.LiftCon(SimpleCon(..), SimpleData(..), simpleCon, unSimpleCon, toName, fromName, Lift) where
import Language.Haskell.TH.Syntax
import Language.Haskell.TH.Lift
-- names
type SimpleName = String
toName :: SimpleName -> Name
toName = mkName
fromName :: Name -> SimpleName
fromName = nameBase
-- types
data SimpleType
= VarTS SimpleName
| ConTS SimpleName
| AppTS SimpleType SimpleType
| TupleTS Int
| ArrowTS
| ListTS
| SigTS SimpleType Kind
| ForallTS [SimpleTyVarBndr] SimpleCxt SimpleType
toType :: SimpleType -> Type
toType (VarTS nm) = VarT (toName nm)
toType (ConTS nm) = ConT (toName nm)
toType (AppTS t1 t2) = AppT (toType t1) (toType t2)
toType (TupleTS n) = TupleT n
toType ArrowTS = ArrowT
toType ListTS = ListT
toType (SigTS ty k) = SigT (toType ty) k
toType (ForallTS bndrs cxt t) = ForallT (map toBndr bndrs) (map toPred cxt) (toType t)
fromType :: Type -> SimpleType
fromType (VarT nm) = VarTS (fromName nm)
fromType (ConT nm) = ConTS (fromName nm)
fromType (AppT t1 t2) = AppTS (fromType t1) (fromType t2)
fromType (TupleT n) = TupleTS n
fromType ArrowT = ArrowTS
fromType ListT = ListTS
fromType (SigT ty k) = SigTS (fromType ty) k
fromType (ForallT bndrs cxt t) = ForallTS (map fromBndr bndrs) (map fromPred cxt) (fromType t)
data SimpleTyVarBndr
= PlainTVS SimpleName
| KindedTVS SimpleName Kind
toBndr :: SimpleTyVarBndr -> TyVarBndr
toBndr (PlainTVS nm) = PlainTV (toName nm)
toBndr (KindedTVS nm k) = KindedTV (toName nm) k
fromBndr :: TyVarBndr -> SimpleTyVarBndr
fromBndr (PlainTV nm) = PlainTVS (fromName nm)
fromBndr (KindedTV nm k) = KindedTVS (fromName nm) k
type SimpleCxt = [SimplePred]
data SimplePred
= ClassPS SimpleName [SimpleType]
| EqualPS SimpleType SimpleType
toPred :: SimplePred -> Pred
toPred (ClassPS nm tys) = ClassP (toName nm) (map toType tys)
toPred (EqualPS t1 t2) = EqualP (toType t1) (toType t2)
fromPred :: Pred -> SimplePred
fromPred (ClassP nm tys) = ClassPS (fromName nm) (map fromType tys)
fromPred (EqualP t1 t2) = EqualPS (fromType t1) (fromType t2)
type SimpleStrictType = (Strict, SimpleType)
toStrictType :: SimpleStrictType -> StrictType
toStrictType (str, ty) = (str, toType ty)
fromStrictType :: StrictType -> SimpleStrictType
fromStrictType (str, ty) = (str, fromType ty)
-- constructors
data SimpleCon' = SimpleCon' [SimpleTyVarBndr] SimpleCxt SimpleName [SimpleStrictType]
toSimpleCon :: SimpleCon' -> SimpleCon
toSimpleCon (SimpleCon' bndrs cxt nm tys) = SimpleCon (map toBndr bndrs) (map toPred cxt) (toName nm) (map toStrictType tys)
fromSimpleCon :: SimpleCon -> SimpleCon'
fromSimpleCon (SimpleCon bndrs cxt nm tys) = SimpleCon' (map fromBndr bndrs) (map fromPred cxt) (fromName nm) (map fromStrictType tys)
instance Lift SimpleCon where
lift con = [| toSimpleCon $(lift (fromSimpleCon con)) |]
instance Lift SimpleData where
lift (SimpleData nm bndrs cons) = [| SimpleData (toName $(lift $ fromName nm)) (map toBndr $(lift $ map fromBndr bndrs)) cons |]
-- old interface
data SimpleData = SimpleData Name [TyVarBndr] [SimpleCon]
data SimpleCon = SimpleCon [TyVarBndr] Cxt Name [StrictType]
simpleCon :: Con -> SimpleCon
simpleCon (NormalC nm stys) = SimpleCon [] [] nm stys
simpleCon (RecC nm vstys) = SimpleCon [] [] nm (map (\(_,s,t) -> (s,t)) vstys)
simpleCon (InfixC st1 nm st2) = SimpleCon [] [] nm [st1, st2]
simpleCon (ForallC bndrs cxt con) = case simpleCon con of
SimpleCon [] [] nm ts -> SimpleCon bndrs cxt nm ts
unSimpleCon :: SimpleCon -> Con
unSimpleCon (SimpleCon [] [] nm ts) = NormalC nm ts
unSimpleCon (SimpleCon bndrs cxt nm ts) = ForallC bndrs cxt (NormalC nm ts)
$(deriveLiftMany [''SimpleType, ''SimpleTyVarBndr, ''SimplePred, ''Kind, ''Strict, ''SimpleCon'])
-- $(deriveLiftMany [''SimpleCon, ''Strict, ''TyVarBndr, ''Pred, ''Type, ''Kind])
| reinerp/th-unboxing | Data/Unboxed/LiftCon.hs | bsd-3-clause | 3,878 | 0 | 10 | 628 | 1,474 | 772 | 702 | 81 | 1 |
module System.Taffybar.Widget.Generic.ChannelGraph where
import BroadcastChan
import Control.Concurrent
import Control.Monad
import Control.Monad.IO.Class
import Data.Foldable (traverse_)
import GI.Gtk
import System.Taffybar.Widget.Generic.Graph
-- | Given a 'BroadcastChan' and an action to consume that broadcast chan and
-- turn it into graphable values, build a graph that will update as values are
-- broadcast over the channel.
channelGraphNew
:: MonadIO m
=> GraphConfig -> BroadcastChan In a -> (a -> IO [Double]) -> m GI.Gtk.Widget
channelGraphNew config chan sampleBuilder = do
(graphWidget, graphHandle) <- graphNew config
_ <- onWidgetRealize graphWidget $ do
ourChan <- newBChanListener chan
sampleThread <- forkIO $ forever $
readBChan ourChan >>=
traverse_ (graphAddSample graphHandle <=< sampleBuilder)
void $ onWidgetUnrealize graphWidget $ killThread sampleThread
return graphWidget
| teleshoes/taffybar | src/System/Taffybar/Widget/Generic/ChannelGraph.hs | bsd-3-clause | 952 | 0 | 16 | 165 | 213 | 111 | 102 | 20 | 1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
module River.Core.Primitive (
Prim(..)
) where
import Control.DeepSeq (NFData)
import Data.Data (Data)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import River.Effect
data Prim =
Neg
| Not
| Add
| Sub
| Mul
| Div
| Mod
| Eq
| Ne
| Lt
| Le
| Gt
| Ge
| And
| Xor
| Or
| Shl
| Shr
deriving (Eq, Ord, Read, Show, Data, Typeable, Generic, NFData)
instance HasEffect Prim where
hasEffect p =
Set.member p effectfulPrims
effectfulPrims :: Set Prim
effectfulPrims =
Set.fromList [Mul, Div, Mod]
| jystic/river | src/River/Core/Primitive.hs | bsd-3-clause | 787 | 0 | 7 | 235 | 225 | 135 | 90 | 38 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE GADTs #-}
module BitD.BitcoinD.RPC ( rpcCall
, rpcGetBlockHash
, rpcGetBlockCount
, rpcGetRawMemPool
, rpcGetRawMemPool'
, rpcGetRawTransaction
, UTF8BS(..)
) where
import BitD.Prelude
import BitD.Networks (Network(..))
import BitD.Protocol.Types (Hash256Hex(..), TxID(..), toBS, toHex, fromHex)
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Lazy.Char8 as BSLC
import qualified Data.Aeson as JSON
import qualified Data.Aeson.Types as AT
import Data.Aeson ((.=), (.:))
import qualified Control.Monad as M
import Data.Maybe (catMaybes)
import System.Process (readProcessWithExitCode)
import System.Exit (ExitCode(..))
data Options = Options { _rpcUser :: String
, _rpcPassword :: String
, _rpcUrl :: String
}
-- | Parameters to connect to bitcoind.
-- TODO: do not hardcode, connect to a config system.
getOptions :: Network -> Options
getOptions BTCMain = Options "bitcoinrpc" "4HixkVrDAE8B81DnS4PVrVFqEXaY5jrQBwei7CeobSwc" "http://127.0.0.1:8332/"
getOptions BTCTest = Options "bitcoinrpc" "4HixkVrDAE8B81DnS4PVrVFqEXaY5jrQBwei7CeobSwc" "http://127.0.0.1:18332/"
rpcCall :: (JSON.ToJSON p, JSON.FromJSON r) => Network -> String -> [p] -> IO (Maybe r)
rpcCall network method params = do
let options = getOptions network
(code, ret, _) <- readProcessWithExitCode "curl" [
"-s",
"--user",
(_rpcUser options ++ ":" ++ _rpcPassword options),
"--data-binary",
BSLC.unpack $ JSON.encode $ JSON.object ["jsonrpc" .= JSON.String "1.0"
,"id" .= JSON.String "bitd"
,"method" .= method
,"params" .= params
],
"-H",
"content-type: text/plain;",
_rpcUrl options
] ""
return $ case code of
ExitFailure _ -> Nothing
ExitSuccess -> do
decoded <- JSON.decodeStrict' $ BSC.pack ret
flip AT.parseMaybe decoded $ \obj ->
obj .: "error" >>= \case
JSON.Null -> obj .: "result"
_ -> M.mzero
noParams :: [()]
noParams = []
newtype UTF8BS = UTF8BS BS.ByteString
deriving (Show)
fromUTF8BS :: UTF8BS -> BS.ByteString
fromUTF8BS (UTF8BS bs) = bs
instance JSON.FromJSON UTF8BS where
parseJSON (JSON.String s) = return $ UTF8BS $ encodeUtf8 s
parseJSON _ = M.mzero
instance JSON.ToJSON UTF8BS where
toJSON (UTF8BS s) = JSON.String $ decodeUtf8 s
rpcGetBlockHash :: Network -> Word32 -> IO (Maybe Hash256Hex)
rpcGetBlockHash network index = do
result <- rpcCall network "getblockhash" [index]
case result of
Nothing -> return Nothing
Just (UTF8BS bs) -> return $ Just $ Hash256Hex bs
rpcGetBlockCount :: Network -> IO (Maybe Integer)
rpcGetBlockCount network = rpcCall network "getblockcount" noParams
rpcGetRawMemPool' :: Network -> IO (Maybe [TxID])
rpcGetRawMemPool' network = do
txHashes <- rpcCall network "getrawmempool" noParams :: IO (Maybe [UTF8BS])
return $ (map (fromHex . Hash256Hex . fromUTF8BS) <$> txHashes)
rpcGetRawTransaction :: Network -> TxID -> IO (Maybe BS.ByteString)
rpcGetRawTransaction network txHash = do
rpcCall network "getrawtransaction" [UTF8BS $ toHex txHash] >>= \case
Nothing -> return Nothing
Just (UTF8BS rawTxHex) -> return $ Just $ fst $ B16.decode rawTxHex
rpcGetRawMemPool :: Network -> IO (Maybe [BS.ByteString])
rpcGetRawMemPool network = do
txHashes <- rpcGetRawMemPool' network
case txHashes of
Nothing -> return Nothing
Just txHashes' -> do
rawTxs <- M.forM txHashes' $ \txHash -> rpcCall network "getrawtransaction" [UTF8BS $ toHex txHash]
return $ Just $ map (\(UTF8BS rawTxHex) -> fst $ B16.decode rawTxHex) $ catMaybes rawTxs
| benma/bitd | src/BitD/BitcoinD/RPC.hs | bsd-3-clause | 4,171 | 0 | 19 | 1,065 | 1,166 | 623 | 543 | 91 | 3 |
{-# OPTIONS_HADDOCK not-home #-}
module Test.WebDriver.Types
( -- * WebDriver sessions
WD(..), WDSession(..), defaultSession, SessionId(..)
-- * Capabilities and configuration
, Capabilities(..), defaultCaps, allCaps
, Platform(..), ProxyType(..), UnexpectedAlertBehavior(..)
-- ** Browser-specific configuration
, Browser(..),
-- ** Default settings for browsers
firefox, chrome, ie, opera, iPhone, iPad, android
, LogLevel(..), IELogLevel(..), IEElementScrollBehavior(..)
-- * WebDriver objects and command-specific types
, Element(..)
, WindowHandle(..), currentWindow
, Selector(..)
, JSArg(..)
, FrameSelector(..)
, Cookie(..), mkCookie
, Orientation(..)
, MouseButton(..)
, WebStorageType(..)
, LogType, LogEntry(..)
, ApplicationCacheStatus(..)
-- * Exceptions
, InvalidURL(..), NoSessionId(..), BadJSON(..)
, HTTPStatusUnknown(..), HTTPConnError(..)
, UnknownCommand(..), ServerError(..)
, FailedCommand(..), FailedCommandType(..)
, FailedCommandInfo(..), StackFrame(..)
, mkFailedCommandInfo, failedCommand
) where
import Test.WebDriver.Monad
import Test.WebDriver.Classes
import Test.WebDriver.Commands
import Test.WebDriver.Exceptions
import Test.WebDriver.Capabilities
| fpco/hs-webdriver | src/Test/WebDriver/Types.hs | bsd-3-clause | 1,406 | 0 | 5 | 342 | 322 | 228 | 94 | 31 | 0 |
{-# LANGUAGE UndecidableInstances #-}
module Data.Rivers.Monads where
data Cofree f a = Root { extract :: a, branch :: f (Cofree f a) }
data Free f a = Var a | Com (f (Free f a))
instance (Show a, Show (f (Cofree f a))) => Show (Cofree f a) where show (Root a x) = show a ++ "@" ++ show x
instance (Show a, Show (f (Free f a))) => Show ( Free f a) where show (Var x) = show x
show (Com x) = show x
eval' :: (Functor f) => (a -> b) -> (f b -> b) -> (Free f a -> b)
eval' var ___ (Var x) = var x
eval' var com (Com x) = com (fmap (eval' var com) x)
eval :: (Functor f) => (f b -> b) -> (Free f b -> b)
eval ___ (Var x) = x
eval com (Com x) = com (fmap (eval com) x)
trace :: (Functor f) => (b -> a) -> (b -> f b) -> (b -> Cofree f a)
trace get next b = Root (get b) (fmap (trace get next) (next b))
delta :: (Functor f) => Cofree f a -> Cofree f (Cofree f a)
delta t@(Root _ us) = Root t (fmap delta us)
instance (Functor f) => Functor (Cofree f) where fmap f (Root a ts) = Root (f a) (fmap (fmap f) ts)
instance (Functor f) => Functor ( Free f) where fmap f (Var x) = Var (f x)
fmap f (Com x) = Com (fmap (fmap f) x)
instance (Functor f) => Monad ( Free f) where return = Var
m >>= k = join (fmap k m)
join :: (Functor f) => Free f (Free f a) -> Free f a
join (Var x) = x
join (Com x) = Com (fmap join x)
embed :: (Functor f) => f a -> Free f a
embed = Com . fmap Var
up :: (Functor f) => (f a -> a) -> (Free f a -> a)
down :: (Functor f) => (Free f a -> a) -> (f a -> a)
up a = eval a
down a = a . embed
| d-rive/rivers | Data/Rivers/Monads.hs | bsd-3-clause | 1,767 | 0 | 11 | 633 | 1,001 | 509 | 492 | -1 | -1 |
{-# LANGUAGE CPP, RebindableSyntax, OverloadedStrings #-}
module Main where
import TestExampleDataSource
import BatchTests
import CoreTests
import DataCacheTest
#ifdef HAVE_APPLICATIVEDO
import AdoTests
#endif
import Data.String
import Test.HUnit
import Haxl.Prelude
main :: IO Counts
main = runTestTT $ TestList
[ TestLabel "ExampleDataSource" TestExampleDataSource.tests
, TestLabel "BatchTests" BatchTests.tests
, TestLabel "CoreTests" CoreTests.tests
, TestLabel "DataCacheTests" DataCacheTest.tests
#ifdef HAVE_APPLICATIVEDO
, TestLabel "AdoTests" AdoTests.tests
#endif
]
| tolysz/Haxl | tests/Main.hs | bsd-3-clause | 593 | 0 | 9 | 77 | 109 | 62 | 47 | 15 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Saturnin.Git
( readFile
, runCmd
, GitSource (..)
, GitURI (..)
, GitRevOrRef (..)
)
where
import qualified Data.ByteString as B
import Data.Text.Lazy (Text, unpack, pack)
import Formatting
import Prelude hiding (readFile)
import System.Exit
import System.FilePath.Posix
import System.IO hiding (readFile)
import System.Process
newtype GitURI = GitURI { uri :: Text }
deriving (Show, Read)
newtype GitRevOrRef = GitRevOrRef { revOrRef :: Text }
deriving (Show, Read)
data GitSource = GitSource
{ gsUri :: GitURI
, gsRevOrRef :: GitRevOrRef
}
deriving (Show, Read)
-- | readFile reads FilePath from repository at GitSource
--
-- Implemented by clone uri; checkout ref/rev and then just readFile
--
-- Other approach could be:
-- git archive --remote=<uri> <tree-ish> <filepath>
-- But it's not currently possible as the <tree-ish> is too
-- restricted:
--
-- 3. Clients may not use other sha1 expressions, even if the end
-- result is reachable. E.g., neither a relative commit like
-- master^ nor a literal sha1 like abcd1234 is allowed, even if
-- the result is reachable from the refs. [1]_
--
-- .. [1]: man git-upload-archive
readFile
:: GitSource
-> FilePath -- The file to read
-> FilePath -- Working directory
-> IO B.ByteString
readFile (GitSource u r) p wd = do
_ <- clone u wd (Just "repo")
_ <- checkout (wd </> "repo") r
B.readFile (wd </> "repo" </> p)
clone
:: GitURI
-> FilePath -- Directory to clone into
-> Maybe FilePath -- Directory name for the repository
-> IO (String, String)
clone (GitURI u) wd (Just n) = runGit wd ["clone", u, pack n]
clone (GitURI u) wd (Nothing) = runGit wd ["clone", u]
checkout :: FilePath -> GitRevOrRef -> IO (String, String)
checkout wd (GitRevOrRef r) = runGit wd ["checkout", r]
runGit
:: FilePath -- working directory
-> [Text] -- argv
-> IO (String, String)
runGit wd argv = runCmd (Just wd) "git" $ fmap unpack argv
runCmd
:: Maybe FilePath -- cwd
-> FilePath -- exe
-> [String] -- argv
-> IO (String, String) -- out, err
runCmd cwd' exe argv = do
let cp = (proc exe argv)
{ cwd = cwd'
, std_out = CreatePipe
, std_err = CreatePipe
}
(_, Just hout, Just herr, ph) <- createProcess cp
ec <- waitForProcess ph
out <- hGetContents hout
err <- hGetContents herr
ret ec out err
where
ret (f @ (ExitFailure _)) out err = error . unpack $ format
( shown
% ": " % shown
% " " % shown
% " out: " % shown
% " err: " % shown
% "\n"
)
f exe argv out err
ret ExitSuccess out err = return (out, err)
| yaccz/saturnin | library/Saturnin/Git.hs | bsd-3-clause | 2,885 | 1 | 18 | 847 | 771 | 425 | 346 | 70 | 2 |
module Camera(
Camera(..)
, cameraMoveForward
, cameraMoveLeft
, cameraMoveRight
, cameraRotateYaw
, cameraRotatePitch
) where
import Control.DeepSeq
import GHC.Generics
import Linear
data Camera = Camera {
cameraUp :: !(V3 Float)
, cameraForward :: !(V3 Float)
, cameraEye :: !(V3 Float)
} deriving (Generic)
instance NFData Camera
cameraRight :: Camera -> V3 Float
cameraRight Camera{..} = normalize $ cameraForward `cross` cameraUp
cameraLeft :: Camera -> V3 Float
cameraLeft Camera{..} = normalize $ cameraUp `cross` cameraForward
cameraMoveForward :: Float -> Camera -> Camera
cameraMoveForward v c = c { cameraEye = cameraEye c + fmap (v*) (cameraForward c) }
cameraMoveLeft :: Float -> Camera -> Camera
cameraMoveLeft v c = c { cameraEye = cameraEye c + fmap (v*) (cameraLeft c) }
cameraMoveRight :: Float -> Camera -> Camera
cameraMoveRight v c = c { cameraEye = cameraEye c + fmap (v*) (cameraRight c) }
cameraRotateYaw :: Float -> Camera -> Camera
cameraRotateYaw v c = c { cameraForward = rotate (axisAngle (cameraUp c) (-v)) $ cameraForward c }
cameraRotatePitch :: Float -> Camera -> Camera
cameraRotatePitch v c = c { cameraForward = rotate (axisAngle (cameraRight c) v) $ cameraForward c } | Teaspot-Studio/model-gridizer | src/Camera.hs | bsd-3-clause | 1,249 | 0 | 12 | 235 | 449 | 241 | 208 | -1 | -1 |
module CallByName.EvaluatorSuite
( tests
) where
import CallByName.Data
import CallByName.Evaluator
import CallByName.Parser (expression)
import Control.Monad.Trans.State.Lazy (evalStateT)
import Data.List (stripPrefix)
import Test.HUnit
import Text.Megaparsec
tests :: Test
tests = TestList
[ testEq "Eval const" (ExprNum 3) "3"
, testEq "Eval bounded var" (ExprNum 5) "let v = 5 in v"
, testNoBound "Eval no-bounded var" "let x = 5 in y"
, testEq "Eval binary num-to-num operator" (ExprNum 5) "-(10, 5)"
, testEq "Eval binary num-to-bool operator (true case)"
(ExprBool True) "greater?(4, 3)"
, testEq "Eval binary num-to-bool operator (false case)"
(ExprBool False) "less?(5,2)"
, testEq "Eval minus" (ExprNum (-1)) "minus(1)"
, testLet
, testCond
, testProc
, testByNameParams
]
testLet :: Test
testLet = TestList
[ testEq "Eval let"
(ExprNum 2)
$ unlines
[ "let x = 30"
, "in let y = -(x,2)"
, " in -(x,y)"
]
, testEq "Eval letrec"
(ExprNum 12)
$ unlines
[ "letrec double(x)"
, " = if zero?(x) then 0 else -((double -(x,1)), -2)"
, "in (double 6)"
]
, testEq "Eval co-recursion"
(ExprNum 1)
$ unlines
[ "letrec"
, " even(x) = if zero?(x) then 1 else (odd -(x,1))"
, " odd(x) = if zero?(x) then 0 else (even -(x,1))"
, "in (odd 13)"
]
, testEq "Eval let and begin expression"
(ExprNum 12)
$ unlines
[ "let times4 = 0"
, "in begin"
, " set times4 = proc (x)"
, " if zero?(x)"
, " then 0"
, " else -((times4 -(x,1)), -4);"
, " (times4 3)"
, " end"
]
]
testCond :: Test
testCond = TestList
[ testEq "Eval true branch of if expression"
(ExprNum 3)
"if zero? (0) then 3 else 4"
, testEq "Eval false branch of if expression"
(ExprNum 4)
"if zero? (5) then 3 else 4"
, testError "Empty condition expression should fail" "cond end"
, testError "A condition expression with no true predicate should fail"
"cond zero?(5) ==> 3 greater?(5, 10) ==> 4 end"
, testEq "Match first condition"
(ExprNum 1)
"cond zero?(0) ==> 1 zero?(0) ==> 2 zero?(0) ==> 3 end"
, testEq "Match third condition"
(ExprNum 3)
"cond zero?(1) ==> 1 zero?(2) ==> 2 zero?(0) ==> 3 end"
]
testProc :: Test
testProc = TestList
[ testEq "Eval proc and call expression (no parameter)"
(ExprNum 1)
"(proc () 1)"
, testEq "Eval proc and call expression (1 parameter)"
(ExprNum 2)
"(proc (x) + (x, x) 1)"
, testEq "Eval proc and call expression (many parameters)"
(ExprNum 7)
"(proc (x y z) + (x, * (y, z)) 1 2 3)"
, testEq "Eval named proc"
(ExprNum 7)
"let f = proc (x y z) + (x, * (y, z)) in (f 1 2 3)"
, testError "Too many parameters" "(proc () 1 1)"
, testError "Too many arguments" "(proc (x y) +(x, y) 1)"
]
testByNameParams :: Test
testByNameParams = TestList
[ testEq "By name parameters should be evaluated every time is it's called."
(ExprNum 6)
$ unlines
[ "let x = 3 in "
, "let incX = proc(a) begin set x = + (x, a); x end in"
, "let threeTimes = proc (a) begin a; a; a end in "
, "(threeTimes (incX 1))"
]
, testEq "Nested by name call should work as flat situation."
(ExprNum 7)
$ unlines
[ "let x = 3 in"
, "let incX = proc(a) begin set x = + (x, a); x end in"
, "let threeTimes = proc (a) begin a; a; a end in "
, "let callThree = proc (a) begin a; (threeTimes a) end in"
, "(callThree (incX 1))"
]
, testEq ("If a value is not called, " `mappend`
"the by name parameter should not being evaluated.")
(ExprNum 3)
$ unlines
[ "let x = 3 in"
, "let incX = proc(a) begin set x = + (x, a); x end in"
, "let alwaysX = proc (a) x in"
, "(alwaysX (incX 1))"
]
]
initEnv :: Environment
initEnv = empty
testEq :: String -> ExpressedValue -> String -> Test
testEq msg expect input = TestCase $
assertEqual msg (Right expect) evalRes
where
evalRes = case runParser expression "Test equal case" input of
Right pRes -> evalStateT (valueOf pRes initEnv) initStore
Left pError -> Left $ show pError
testError :: String -> String -> Test
testError msg input = TestCase $
assertBool msg evalRes
where
evalRes = case runParser expression "Test equal case" input of
Right pRes ->
case evalStateT (valueOf pRes initEnv) initStore of
Left _ -> True
Right _ -> False
Left _ -> False
testNoBound :: String -> String -> Test
testNoBound msg input = TestCase $
assertEqual msg noBound True
where
noBound = case runParser expression "Test nobound case" input of
Right pRes ->
case evalStateT (valueOf pRes initEnv) initStore of
Left s ->
case stripPrefix "Not in scope: " s of
Nothing -> False
_ -> True
_ -> False
_ -> False
| li-zhirui/EoplLangs | test/CallByName/EvaluatorSuite.hs | bsd-3-clause | 5,678 | 0 | 15 | 2,114 | 994 | 518 | 476 | 143 | 4 |
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -Wall #-}
-- | Algebra
module Tower.Ordering (
-- * lattice
POrd(..)
, POrdering(..)
, Topped(..)
, Bottomed(..)
, Bounded
, Negated(..)
, Semilattice
, Lattice(..)
, ord2pord
) where
import qualified Protolude as P
import Protolude (Double, Float, Int, Integer, Bool(..), Ord(..), Eq(..), fst)
import Data.Coerce
import Tower.Magma
-- | Equal to, Less than, Greater than, Not comparable to
data POrdering = PEQ | PLT | PGT | PNC
class POrd s where pcompare :: s -> s -> POrdering
instance (Ord a) => POrd a where
pcompare n m = if n > m then PGT else if n == m then PEQ else PLT
ord2pord :: P.Ordering -> POrdering
ord2pord P.EQ = PEQ
ord2pord P.LT = PLT
ord2pord P.GT = PGT
class POrd s => Topped s where top :: s
class POrd s => Bottomed s where bottom :: s
class ( Associative a
, Commutative a
, Idempotent a) =>
Semilattice a
class ( Topped a
, Bottomed a) =>
Bounded a
instance Topped Int where top = P.maxBound
instance Bottomed Int where bottom = P.minBound
instance Bounded Int
instance Topped Bool where top = True
instance Bottomed Bool where bottom = False
instance Bounded Bool
class (
Coercible a (Sup a)
, Coercible a (Inf a)
, Semilattice (Sup a)
, Semilattice (Inf a)
, POrd a
) => Lattice a where
type family Inf a
type family Sup a
(/\) :: a -> a -> a
(/\) = coerce ((⊕) :: Sup a -> Sup a -> Sup a)
(\/) :: a -> a -> a
(\/) = coerce ((⊕) :: Inf a -> Inf a -> Inf a)
class (Lattice a, Isomorphic (Inf a) (Sup a) ) => Negated a where
negated :: a -> a
negated a = coerce (fst iso (coerce a :: Inf a) :: Sup a) :: a
-- Int
newtype InfInt = InfInt Int
newtype SupInt = SupInt Int
instance Magma InfInt where
InfInt a ⊕ InfInt b = InfInt (if a <= b then a else b)
instance Magma SupInt where
SupInt a ⊕ SupInt b = SupInt (if a >= b then a else b)
instance Associative InfInt
instance Associative SupInt
instance Commutative SupInt
instance Commutative InfInt
instance Idempotent SupInt
instance Idempotent InfInt
instance Homomorphic SupInt InfInt where hom (SupInt a) = InfInt (-a)
instance Homomorphic InfInt SupInt where hom (InfInt a) = SupInt (-a)
instance Isomorphic SupInt InfInt where iso = (hom, hom)
instance Isomorphic InfInt SupInt where iso = (hom, hom)
instance Semilattice SupInt
instance Semilattice InfInt
instance Lattice Int where
type Inf Int = InfInt
type Sup Int = SupInt
-- Integer
newtype InfInteger = InfInteger Integer
newtype SupInteger = SupInteger Integer
instance Magma InfInteger where
InfInteger a ⊕ InfInteger b = InfInteger (if a <= b then a else b)
instance Magma SupInteger where
SupInteger a ⊕ SupInteger b = SupInteger (if a >= b then a else b)
instance Associative InfInteger
instance Associative SupInteger
instance Commutative SupInteger
instance Commutative InfInteger
instance Idempotent SupInteger
instance Idempotent InfInteger
instance Homomorphic SupInteger InfInteger where hom (SupInteger a) = InfInteger (-a)
instance Homomorphic InfInteger SupInteger where hom (InfInteger a) = SupInteger (-a)
instance Isomorphic SupInteger InfInteger where iso = (hom, hom)
instance Isomorphic InfInteger SupInteger where iso = (hom, hom)
instance Semilattice SupInteger
instance Semilattice InfInteger
instance Lattice Integer where
type Inf Integer = InfInteger
type Sup Integer = SupInteger
-- Float
newtype InfFloat = InfFloat Float
newtype SupFloat = SupFloat Float
instance Magma InfFloat where
InfFloat a ⊕ InfFloat b = InfFloat (if a <= b then a else b)
instance Magma SupFloat where
SupFloat a ⊕ SupFloat b = SupFloat (if a >= b then a else b)
instance Associative InfFloat
instance Associative SupFloat
instance Commutative SupFloat
instance Commutative InfFloat
instance Idempotent SupFloat
instance Idempotent InfFloat
instance Homomorphic SupFloat InfFloat where hom (SupFloat a) = InfFloat (-a)
instance Homomorphic InfFloat SupFloat where hom (InfFloat a) = SupFloat (-a)
instance Isomorphic SupFloat InfFloat where iso = (hom, hom)
instance Isomorphic InfFloat SupFloat where iso = (hom, hom)
instance Semilattice SupFloat
instance Semilattice InfFloat
instance Lattice Float where
type Inf Float = InfFloat
type Sup Float = SupFloat
-- Double
newtype InfDouble = InfDouble Double
newtype SupDouble = SupDouble Double
instance Magma InfDouble where
InfDouble a ⊕ InfDouble b = InfDouble (if a <= b then a else b)
instance Magma SupDouble where
SupDouble a ⊕ SupDouble b = SupDouble (if a >= b then a else b)
instance Associative InfDouble
instance Associative SupDouble
instance Commutative SupDouble
instance Commutative InfDouble
instance Idempotent SupDouble
instance Idempotent InfDouble
instance Homomorphic SupDouble InfDouble where hom (SupDouble a) = InfDouble (-a)
instance Homomorphic InfDouble SupDouble where hom (InfDouble a) = SupDouble (-a)
instance Isomorphic SupDouble InfDouble where iso = (hom, hom)
instance Isomorphic InfDouble SupDouble where iso = (hom, hom)
instance Semilattice SupDouble
instance Semilattice InfDouble
instance Lattice Double where
type Inf Double = InfDouble
type Sup Double = SupDouble
| tonyday567/tower | src/Tower/Ordering.hs | bsd-3-clause | 5,394 | 0 | 11 | 1,065 | 1,847 | 970 | 877 | -1 | -1 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
-- | This module provides the 'Constraint' type.
module Jat.Constraints
(
PATerm
, PAFun (..)
, PAVar (..)
, vmap
, top
, bot
, isTop,isBot
, not
, add,sub,and,or,gte,eq,neq,ass
, ufun, int, bool
, uvar, ivar, bvar
, prettyPATerm
, isVar,isUVar, isIVar,isBVar
, isUFun, isRFun, isIFun, isBFun
, isUTerm
, toDNF
, pushNot
, normalise
{-, simplify-}
)
where
import qualified Data.Rewriting.Term as T
import Jat.Utils.Pretty ((<>),(<+>))
import qualified Jat.Utils.Pretty as PP
import Prelude hiding (and,or,not)
data PAFun =
UFun String
| IConst Int
| BConst Bool
| Add | Sub
| Not | Or | And
| Lt | Lte | Gt | Gte
| Eq | Neq
| Ass
deriving(Show,Eq,Ord)
data PAVar =
UVar String Int
| IVar String Int
| BVar String Int
deriving (Show,Eq,Ord)
isVar,isUVar, isIVar,isBVar :: PATerm -> Bool
isVar (T.Var _) = True
isVar _ = False
isUVar (T.Var (UVar _ _)) = True
isUVar _ = False
isIVar (T.Var (IVar _ _)) = True
isIVar _ = False
isBVar (T.Var (BVar _ _)) = True
isBVar _ = False
isRFun,isUFun, isIFun,isBFun :: PATerm -> Bool
isUFun (T.Fun (UFun _) _) = True
isUFun _ = False
isRFun (T.Fun f _) = f `elem` [Lt, Lte, Gt, Gte, Eq,Neq]
isRFun _ = False
isIFun (T.Fun (IConst _) _) = True
isIFun (T.Fun i _) = i `elem` [Add,Sub]
isIFun _ = False
isBFun (T.Fun (BConst _) _) = True
isBFun (T.Fun b _) = b `elem` [And,Or,Not]
isBFun _ = False
isUTerm :: PATerm -> Bool
isUTerm t = isUFun t || isUVar t
vmap :: (Int -> Int) -> PAVar -> PAVar
vmap f (UVar s i) = UVar s (f i)
vmap f (IVar s i) = IVar s (f i)
vmap f (BVar s i) = BVar s (f i)
type PATerm = T.Term PAFun PAVar
top :: PATerm
top = T.Fun (BConst True) []
bot :: PATerm
bot = T.Fun (BConst False) []
isTop :: PATerm -> Bool
isTop (T.Fun (BConst True) []) = True
isTop _ = False
isBot :: PATerm -> Bool
isBot (T.Fun (BConst False) []) = True
isBot _ = False
-- only RFuns
toDNF :: PATerm -> [PATerm]
toDNF = distribute . pushNot
where
distribute (T.Fun Or ts) = concatMap distribute ts
distribute (T.Fun And ts) = [T.Fun And ts' | ts' <- mapM distribute ts]
distribute t = [t]
pushNot :: PATerm -> PATerm
pushNot (T.Fun Not [t]) = pushNot' t where
pushNot' (T.Fun And ts) = T.Fun Or $ map pushNot' ts
pushNot' (T.Fun Or ts) = T.Fun And $ map pushNot' ts
pushNot' (T.Fun Not [s]) = s
pushNot' (T.Fun Lt ts) = T.Fun Gte ts
pushNot' (T.Fun Lte ts) = T.Fun Gt ts
pushNot' (T.Fun Gte ts) = T.Fun Lt ts
pushNot' (T.Fun Gt ts) = T.Fun Lte ts
pushNot' (T.Fun Eq ts) = T.Fun Neq ts
pushNot' (T.Fun Neq ts) = T.Fun Eq ts
pushNot' (T.Fun (BConst True) []) = bot
pushNot' (T.Fun (BConst False) []) = top
pushNot' v@(T.Var _) = T.Fun Not [v]
pushNot' _ = error "Jat.Constraints: the impossible happened"
pushNot (T.Fun And ts) = T.Fun And (map pushNot ts)
pushNot (T.Fun Or ts) = T.Fun Or (map pushNot ts)
pushNot t = t
normalise :: PATerm -> PATerm
normalise = ineq . lhs
where
lhs c@(T.Fun f [t1@(T.Fun _ _),t2@(T.Var _)])
| isRFun c = T.Fun (revf f) [t2,t1]
lhs t = t
ineq (T.Fun Gt [t1,t2]) = gte t1 (add t2 $ int 1)
ineq (T.Fun Lt [t1,t2]) = T.Fun Lte [t1, sub t2 (int 1)]
ineq t = t
revf Lt = Gt
revf Gt = Lt
revf Lte = Gte
revf Gte = Lte
revf f = f
add,sub,and,or,gte,eq,neq,ass :: PATerm -> PATerm -> PATerm
add t1 t2 = T.Fun Add [t1,t2]
sub t1 t2 = T.Fun Sub [t1,t2]
and t1 t2 = T.Fun And [t1,t2]
or t1 t2 = T.Fun Or [t1,t2]
gte t1 t2 = T.Fun Gte [t1,t2]
eq t1 t2 = T.Fun Eq [t1,t2]
neq t1 t2 = T.Fun Neq [t1,t2]
ass t1 t2 = T.Fun Ass [t1,t2]
not :: PATerm -> PATerm
not t = T.Fun Not [t]
ufun :: String -> [PATerm] -> PATerm
ufun = T.Fun . UFun
int :: Int -> PATerm
int i = T.Fun (IConst i) []
bool :: Bool -> PATerm
bool b = T.Fun (BConst b) []
uvar :: String -> Int -> PATerm
uvar s = T.Var . UVar s
ivar :: String -> Int -> PATerm
ivar s = T.Var . IVar s
bvar :: String -> Int -> PATerm
bvar s = T.Var . BVar s
instance PP.Pretty PATerm where
pretty = prettyPATerm
prettyPATerm :: PATerm -> PP.Doc
prettyPATerm (T.Fun f ts) = case f of
UFun s -> PP.text s <> args ts where
args ts1 = PP.encloseSep PP.lparen PP.rparen PP.comma [prettyPATerm ti | ti <- ts1]
IConst i
| null ts -> PP.int i
| otherwise -> errorx
BConst b
| null ts -> PP.bool b
| otherwise -> errorx
Add -> binary "+" ts
Sub -> binary "-" ts
Not -> unary "not" ts
And -> binary "&&" ts
Or -> binary "||" ts
Lt -> binary "<" ts
Lte -> binary "=<" ts
Gte -> binary ">=" ts
Gt -> binary ">" ts
Eq -> binary "==" ts
Neq -> binary "/=" ts
Ass -> binary ":=" ts
where
binary s [t1,t2] = PP.parens $ prettyPATerm t1 <+> PP.text s <+> prettyPATerm t2
binary _ _ = errorx
unary _ [t] = PP.text "not" <> PP.parens (prettyPATerm t)
unary _ _ = errorx
errorx = error "prettyCTerm: malformed tmer"
prettyPATerm (T.Var v) = case v of
UVar s i -> PP.text s <> PP.int i
IVar s i -> PP.char 'i' <> PP.text s <> PP.int i
BVar s i -> PP.char 'b' <> PP.text s <> PP.int i
| ComputationWithBoundedResources/jat | src/Jat/Constraints.hs | bsd-3-clause | 5,515 | 0 | 15 | 1,660 | 2,653 | 1,382 | 1,271 | 170 | 19 |
{-# LANGUAGE BinaryLiterals #-}
module Main where
import Prelude hiding (cycle)
import Machine
import AssemblerParser
import AssemblerTranslator
import Text.Parsec (parse)
import System.IO
import PpComputerState
import Control.Monad.State.Lazy
fetchASM :: IO [ASM]
fetchASM = do putStr "Path to .xasm file: "
f <- getLine
s <- readFile f
let x = parse assemblerParser f s
case x of Left e -> (putStrLn $ show e) >> fetchASM
Right p -> return p
produceInitialState :: [ASM] -> IO XComputerState
produceInitialState p = return (0,0,0,0,0,0,0,0,m)
where m = produceMemoryMap p 0
main = do hSetBuffering stdin NoBuffering
hSetBuffering stdout NoBuffering
p <- fetchASM
s <- produceInitialState p
putStrLn $ ppComputerState s
go s
go :: XComputerState -> IO ()
go s = do (instruction,s') <- runStateT (cycle) s
putStrLn $ ppComputerState s'
case instruction of HLT -> return ()
_ -> go s'
| danielbarter/xcomputer | src/Main.hs | bsd-3-clause | 1,095 | 0 | 13 | 350 | 344 | 173 | 171 | 31 | 2 |
module Lichen.Plagiarism.Provided where
import qualified Data.Set as Set
--import qualified Data.Map.Strict as Map
import Lichen.Plagiarism.Submitty
providedFingerprints :: FilePath -> Set.Set Fingerprint
providedFingerprints _ = undefined
| Submitty/AnalysisTools | src/Lichen/Plagiarism/Provided.hs | bsd-3-clause | 243 | 0 | 7 | 28 | 44 | 27 | 17 | 5 | 1 |
{-# LANGUAGE QuasiQuotes, TypeFamilies, PackageImports #-}
import File.Binary
import File.Binary.Instances
import File.Binary.Instances.BigEndian
import Control.Monad.Instances
import "monads-tf" Control.Monad.Error
main :: IO ()
main = do
-- let hoge = fromBinary () "hello" :: Maybe (TestBitsConst, String)
(hoge, rest) <- fromBinary () "hello" :: IO (TestBitsConst, String)
print hoge
hage <- toBinary () hoge :: IO String
print hage
[binary|
TestBitsConst deriving Show
1: some
1{BitsInt}: 0
{Bool}: True
6{BitsInt}: seven
1: other
|]
| YoshikuniJujo/binary-file | examples/testBitConstant.hs | bsd-3-clause | 550 | 0 | 9 | 83 | 120 | 66 | 54 | 13 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Astro.Coords.ECRSpec where
import Test.Hspec
import Test.QuickCheck
import Data.AEq
import TestUtil
import TestInstances
import Astrodynamics (greenwichRA)
import Astro.Coords
import Astro.Coords.ECR
import Astro.Coords.PosVel
import Astro.Place
import Astro.Time -- (UT1, E, addTime)
import Astro.Time.At
import Astro.Util (perfectGEO, perfectGEO')
import Numeric.Units.Dimensional.Prelude
import Numeric.Units.Dimensional.LinearAlgebra
import Numeric.Units.Dimensional.LinearAlgebra.PosVel (radius)
import qualified Prelude
main = hspec spec
spec = do
spec_ecrToECI
spec_eciToECR
spec_ecrToECIPV
spec_eciToECRPV
-- ----------------------------------------------------------
spec_ecrToECI = describe "ecrToECI" $ do
it "doesn't add out-of plane components to a perfect GEO" $ property $
\(l::GeoLongitude D) t -> (vElemAt n2 . c . ecrToECI t . perfectGEO) l == _0
it "is the inverse of eciToECR" $ property $
\(p::Coord ECR D) t -> (eciToECR t . ecrToECI t) p ~== p
it "does not change the out-of-plane component" $ property $
\(p::Coord ECR D) t -> vElemAt n2 (c $ ecrToECI t p) == vElemAt n2 (c p)
it "does not change the radius" $ property $
\(p::Coord ECR D) t -> radius (s $ ecrToECI t p) ~== radius (s p)
-- ----------------------------------------------------------
spec_eciToECR = describe "eciToECR" $ do
it "is the inverse of ecrToECI" $ property $
\(p::Coord ECI D) t -> (ecrToECI t . eciToECR t) p ~== p
-- ----------------------------------------------------------
spec_ecrToECIPV = describe "ecrToECIPV" $ do
it "is identical to ecrToECI for the position" $ property $
--Comparison of cartesian coords fails due to numerics.
\(pv::PosVel ECR D) t -> (s . pos . ecrToECIPV t) pv ~== (s . ecrToECI t . pos) pv
it "is the inverse of eciToECRPV" $ property $
\(pv::PosVel ECR D) t -> (eciToECRPV t . ecrToECIPV t) pv ~== pv
-- ----------------------------------------------------------
spec_eciToECRPV = describe "eciToECRPV" $ do
it "is identical to eciToECR for the position" $ property $
--Comparison of cartesian coords fails due to numerics.
\(pv::PosVel ECI D) t -> (s . pos . eciToECRPV t) pv ~== (s . eciToECR t . pos) pv
it "is the inverse of ecrToECIPV" $ property $
\(pv::PosVel ECI D) t -> (ecrToECIPV t . eciToECRPV t) pv ~== pv
-- {-
p = (-0.5653349232735853::D) *~ meter <: (-5.133004275272132) *~meter <:. (-7.22445929855348) *~ meter
t = clock' 1858 11 24 20 10 15.151878680541
pv = C' p (_0 <: _0 <:. _0)
-- -}
| bjornbm/astro | test/Astro/Coords/ECRSpec.hs | bsd-3-clause | 2,578 | 0 | 16 | 467 | 817 | 419 | 398 | 50 | 1 |
module TiState where
import Debug.Trace
import Language
import PrettyPrint
import Parser
import TiTypes
--import GCMarkScan
import GCTwoSpace
import Utils
extraPreludeDefns :: CoreProgram
extraPreludeDefns
= [ ("False", [], EConstr 1 0)
, ("True", [], EConstr 2 0)
, ("and", ["x", "y"], EAp (EAp (EAp (EVar "if") (EVar "x")) (EVar "y")) (EVar "False"))
, ("or", ["x", "y"], EAp (EAp (EAp (EVar "if") (EVar "x")) (EVar "True")) (EVar "y"))
, ("MkPair", ["a", "b"], EAp (EAp (EConstr 1 2) (EVar "a")) (EVar "b"))
, ("fst", ["p"], EAp (EAp (EVar "casePair") (EVar "p")) (EVar "K"))
, ("snd", ["p"], EAp (EAp (EVar "casePair") (EVar "p")) (EVar "K1"))
, ("Nil", [], EConstr 1 0)
, ("Cons", ["x", "xs"], EAp (EAp (EConstr 2 2) (EVar "x")) (EVar "xs"))
-- head xs = caseList xs abort K
, ("head", ["xs"], EAp (EAp (EAp (EVar "caseList") (EVar "xs")) (EVar "abort")) (EVar "K"))
-- tail xs = caseList xs abort K1
, ("tail", ["xs"], EAp (EAp (EAp (EVar "caseList") (EVar "xs")) (EVar "abort")) (EVar "K1"))
, ("printList", ["xs"], EAp (EAp (EAp (EVar "caseList") (EVar "xs")) (EVar "stop")) (EVar "printCons"))
, ("printCons", ["h", "t"], EAp (EAp (EVar "print") (EVar "h")) (EAp (EVar "printList") (EVar "t")))
, ("__main", [], EAp (EVar "printList") (EVar "main"))
]
tiStatInitial :: TiStats
tiStatInitial = (0, 0, 0, 0, 0)
tiStatIncSteps :: TiStats -> TiStats
tiStatIncSteps (s, sr, pr, h, d) = (s + 1, sr, pr, h, d)
tiStatIncSReductions :: TiStats -> TiStats
tiStatIncSReductions (s, sr, pr, h, d) = (s, sr + 1, pr, h, d)
tiStatIncPReductions :: TiStats -> TiStats
tiStatIncPReductions (s, sr, pr, h, d) = (s, sr, pr + 1, h, d)
tiStatIncHeap :: Int -> TiStats -> TiStats
tiStatIncHeap n (s, sr, pr, h, d) = (s, sr, pr, h + n, d)
tiStatSetMaxDepth :: Int -> TiStats -> TiStats
tiStatSetMaxDepth n stat@(s, sr, pr, h, d)
= if n > d
then (s, sr, pr, h, n)
else stat
tiStatGetSteps :: TiStats -> Int
tiStatGetSteps (s, sr, pr, h, d) = s
tiStatGetSReductions :: TiStats -> Int
tiStatGetSReductions (s, sr, pr, h, d) = sr
tiStatGetPReductions :: TiStats -> Int
tiStatGetPReductions (s, sr, pr, h, d) = pr
tiStatGetHeap :: TiStats -> Int
tiStatGetHeap (s, sr, pr, h, d) = h
tiStatGetDepth :: TiStats -> Int
tiStatGetDepth (s, sr, pr, h, d) = d
applyToStats :: (TiStats -> TiStats) -> TiState -> TiState
applyToStats stats_fn (output, stack, dump, heap, sc_defs, stats)
= (output, stack, dump, heap, sc_defs, stats_fn stats)
runProg :: String -> String
runProg = showResults . eval . compile . parse
compile :: CoreProgram -> TiState
compile program
= ([], initial_stack, initialTiDump, initial_heap, globals, tiStatInitial)
where
sc_defs = program ++ preludeDefns ++ extraPreludeDefns
(initial_heap, globals) = buildInitialHeap sc_defs
initial_stack = [address_of_main]
address_of_main = aLookup globals "__main" (error "the impossible happened")
buildInitialHeap :: CoreProgram -> (TiHeap, TiGlobals)
buildInitialHeap sc_defs
= (heap2, sc_addrs ++ prim_addrs)
where
(heap1, sc_addrs) = mapAccuml allocateSc hInitial sc_defs
(heap2, prim_addrs) = mapAccuml allocatePrim heap1 primitives
allocateSc :: TiHeap -> CoreScDefn -> (TiHeap, (Name, Addr))
allocateSc heap (name, args, body)
= (heap', (name, addr))
where
(heap', addr) = hAlloc heap (NSupercomb name args body)
primitives :: ASSOC Name Primitive
primitives = [ ("negate", Neg)
, ("+", Add), ("-", Sub)
, ("*", Mul), ("/", Div)
, ("if", If)
, (">", Greater)
, (">=", GreaterEq)
, ("<", Less)
, ("<=", LessEq)
, ("==", Eq)
, ("~=", NotEq)
, ("casePair", PrimCasePair)
, ("caseList", PrimCaseList)
, ("abort", Abort)
, ("print", Print)
, ("stop", Stop)
]
allocatePrim :: TiHeap -> (Name, Primitive) -> (TiHeap, (Name, Addr))
allocatePrim heap (name, prim)
= (heap', (name, addr))
where
(heap', addr) = hAlloc heap (NPrim name prim)
eval :: TiState -> [TiState]
eval state = state : rest_states
where
rest_states
| tiFinal state = [] -- # so I can put a `#` in front of my guard?
| otherwise = eval next_states
next_states = doAdmin (step state)
doAdmin :: TiState -> TiState
doAdmin state@(output, stack, dump, heap, globals, stats)
= state'''
where
state''' = if (hSize heap > 50) then (gc state'') else state''
state'' = applyToStats (tiStatSetMaxDepth (length stack)) state'
state'@(output, stack, dump, heap, glabals, stats) = applyToStats tiStatIncSteps state
tiFinal :: TiState -> Bool
tiFinal (output, [sole_addr], [], heap, globals, stats) = isDataNode (hLookup heap sole_addr)
tiFinal (output, [], [], heap, globals, stats) = True
tiFinal state = False
isDataNode :: Node -> Bool
isDataNode (NNum n) = True
isDataNode (NData tag addrs) = True
isDataNode node = False
step :: TiState -> TiState
step state
= dispatch (hLookup heap (hd stack))
where
(output, stack, dump, heap, globals, stats) = state
dispatch (NNum n) = numStep state n
dispatch (NAp a1 a2) = apStep state a1 a2
dispatch (NSupercomb sc args body) = scStep state sc args body
dispatch (NInd addr) = scInd state addr
dispatch (NPrim name prim) = primStep state prim
dispatch (NData tag addrs) = dataStep state tag addrs
numStep :: TiState -> Int -> TiState
numStep (output, stack, dump, heap, globals, stats) n
= if length dump /= 0
then (output, hd dump, tl dump, heap, globals, stats)
else error "Number applied as a function!"
-- # tumbling down to the spine
apStep :: TiState -> Addr -> Addr -> TiState
apStep (output, stack, dump, heap, globals, stats) a1 a2
= case node of
(NInd a3) -> (output, stack, dump, new_heap, globals, stats)
where
new_heap = hUpdate heap (hd stack) (NAp a1 a3)
otherwise -> (output, a1 : stack, dump, heap, globals, stats)
where
node = hLookup heap a2
scStep :: TiState -> Name -> [Name] -> CoreExpr -> TiState
scStep (output, stack, dump, heap, globals, stats) sc_name arg_names body
= if (length arg_bindings) == (length arg_names)
then (output, new_stack, dump, new_heap, globals, new_stats')
else error "Insufficient arguments"
where
new_stats' = tiStatIncHeap (hSize new_heap - hSize heap) new_stats
new_stats = tiStatIncSReductions stats
new_stack = root_addr : ss
new_heap = instantiateAndUpdate body root_addr heap env
(root_addr:ss) = drop (length arg_names) stack
env = arg_bindings ++ globals
arg_bindings = zip2 arg_names (getargs heap stack)
scInd :: TiState -> Addr -> TiState
scInd (output, stack, dump, heap, globals, stats) addr
= (output, new_stack, dump, heap, globals, stats)
where
new_stack = addr : (tl stack)
primStep :: TiState -> Primitive -> TiState
primStep state Neg = primNeg state
-- for data constructors
primStep state If = primIf state
primStep state PrimCasePair = primCasePair state
primStep state PrimCaseList = primCaseList state
primStep state (PrimConstr tag arity) = primConstr state tag arity
primStep state Abort = primAbort state
primStep state Print = primPrint state
primStep state Stop = primStop state
primStep state Add = primDyadic state $ primArith (+)
primStep state Sub = primDyadic state $ primArith (-)
primStep state Mul = primDyadic state $ primArith (*)
primStep state Div = primDyadic state $ primArith (div)
primStep state Greater = primDyadic state $ primComp (>)
primStep state GreaterEq = primDyadic state $ primComp (>=)
primStep state Less = primDyadic state $ primComp (<)
primStep state LessEq = primDyadic state $ primComp (<=)
primStep state Eq = primDyadic state $ primComp (==)
primStep state NotEq = primDyadic state $ primComp (/=)
dataStep :: TiState -> Int -> [Addr] -> TiState
dataStep (output, stack, dump, heap, globals, stats) tag addrs
= if length dump /= 0
then (output, hd dump, tl dump, heap, globals, stats)
else error "data constructor applied as a function!"
primNeg :: TiState -> TiState
primNeg (output, stack@(_:ss), dump, heap, globals, stats)
= case (isDataNode node) of
-- the result may be a indirection, so we have to step back instead of
-- passing the whole stack
False -> (output, [addr], ss:dump, heap, globals, stats)
True -> (output, ss, dump, new_heap, globals, stats)
where
new_heap = hUpdate heap root_addr (NNum (negate n))
root_addr = hd ss
(NNum n) = node
where
node = hLookup heap addr
[addr] = getargs heap stack
primIf :: TiState -> TiState
primIf (output, stack@(_:_:_:ss), dump, heap, globals, stats)
= case (isDataNode node1) of
False -> (output, [addr1], ss:dump, heap, globals, stats)
True -> (output, ss, dump, new_heap, globals, stats)
where
new_heap = case tag == 2 of
True -> hUpdate heap root_addr (NInd addr2)
False -> hUpdate heap root_addr (NInd addr3)
root_addr = hd ss
(NData tag addrs) = node1
where
node3 = hLookup heap addr3
node2 = hLookup heap addr2
node1 = hLookup heap addr1
[addr1, addr2, addr3] = getargs heap stack
primConstr :: TiState -> Int -> Int -> TiState
primConstr (output, stack, dump, heap, globals, stats) tag arity
= (output, new_stack, dump, new_heap, globals, stats)
where
new_heap = hUpdate heap addr (NData tag (take arity addrs))
new_stack@(addr:_) = drop arity stack
addrs = getargs heap stack
primCasePair :: TiState -> TiState
primCasePair (output, stack@(_:s:ss), dump, heap, globals, stats)
= case (isDataNode node1) of
False -> (output, [addr1], (s:ss):dump, heap, globals, stats)
True -> (output, ss, dump, new_heap', globals, stats)
where
new_heap' = hUpdate new_heap root_addr (NInd addr)
root_addr = hd ss
(new_heap, addr) = nodeApply (heap, addr2) addrs
(NData tag addrs) = node1
where
node1 = hLookup heap addr1
[addr1, addr2] = getargs heap stack
nodeApply :: (TiHeap, Addr) -> [Addr] -> (TiHeap, Addr)
nodeApply (heap, f) [] = (heap, f)
nodeApply (heap, f) (a:as) = nodeApply (hAlloc heap (NAp f a)) as
primCaseList :: TiState -> TiState
primCaseList (output, stack@(_:s1:s2:ss), dump, heap, globals, stats)
= case (isDataNode node1) of
False -> (output, [addr1], (s1:s2:ss):dump, heap, globals, stats)
True -> case tag of
-- Nil
1 -> (output, ss, dump, new_heap, globals, stats)
where
new_heap = hUpdate heap root_addr (NInd addr2)
-- Cons x xs
2 -> (output, ss, dump, new_heap', globals, stats)
where
new_heap' = hUpdate new_heap root_addr (NInd addr)
-- addr3 should point to a supercombinator for now :(
(new_heap, addr) = nodeApply (heap, addr3) addrs
where
root_addr = hd ss
(NData tag addrs) = node1
where
node1 = hLookup heap addr1
[addr1, addr2, addr3] = getargs heap stack
primDyadic :: TiState -> (Node -> Node -> Node) -> TiState
primDyadic (output, stack@(_:s:ss), dump, heap, globals, stats) comp
= case (isDataNode node1) of
False -> (output, [addr1], (s:ss):dump, heap, globals, stats)
True -> case (isDataNode node2) of
False -> (output, [addr2], ss:dump, heap, globals, stats)
True -> (output, ss, dump, new_heap, globals, stats)
where
new_heap = hUpdate heap root_addr (comp node1 node2)
root_addr = hd ss
where
node2 = hLookup heap addr2
node1 = hLookup heap addr1
[addr1, addr2] = getargs heap stack
primArith :: (Int -> Int -> Int) -> Node -> Node -> Node
primArith f (NNum a) (NNum b) = (NNum (f a b))
primArith _ _ _ = error "A non-numerical data is compared to another node."
primComp :: (Int -> Int -> Bool) -> Node -> Node -> Node
primComp comp (NNum a) (NNum b) = boolToNData (comp a b)
primComp comp (NData a _) (NData b _) = boolToNData (comp a b) -- buggy
primComp comp (NNum _) (NData _ _) = error "A number is compared to a data constructor."
primComp comp (NData _ _) (NNum _) = error "A data constructor is compared to a number."
primComp _ _ _ = error "A non-data node is compared to another node."
boolToNData :: Bool -> Node
boolToNData True = NData 2 []
boolToNData False = NData 1 []
primAbort :: TiState -> TiState
primAbort (output, stack, dump, heap, globals, stats)
= error "Abort!"
primPrint :: TiState -> TiState
primPrint (output, stack@(_:s:ss), dump, heap, globals, stats)
= case (isDataNode node1) of
False -> (output, [addr1], (s:ss):dump, heap, globals, stats)
True -> (output ++ [n], [addr2], dump, heap, globals, stats)
where
root_addr = hd ss
(NNum n) = node1
where
node1 = hLookup heap addr1
[addr1, addr2] = getargs heap stack
primStop :: TiState -> TiState
primStop (output, _, [], heap, globals, stats) = (output, [], [], heap, globals, stats)
primStop (output, _, dump, heap, globals, stats) = (output, hd dump, tl dump, heap, globals, stats)
getargs :: TiHeap -> TiStack -> [Addr]
getargs heap (sc : stack)
= map get_arg stack
-- # take the right branch as the argument
where get_arg addr = arg where (NAp fun arg) = hLookup heap addr
instantiate :: CoreExpr -> TiHeap -> ASSOC Name Addr -> (TiHeap, Addr)
instantiate (ENum n) heap env = hAlloc heap (NNum n)
instantiate (EAp e1 e2) heap env
= hAlloc heap2 (NAp a1 a2)
where
(heap1, a1) = instantiate e1 heap env
(heap2, a2) = instantiate e2 heap1 env
instantiate (EVar v) heap env
= (heap, aLookup env v (error ("Undefined name " ++ show v)))
instantiate (EConstr tag arity) heap env
= instantiateConstr tag arity heap env
instantiate (ELet isrec defs body) heap env
= instantiateLet isrec defs body heap env
instantiate (ECase e alts) heap env = error "Can't instantiate case exprs"
instantiateConstr tag arity heap env
= hAlloc heap (NPrim ("Pack{" ++ show tag ++ "," ++ show arity ++ "}") (PrimConstr tag arity))
instantiateLet isrec defs body heap env
= instantiate body new_heap new_env
where
(new_heap, addrs) = mapAccuml (instantiateDefs isrec) heap exprs
new_env = (zip2 names addrs) ++ env
instantiateDefs True heap expr = instantiate expr heap new_env
instantiateDefs False heap expr = instantiate expr heap env
exprs = aRange defs
names = aDomain defs
instantiateAndUpdate :: CoreExpr -> Addr -> TiHeap -> ASSOC Name Addr -> TiHeap
instantiateAndUpdate (ENum n) upd_addr heap env
= hUpdate heap upd_addr (NNum n)
instantiateAndUpdate (EAp e1 e2) upd_addr heap env
= hUpdate heap2 upd_addr (NAp a1 a2)
where
(heap1, a1) = instantiate e1 heap env
(heap2, a2) = instantiate e2 heap1 env
instantiateAndUpdate (EVar v) upd_addr heap env
= hUpdate heap upd_addr (NInd addr)
where
addr = aLookup env v (error ("Undefined name " ++ show v))
instantiateAndUpdate (EConstr tag arity) upd_addr heap env
= hUpdate heap upd_addr (NPrim ("Pack{" ++ show tag ++ "," ++ show arity ++ "}") (PrimConstr tag arity))
instantiateAndUpdate (ELet isrec defs body) upd_addr heap env
= hUpdate new_heap' upd_addr (NInd addr)
where
(new_heap', addr) = instantiate body new_heap new_env
(new_heap, addrs) = mapAccuml (instantiateDefs isrec) heap exprs
new_env = (zip2 names addrs) ++ env
instantiateDefs True heap expr = instantiate expr heap new_env
instantiateDefs False heap expr = instantiate expr heap env
exprs = aRange defs
names = aDomain defs
instantiateAndUpdate (ECase e alts) upd_addr heap env
= error "Can't instantiate case exprs"
showResults :: [TiState] -> String
showResults states
= iDisplay (iConcat [ iLayn (map showState states), showStats state, showOutput state ])
where
state@(output, stack, dump, heap, globals, stats) = last states
showState :: TiState -> Iseq
showState (output, stack, dump, heap, globals, stats)
= iConcat [ showStack heap stack, iNewline, showHeap heap, iNewline ]
showStack :: TiHeap -> TiStack -> Iseq
showStack heap stack
= iConcat
[ iStr "Stk ["
, iIndent (iInterleave iNewline (map show_stack_item stack))
, iStr " ]"
]
where
show_stack_item addr
= iConcat
[ showFWAddr addr
, iStr ": "
, showStkNode heap (hLookup heap addr)
]
showStkNode :: TiHeap -> Node -> Iseq
showStkNode heap (NAp fun_addr arg_addr)
= iConcat
[ iStr "NAp "
, showFWAddr fun_addr
, iStr " "
, showFWAddr arg_addr
, iStr " ("
, showNode (hLookup heap arg_addr)
, iStr ")"
]
showStkNode heap node = showNode node
showNode :: Node -> Iseq
showNode (NAp a1 a2)
= iConcat
[ iStr "NAp "
, showAddr a1
, iStr " "
, showAddr a2
]
showNode (NSupercomb name args body) = iStr ("NSupercomb " ++ name)
showNode (NNum n) = (iStr "NNum ") `iAppend` (iNum n)
showNode (NInd addr) = (iStr "NInd ") `iAppend` (iStr $ show addr)
showNode (NPrim name prim) = iStr ("NPrim " ++ name)
showNode (NData tag addrs)
= iConcat
[ iStr "Pack{"
, iStr $ show tag
, iStr ","
, iStr $ show (length addrs)
, iStr "}"
]
showAddr :: Addr -> Iseq
showAddr addr = iStr (show addr)
showFWAddr :: Addr -> Iseq -- Show address in field of width 4
showFWAddr addr
= iStr (spaces (4 - length str) ++ str)
where
str = show addr
showStats :: TiState -> Iseq
showStats (output, stack, dump, heap, globals, stats)
= iConcat
[ iNewline
, iNewline
, iStr "Total number of steps = "
, iNum (tiStatGetSteps stats)
, iNewline
, iStr "Total number of supercombinator reductions = "
, iNum (tiStatGetSReductions stats)
, iNewline
, iStr "Total number of primitive reductions = "
, iNum (tiStatGetPReductions stats)
, iNewline
, iStr "New heaps allocated = "
, iNum (tiStatGetHeap stats)
, iNewline
, iStr "Max stack depth = "
, iNum (tiStatGetDepth stats)
, iNewline
]
showHeap :: TiHeap -> Iseq
showHeap (size, free, cts) = showASSOC cts
showASSOC :: ASSOC Addr Node -> Iseq
showASSOC pairs
= iConcat
[ iStr "Heap ["
, iIndent (iInterleave iNewline (map showAddrNode pairs))
, iStr " ]"
]
showAddrNode :: (Addr, Node) -> Iseq
showAddrNode (addr, node)
= iConcat
[ showFWAddr addr
, iStr ": "
, showNode node
]
showOutput :: TiState -> Iseq
showOutput (output, stack, dump, heap, globals, stats)
= iConcat
[ iStr "Output ["
, iInterleave (iStr ", ") $ map (iStr . show) output
, iStr "]"
, iNewline
]
| caasi/spj-book-student-1992 | src/TiState.hs | bsd-3-clause | 19,509 | 0 | 15 | 5,161 | 7,250 | 3,942 | 3,308 | 413 | 6 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Eclogues.APISpec (spec) where
import Eclogues.API (Action (..))
import Eclogues.Job (mkBoxSpec)
import TestUtils (forceName)
import Data.Aeson (encode)
import Data.String.QQ (s)
import Test.Hspec
spec :: Spec
spec = describe "Action" $
it "encodes to the expected JSON" $ do
let job = forceName "job"
encode (ActCreateBox $ mkBoxSpec job) `shouldBe` [s|{"action":"CreateBox","spec":{"id":"job"}}|]
encode (ActDeleteBox job) `shouldBe` [s|{"action":"DeleteBox","id":"job"}|]
| rimmington/eclogues | eclogues-impl/test/Eclogues/APISpec.hs | bsd-3-clause | 578 | 0 | 12 | 96 | 155 | 90 | 65 | 15 | 1 |
-- |
-- TH.Lib contains lots of useful helper functions for
-- generating and manipulating Template Haskell terms
{-# LANGUAGE CPP #-}
module Language.Haskell.TH.Lib where
-- All of the exports from this module should
-- be "public" functions. The main module TH
-- re-exports them all.
import Language.Haskell.TH.Syntax hiding (Role, InjectivityAnn)
import qualified Language.Haskell.TH.Syntax as TH
import Control.Monad( liftM, liftM2 )
import Data.Word( Word8 )
----------------------------------------------------------
-- * Type synonyms
----------------------------------------------------------
type InfoQ = Q Info
type PatQ = Q Pat
type FieldPatQ = Q FieldPat
type ExpQ = Q Exp
type TExpQ a = Q (TExp a)
type DecQ = Q Dec
type DecsQ = Q [Dec]
type ConQ = Q Con
type TypeQ = Q Type
type TyLitQ = Q TyLit
type CxtQ = Q Cxt
type PredQ = Q Pred
type MatchQ = Q Match
type ClauseQ = Q Clause
type BodyQ = Q Body
type GuardQ = Q Guard
type StmtQ = Q Stmt
type RangeQ = Q Range
type SourceStrictnessQ = Q SourceStrictness
type SourceUnpackednessQ = Q SourceUnpackedness
type BangQ = Q Bang
type BangTypeQ = Q BangType
type VarBangTypeQ = Q VarBangType
type StrictTypeQ = Q StrictType
type VarStrictTypeQ = Q VarStrictType
type FieldExpQ = Q FieldExp
type RuleBndrQ = Q RuleBndr
type TySynEqnQ = Q TySynEqn
-- must be defined here for DsMeta to find it
type Role = TH.Role
type InjectivityAnn = TH.InjectivityAnn
----------------------------------------------------------
-- * Lowercase pattern syntax functions
----------------------------------------------------------
intPrimL :: Integer -> Lit
intPrimL = IntPrimL
wordPrimL :: Integer -> Lit
wordPrimL = WordPrimL
floatPrimL :: Rational -> Lit
floatPrimL = FloatPrimL
doublePrimL :: Rational -> Lit
doublePrimL = DoublePrimL
integerL :: Integer -> Lit
integerL = IntegerL
charL :: Char -> Lit
charL = CharL
charPrimL :: Char -> Lit
charPrimL = CharPrimL
stringL :: String -> Lit
stringL = StringL
stringPrimL :: [Word8] -> Lit
stringPrimL = StringPrimL
rationalL :: Rational -> Lit
rationalL = RationalL
litP :: Lit -> PatQ
litP l = return (LitP l)
varP :: Name -> PatQ
varP v = return (VarP v)
tupP :: [PatQ] -> PatQ
tupP ps = do { ps1 <- sequence ps; return (TupP ps1)}
unboxedTupP :: [PatQ] -> PatQ
unboxedTupP ps = do { ps1 <- sequence ps; return (UnboxedTupP ps1)}
conP :: Name -> [PatQ] -> PatQ
conP n ps = do ps' <- sequence ps
return (ConP n ps')
infixP :: PatQ -> Name -> PatQ -> PatQ
infixP p1 n p2 = do p1' <- p1
p2' <- p2
return (InfixP p1' n p2')
uInfixP :: PatQ -> Name -> PatQ -> PatQ
uInfixP p1 n p2 = do p1' <- p1
p2' <- p2
return (UInfixP p1' n p2')
parensP :: PatQ -> PatQ
parensP p = do p' <- p
return (ParensP p')
tildeP :: PatQ -> PatQ
tildeP p = do p' <- p
return (TildeP p')
bangP :: PatQ -> PatQ
bangP p = do p' <- p
return (BangP p')
asP :: Name -> PatQ -> PatQ
asP n p = do p' <- p
return (AsP n p')
wildP :: PatQ
wildP = return WildP
recP :: Name -> [FieldPatQ] -> PatQ
recP n fps = do fps' <- sequence fps
return (RecP n fps')
listP :: [PatQ] -> PatQ
listP ps = do ps' <- sequence ps
return (ListP ps')
sigP :: PatQ -> TypeQ -> PatQ
sigP p t = do p' <- p
t' <- t
return (SigP p' t')
viewP :: ExpQ -> PatQ -> PatQ
viewP e p = do e' <- e
p' <- p
return (ViewP e' p')
fieldPat :: Name -> PatQ -> FieldPatQ
fieldPat n p = do p' <- p
return (n, p')
-------------------------------------------------------------------------------
-- * Stmt
bindS :: PatQ -> ExpQ -> StmtQ
bindS p e = liftM2 BindS p e
letS :: [DecQ] -> StmtQ
letS ds = do { ds1 <- sequence ds; return (LetS ds1) }
noBindS :: ExpQ -> StmtQ
noBindS e = do { e1 <- e; return (NoBindS e1) }
parS :: [[StmtQ]] -> StmtQ
parS sss = do { sss1 <- mapM sequence sss; return (ParS sss1) }
-------------------------------------------------------------------------------
-- * Range
fromR :: ExpQ -> RangeQ
fromR x = do { a <- x; return (FromR a) }
fromThenR :: ExpQ -> ExpQ -> RangeQ
fromThenR x y = do { a <- x; b <- y; return (FromThenR a b) }
fromToR :: ExpQ -> ExpQ -> RangeQ
fromToR x y = do { a <- x; b <- y; return (FromToR a b) }
fromThenToR :: ExpQ -> ExpQ -> ExpQ -> RangeQ
fromThenToR x y z = do { a <- x; b <- y; c <- z;
return (FromThenToR a b c) }
-------------------------------------------------------------------------------
-- * Body
normalB :: ExpQ -> BodyQ
normalB e = do { e1 <- e; return (NormalB e1) }
guardedB :: [Q (Guard,Exp)] -> BodyQ
guardedB ges = do { ges' <- sequence ges; return (GuardedB ges') }
-------------------------------------------------------------------------------
-- * Guard
normalG :: ExpQ -> GuardQ
normalG e = do { e1 <- e; return (NormalG e1) }
normalGE :: ExpQ -> ExpQ -> Q (Guard, Exp)
normalGE g e = do { g1 <- g; e1 <- e; return (NormalG g1, e1) }
patG :: [StmtQ] -> GuardQ
patG ss = do { ss' <- sequence ss; return (PatG ss') }
patGE :: [StmtQ] -> ExpQ -> Q (Guard, Exp)
patGE ss e = do { ss' <- sequence ss;
e' <- e;
return (PatG ss', e') }
-------------------------------------------------------------------------------
-- * Match and Clause
-- | Use with 'caseE'
match :: PatQ -> BodyQ -> [DecQ] -> MatchQ
match p rhs ds = do { p' <- p;
r' <- rhs;
ds' <- sequence ds;
return (Match p' r' ds') }
-- | Use with 'funD'
clause :: [PatQ] -> BodyQ -> [DecQ] -> ClauseQ
clause ps r ds = do { ps' <- sequence ps;
r' <- r;
ds' <- sequence ds;
return (Clause ps' r' ds') }
---------------------------------------------------------------------------
-- * Exp
-- | Dynamically binding a variable (unhygenic)
dyn :: String -> ExpQ
dyn s = return (VarE (mkName s))
varE :: Name -> ExpQ
varE s = return (VarE s)
conE :: Name -> ExpQ
conE s = return (ConE s)
litE :: Lit -> ExpQ
litE c = return (LitE c)
appE :: ExpQ -> ExpQ -> ExpQ
appE x y = do { a <- x; b <- y; return (AppE a b)}
parensE :: ExpQ -> ExpQ
parensE x = do { x' <- x; return (ParensE x') }
uInfixE :: ExpQ -> ExpQ -> ExpQ -> ExpQ
uInfixE x s y = do { x' <- x; s' <- s; y' <- y;
return (UInfixE x' s' y') }
infixE :: Maybe ExpQ -> ExpQ -> Maybe ExpQ -> ExpQ
infixE (Just x) s (Just y) = do { a <- x; s' <- s; b <- y;
return (InfixE (Just a) s' (Just b))}
infixE Nothing s (Just y) = do { s' <- s; b <- y;
return (InfixE Nothing s' (Just b))}
infixE (Just x) s Nothing = do { a <- x; s' <- s;
return (InfixE (Just a) s' Nothing)}
infixE Nothing s Nothing = do { s' <- s; return (InfixE Nothing s' Nothing) }
infixApp :: ExpQ -> ExpQ -> ExpQ -> ExpQ
infixApp x y z = infixE (Just x) y (Just z)
sectionL :: ExpQ -> ExpQ -> ExpQ
sectionL x y = infixE (Just x) y Nothing
sectionR :: ExpQ -> ExpQ -> ExpQ
sectionR x y = infixE Nothing x (Just y)
lamE :: [PatQ] -> ExpQ -> ExpQ
lamE ps e = do ps' <- sequence ps
e' <- e
return (LamE ps' e')
-- | Single-arg lambda
lam1E :: PatQ -> ExpQ -> ExpQ
lam1E p e = lamE [p] e
lamCaseE :: [MatchQ] -> ExpQ
lamCaseE ms = sequence ms >>= return . LamCaseE
tupE :: [ExpQ] -> ExpQ
tupE es = do { es1 <- sequence es; return (TupE es1)}
unboxedTupE :: [ExpQ] -> ExpQ
unboxedTupE es = do { es1 <- sequence es; return (UnboxedTupE es1)}
condE :: ExpQ -> ExpQ -> ExpQ -> ExpQ
condE x y z = do { a <- x; b <- y; c <- z; return (CondE a b c)}
multiIfE :: [Q (Guard, Exp)] -> ExpQ
multiIfE alts = sequence alts >>= return . MultiIfE
letE :: [DecQ] -> ExpQ -> ExpQ
letE ds e = do { ds2 <- sequence ds; e2 <- e; return (LetE ds2 e2) }
caseE :: ExpQ -> [MatchQ] -> ExpQ
caseE e ms = do { e1 <- e; ms1 <- sequence ms; return (CaseE e1 ms1) }
doE :: [StmtQ] -> ExpQ
doE ss = do { ss1 <- sequence ss; return (DoE ss1) }
compE :: [StmtQ] -> ExpQ
compE ss = do { ss1 <- sequence ss; return (CompE ss1) }
arithSeqE :: RangeQ -> ExpQ
arithSeqE r = do { r' <- r; return (ArithSeqE r') }
listE :: [ExpQ] -> ExpQ
listE es = do { es1 <- sequence es; return (ListE es1) }
sigE :: ExpQ -> TypeQ -> ExpQ
sigE e t = do { e1 <- e; t1 <- t; return (SigE e1 t1) }
recConE :: Name -> [Q (Name,Exp)] -> ExpQ
recConE c fs = do { flds <- sequence fs; return (RecConE c flds) }
recUpdE :: ExpQ -> [Q (Name,Exp)] -> ExpQ
recUpdE e fs = do { e1 <- e; flds <- sequence fs; return (RecUpdE e1 flds) }
stringE :: String -> ExpQ
stringE = litE . stringL
fieldExp :: Name -> ExpQ -> Q (Name, Exp)
fieldExp s e = do { e' <- e; return (s,e') }
-- | @staticE x = [| static x |]@
staticE :: ExpQ -> ExpQ
staticE = fmap StaticE
unboundVarE :: Name -> ExpQ
unboundVarE s = return (UnboundVarE s)
-- ** 'arithSeqE' Shortcuts
fromE :: ExpQ -> ExpQ
fromE x = do { a <- x; return (ArithSeqE (FromR a)) }
fromThenE :: ExpQ -> ExpQ -> ExpQ
fromThenE x y = do { a <- x; b <- y; return (ArithSeqE (FromThenR a b)) }
fromToE :: ExpQ -> ExpQ -> ExpQ
fromToE x y = do { a <- x; b <- y; return (ArithSeqE (FromToR a b)) }
fromThenToE :: ExpQ -> ExpQ -> ExpQ -> ExpQ
fromThenToE x y z = do { a <- x; b <- y; c <- z;
return (ArithSeqE (FromThenToR a b c)) }
-------------------------------------------------------------------------------
-- * Dec
valD :: PatQ -> BodyQ -> [DecQ] -> DecQ
valD p b ds =
do { p' <- p
; ds' <- sequence ds
; b' <- b
; return (ValD p' b' ds')
}
funD :: Name -> [ClauseQ] -> DecQ
funD nm cs =
do { cs1 <- sequence cs
; return (FunD nm cs1)
}
tySynD :: Name -> [TyVarBndr] -> TypeQ -> DecQ
tySynD tc tvs rhs = do { rhs1 <- rhs; return (TySynD tc tvs rhs1) }
dataD :: CxtQ -> Name -> [TyVarBndr] -> Maybe Kind -> [ConQ] -> CxtQ -> DecQ
dataD ctxt tc tvs ksig cons derivs =
do
ctxt1 <- ctxt
cons1 <- sequence cons
derivs1 <- derivs
return (DataD ctxt1 tc tvs ksig cons1 derivs1)
newtypeD :: CxtQ -> Name -> [TyVarBndr] -> Maybe Kind -> ConQ -> CxtQ -> DecQ
newtypeD ctxt tc tvs ksig con derivs =
do
ctxt1 <- ctxt
con1 <- con
derivs1 <- derivs
return (NewtypeD ctxt1 tc tvs ksig con1 derivs1)
classD :: CxtQ -> Name -> [TyVarBndr] -> [FunDep] -> [DecQ] -> DecQ
classD ctxt cls tvs fds decs =
do
decs1 <- sequence decs
ctxt1 <- ctxt
return $ ClassD ctxt1 cls tvs fds decs1
instanceD :: CxtQ -> TypeQ -> [DecQ] -> DecQ
instanceD = instanceWithOverlapD Nothing
instanceWithOverlapD :: Maybe Overlap -> CxtQ -> TypeQ -> [DecQ] -> DecQ
instanceWithOverlapD o ctxt ty decs =
do
ctxt1 <- ctxt
decs1 <- sequence decs
ty1 <- ty
return $ InstanceD o ctxt1 ty1 decs1
sigD :: Name -> TypeQ -> DecQ
sigD fun ty = liftM (SigD fun) $ ty
forImpD :: Callconv -> Safety -> String -> Name -> TypeQ -> DecQ
forImpD cc s str n ty
= do ty' <- ty
return $ ForeignD (ImportF cc s str n ty')
infixLD :: Int -> Name -> DecQ
infixLD prec nm = return (InfixD (Fixity prec InfixL) nm)
infixRD :: Int -> Name -> DecQ
infixRD prec nm = return (InfixD (Fixity prec InfixR) nm)
infixND :: Int -> Name -> DecQ
infixND prec nm = return (InfixD (Fixity prec InfixN) nm)
pragInlD :: Name -> Inline -> RuleMatch -> Phases -> DecQ
pragInlD name inline rm phases
= return $ PragmaD $ InlineP name inline rm phases
pragSpecD :: Name -> TypeQ -> Phases -> DecQ
pragSpecD n ty phases
= do
ty1 <- ty
return $ PragmaD $ SpecialiseP n ty1 Nothing phases
pragSpecInlD :: Name -> TypeQ -> Inline -> Phases -> DecQ
pragSpecInlD n ty inline phases
= do
ty1 <- ty
return $ PragmaD $ SpecialiseP n ty1 (Just inline) phases
pragSpecInstD :: TypeQ -> DecQ
pragSpecInstD ty
= do
ty1 <- ty
return $ PragmaD $ SpecialiseInstP ty1
pragRuleD :: String -> [RuleBndrQ] -> ExpQ -> ExpQ -> Phases -> DecQ
pragRuleD n bndrs lhs rhs phases
= do
bndrs1 <- sequence bndrs
lhs1 <- lhs
rhs1 <- rhs
return $ PragmaD $ RuleP n bndrs1 lhs1 rhs1 phases
pragAnnD :: AnnTarget -> ExpQ -> DecQ
pragAnnD target expr
= do
exp1 <- expr
return $ PragmaD $ AnnP target exp1
pragLineD :: Int -> String -> DecQ
pragLineD line file = return $ PragmaD $ LineP line file
dataInstD :: CxtQ -> Name -> [TypeQ] -> Maybe Kind -> [ConQ] -> CxtQ -> DecQ
dataInstD ctxt tc tys ksig cons derivs =
do
ctxt1 <- ctxt
tys1 <- sequence tys
cons1 <- sequence cons
derivs1 <- derivs
return (DataInstD ctxt1 tc tys1 ksig cons1 derivs1)
newtypeInstD :: CxtQ -> Name -> [TypeQ] -> Maybe Kind -> ConQ -> CxtQ -> DecQ
newtypeInstD ctxt tc tys ksig con derivs =
do
ctxt1 <- ctxt
tys1 <- sequence tys
con1 <- con
derivs1 <- derivs
return (NewtypeInstD ctxt1 tc tys1 ksig con1 derivs1)
tySynInstD :: Name -> TySynEqnQ -> DecQ
tySynInstD tc eqn =
do
eqn1 <- eqn
return (TySynInstD tc eqn1)
dataFamilyD :: Name -> [TyVarBndr] -> Maybe Kind -> DecQ
dataFamilyD tc tvs kind
= return $ DataFamilyD tc tvs kind
openTypeFamilyD :: Name -> [TyVarBndr] -> FamilyResultSig
-> Maybe InjectivityAnn -> DecQ
openTypeFamilyD tc tvs res inj
= return $ OpenTypeFamilyD (TypeFamilyHead tc tvs res inj)
closedTypeFamilyD :: Name -> [TyVarBndr] -> FamilyResultSig
-> Maybe InjectivityAnn -> [TySynEqnQ] -> DecQ
closedTypeFamilyD tc tvs result injectivity eqns =
do eqns1 <- sequence eqns
return (ClosedTypeFamilyD (TypeFamilyHead tc tvs result injectivity) eqns1)
-- These were deprecated in GHC 8.0 with a plan to remove them in 8.2. If you
-- remove this check please also:
-- 1. remove deprecated functions
-- 2. remove CPP language extension from top of this module
-- 3. remove the FamFlavour data type from Syntax module
-- 4. make sure that all references to FamFlavour are gone from DsMeta,
-- Convert, TcSplice (follows from 3)
#if __GLASGOW_HASKELL__ >= 802
#error Remove deprecated familyNoKindD, familyKindD, closedTypeFamilyNoKindD and closedTypeFamilyKindD
#endif
{-# DEPRECATED familyNoKindD, familyKindD
"This function will be removed in the next stable release. Use openTypeFamilyD/dataFamilyD instead." #-}
familyNoKindD :: FamFlavour -> Name -> [TyVarBndr] -> DecQ
familyNoKindD flav tc tvs =
case flav of
TypeFam -> return $ OpenTypeFamilyD (TypeFamilyHead tc tvs NoSig Nothing)
DataFam -> return $ DataFamilyD tc tvs Nothing
familyKindD :: FamFlavour -> Name -> [TyVarBndr] -> Kind -> DecQ
familyKindD flav tc tvs k =
case flav of
TypeFam ->
return $ OpenTypeFamilyD (TypeFamilyHead tc tvs (KindSig k) Nothing)
DataFam -> return $ DataFamilyD tc tvs (Just k)
{-# DEPRECATED closedTypeFamilyNoKindD, closedTypeFamilyKindD
"This function will be removed in the next stable release. Use closedTypeFamilyD instead." #-}
closedTypeFamilyNoKindD :: Name -> [TyVarBndr] -> [TySynEqnQ] -> DecQ
closedTypeFamilyNoKindD tc tvs eqns =
do eqns1 <- sequence eqns
return (ClosedTypeFamilyD (TypeFamilyHead tc tvs NoSig Nothing) eqns1)
closedTypeFamilyKindD :: Name -> [TyVarBndr] -> Kind -> [TySynEqnQ] -> DecQ
closedTypeFamilyKindD tc tvs kind eqns =
do eqns1 <- sequence eqns
return (ClosedTypeFamilyD (TypeFamilyHead tc tvs (KindSig kind) Nothing)
eqns1)
roleAnnotD :: Name -> [Role] -> DecQ
roleAnnotD name roles = return $ RoleAnnotD name roles
standaloneDerivD :: CxtQ -> TypeQ -> DecQ
standaloneDerivD ctxtq tyq =
do
ctxt <- ctxtq
ty <- tyq
return $ StandaloneDerivD ctxt ty
defaultSigD :: Name -> TypeQ -> DecQ
defaultSigD n tyq =
do
ty <- tyq
return $ DefaultSigD n ty
tySynEqn :: [TypeQ] -> TypeQ -> TySynEqnQ
tySynEqn lhs rhs =
do
lhs1 <- sequence lhs
rhs1 <- rhs
return (TySynEqn lhs1 rhs1)
cxt :: [PredQ] -> CxtQ
cxt = sequence
normalC :: Name -> [BangTypeQ] -> ConQ
normalC con strtys = liftM (NormalC con) $ sequence strtys
recC :: Name -> [VarBangTypeQ] -> ConQ
recC con varstrtys = liftM (RecC con) $ sequence varstrtys
infixC :: Q (Bang, Type) -> Name -> Q (Bang, Type) -> ConQ
infixC st1 con st2 = do st1' <- st1
st2' <- st2
return $ InfixC st1' con st2'
forallC :: [TyVarBndr] -> CxtQ -> ConQ -> ConQ
forallC ns ctxt con = liftM2 (ForallC ns) ctxt con
gadtC :: [Name] -> [StrictTypeQ] -> TypeQ -> ConQ
gadtC cons strtys ty = liftM2 (GadtC cons) (sequence strtys) ty
recGadtC :: [Name] -> [VarStrictTypeQ] -> TypeQ -> ConQ
recGadtC cons varstrtys ty = liftM2 (RecGadtC cons) (sequence varstrtys) ty
-------------------------------------------------------------------------------
-- * Type
forallT :: [TyVarBndr] -> CxtQ -> TypeQ -> TypeQ
forallT tvars ctxt ty = do
ctxt1 <- ctxt
ty1 <- ty
return $ ForallT tvars ctxt1 ty1
varT :: Name -> TypeQ
varT = return . VarT
conT :: Name -> TypeQ
conT = return . ConT
infixT :: TypeQ -> Name -> TypeQ -> TypeQ
infixT t1 n t2 = do t1' <- t1
t2' <- t2
return (InfixT t1' n t2')
uInfixT :: TypeQ -> Name -> TypeQ -> TypeQ
uInfixT t1 n t2 = do t1' <- t1
t2' <- t2
return (UInfixT t1' n t2')
parensT :: TypeQ -> TypeQ
parensT t = do t' <- t
return (ParensT t')
appT :: TypeQ -> TypeQ -> TypeQ
appT t1 t2 = do
t1' <- t1
t2' <- t2
return $ AppT t1' t2'
arrowT :: TypeQ
arrowT = return ArrowT
listT :: TypeQ
listT = return ListT
litT :: TyLitQ -> TypeQ
litT l = fmap LitT l
tupleT :: Int -> TypeQ
tupleT i = return (TupleT i)
unboxedTupleT :: Int -> TypeQ
unboxedTupleT i = return (UnboxedTupleT i)
sigT :: TypeQ -> Kind -> TypeQ
sigT t k
= do
t' <- t
return $ SigT t' k
equalityT :: TypeQ
equalityT = return EqualityT
wildCardT :: TypeQ
wildCardT = return WildCardT
{-# DEPRECATED classP "As of template-haskell-2.10, constraint predicates (Pred) are just types (Type), in keeping with ConstraintKinds. Please use 'conT' and 'appT'." #-}
classP :: Name -> [Q Type] -> Q Pred
classP cla tys
= do
tysl <- sequence tys
return (foldl AppT (ConT cla) tysl)
{-# DEPRECATED equalP "As of template-haskell-2.10, constraint predicates (Pred) are just types (Type), in keeping with ConstraintKinds. Please see 'equalityT'." #-}
equalP :: TypeQ -> TypeQ -> PredQ
equalP tleft tright
= do
tleft1 <- tleft
tright1 <- tright
eqT <- equalityT
return (foldl AppT eqT [tleft1, tright1])
promotedT :: Name -> TypeQ
promotedT = return . PromotedT
promotedTupleT :: Int -> TypeQ
promotedTupleT i = return (PromotedTupleT i)
promotedNilT :: TypeQ
promotedNilT = return PromotedNilT
promotedConsT :: TypeQ
promotedConsT = return PromotedConsT
noSourceUnpackedness, sourceNoUnpack, sourceUnpack :: SourceUnpackednessQ
noSourceUnpackedness = return NoSourceUnpackedness
sourceNoUnpack = return SourceNoUnpack
sourceUnpack = return SourceUnpack
noSourceStrictness, sourceLazy, sourceStrict :: SourceStrictnessQ
noSourceStrictness = return NoSourceStrictness
sourceLazy = return SourceLazy
sourceStrict = return SourceStrict
{-# DEPRECATED isStrict
["Use 'bang'. See https://ghc.haskell.org/trac/ghc/wiki/Migration/8.0. ",
"Example usage: 'bang noSourceUnpackedness sourceStrict'"] #-}
{-# DEPRECATED notStrict
["Use 'bang'. See https://ghc.haskell.org/trac/ghc/wiki/Migration/8.0. ",
"Example usage: 'bang noSourceUnpackedness noSourceStrictness'"] #-}
{-# DEPRECATED unpacked
["Use 'bang'. See https://ghc.haskell.org/trac/ghc/wiki/Migration/8.0. ",
"Example usage: 'bang sourceUnpack sourceStrict'"] #-}
isStrict, notStrict, unpacked :: Q Strict
isStrict = bang noSourceUnpackedness sourceStrict
notStrict = bang noSourceUnpackedness noSourceStrictness
unpacked = bang sourceUnpack sourceStrict
bang :: SourceUnpackednessQ -> SourceStrictnessQ -> BangQ
bang u s = do u' <- u
s' <- s
return (Bang u' s')
bangType :: BangQ -> TypeQ -> BangTypeQ
bangType = liftM2 (,)
varBangType :: Name -> BangTypeQ -> VarBangTypeQ
varBangType v bt = do (b, t) <- bt
return (v, b, t)
{-# DEPRECATED strictType
"As of @template-haskell-2.11.0.0@, 'StrictType' has been replaced by 'BangType'. Please use 'bangType' instead." #-}
strictType :: Q Strict -> TypeQ -> StrictTypeQ
strictType = bangType
{-# DEPRECATED varStrictType
"As of @template-haskell-2.11.0.0@, 'VarStrictType' has been replaced by 'VarBangType'. Please use 'varBangType' instead." #-}
varStrictType :: Name -> StrictTypeQ -> VarStrictTypeQ
varStrictType = varBangType
-- * Type Literals
numTyLit :: Integer -> TyLitQ
numTyLit n = if n >= 0 then return (NumTyLit n)
else fail ("Negative type-level number: " ++ show n)
strTyLit :: String -> TyLitQ
strTyLit s = return (StrTyLit s)
-------------------------------------------------------------------------------
-- * Kind
plainTV :: Name -> TyVarBndr
plainTV = PlainTV
kindedTV :: Name -> Kind -> TyVarBndr
kindedTV = KindedTV
varK :: Name -> Kind
varK = VarT
conK :: Name -> Kind
conK = ConT
tupleK :: Int -> Kind
tupleK = TupleT
arrowK :: Kind
arrowK = ArrowT
listK :: Kind
listK = ListT
appK :: Kind -> Kind -> Kind
appK = AppT
starK :: Kind
starK = StarT
constraintK :: Kind
constraintK = ConstraintT
-------------------------------------------------------------------------------
-- * Type family result
noSig :: FamilyResultSig
noSig = NoSig
kindSig :: Kind -> FamilyResultSig
kindSig = KindSig
tyVarSig :: TyVarBndr -> FamilyResultSig
tyVarSig = TyVarSig
-------------------------------------------------------------------------------
-- * Injectivity annotation
injectivityAnn :: Name -> [Name] -> InjectivityAnn
injectivityAnn = TH.InjectivityAnn
-------------------------------------------------------------------------------
-- * Role
nominalR, representationalR, phantomR, inferR :: Role
nominalR = NominalR
representationalR = RepresentationalR
phantomR = PhantomR
inferR = InferR
-------------------------------------------------------------------------------
-- * Callconv
cCall, stdCall, cApi, prim, javaScript :: Callconv
cCall = CCall
stdCall = StdCall
cApi = CApi
prim = Prim
javaScript = JavaScript
-------------------------------------------------------------------------------
-- * Safety
unsafe, safe, interruptible :: Safety
unsafe = Unsafe
safe = Safe
interruptible = Interruptible
-------------------------------------------------------------------------------
-- * FunDep
funDep :: [Name] -> [Name] -> FunDep
funDep = FunDep
-------------------------------------------------------------------------------
-- * FamFlavour
typeFam, dataFam :: FamFlavour
typeFam = TypeFam
dataFam = DataFam
-------------------------------------------------------------------------------
-- * RuleBndr
ruleVar :: Name -> RuleBndrQ
ruleVar = return . RuleVar
typedRuleVar :: Name -> TypeQ -> RuleBndrQ
typedRuleVar n ty = ty >>= return . TypedRuleVar n
-------------------------------------------------------------------------------
-- * AnnTarget
valueAnnotation :: Name -> AnnTarget
valueAnnotation = ValueAnnotation
typeAnnotation :: Name -> AnnTarget
typeAnnotation = TypeAnnotation
moduleAnnotation :: AnnTarget
moduleAnnotation = ModuleAnnotation
--------------------------------------------------------------
-- * Useful helper function
appsE :: [ExpQ] -> ExpQ
appsE [] = error "appsE []"
appsE [x] = x
appsE (x:y:zs) = appsE ( (appE x y) : zs )
-- | Return the Module at the place of splicing. Can be used as an
-- input for 'reifyModule'.
thisModule :: Q Module
thisModule = do
loc <- location
return $ Module (mkPkgName $ loc_package loc) (mkModName $ loc_module loc)
| tjakway/ghcjvm | libraries/template-haskell/Language/Haskell/TH/Lib.hs | bsd-3-clause | 24,488 | 0 | 13 | 6,078 | 7,991 | 4,112 | 3,879 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Pos.Diffusion.Full.Block
( getBlocks
, requestTip
, announceBlockHeader
, handleHeadersCommunication
, streamBlocks
, blockListeners
, ResetNodeTimer (..)
) where
import Universum
import qualified Control.Concurrent.Async as Async
import qualified Control.Concurrent.STM as Conc
import Control.Exception (Exception (..), throwIO)
import Control.Lens (to)
import Control.Monad.Except (ExceptT, runExceptT, throwError)
import qualified Data.ByteString.Lazy as BSL
import Data.Conduit (await, runConduit, (.|))
import Data.List.NonEmpty (NonEmpty ((:|)))
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as M
import qualified Data.Set as S
import Formatting (bprint, build, int, sformat, shown, stext, (%))
import qualified Formatting.Buildable as B
import qualified Network.Broadcast.OutboundQueue as OQ
import Node.Conversation (sendRaw)
import Serokell.Util.Text (listJson)
import qualified System.Metrics.Gauge as Gauge
import Pos.Binary.Communication (serializeMsgSerializedBlock,
serializeMsgStreamBlock)
import Pos.Chain.Block (Block, BlockHeader (..), HeaderHash,
MainBlockHeader, blockHeader, headerHash, prevBlockL)
import Pos.Chain.Update (BlockVersionData)
import Pos.Communication.Limits (mlMsgBlock, mlMsgGetBlocks,
mlMsgGetHeaders, mlMsgHeaders, mlMsgStream,
mlMsgStreamBlock)
import Pos.Core (ProtocolConstants (..), difficultyL)
import Pos.Core.Chrono (NE, NewestFirst (..), OldestFirst (..),
toOldestFirst, _NewestFirst, _OldestFirst)
import Pos.Core.Exception (cardanoExceptionFromException,
cardanoExceptionToException)
import Pos.Crypto (shortHashF)
import Pos.DB (DBError (DBMalformed))
import Pos.Infra.Communication.Listener (listenerConv)
import Pos.Infra.Communication.Protocol (Conversation (..),
ConversationActions (..), EnqueueMsg, ListenerSpec,
MkListeners (..), MsgType (..), NodeId, Origin (..),
OutSpecs, constantListeners, recvLimited,
waitForConversations, waitForDequeues)
import Pos.Infra.Diffusion.Types (DiffusionHealth (..),
StreamBlocks (..))
import Pos.Infra.Network.Types (Bucket)
import Pos.Logic.Types (Logic)
import qualified Pos.Logic.Types as Logic
import Pos.Network.Block.Types (MsgBlock (..), MsgGetBlocks (..),
MsgGetHeaders (..), MsgHeaders (..),
MsgSerializedBlock (..), MsgStream (..),
MsgStreamBlock (..), MsgStreamStart (..),
MsgStreamUpdate (..))
import Pos.Util (_neHead, _neLast)
import Pos.Util.Trace (Severity (..), Trace, traceWith)
{-# ANN module ("HLint: ignore Reduce duplication" :: Text) #-}
----------------------------------------------------------------------------
-- Exceptions
----------------------------------------------------------------------------
data BlockNetLogicException
= DialogUnexpected Text
-- ^ Node's response in any network/block related logic was
-- unexpected.
| BlockNetLogicInternal Text
-- ^ We don't expect this to happen. Most probably it's internal
-- logic error.
deriving (Show)
instance B.Buildable BlockNetLogicException where
build e = bprint ("BlockNetLogicException: "%shown) e
instance Exception BlockNetLogicException where
toException = cardanoExceptionToException
fromException = cardanoExceptionFromException
displayException = toString . pretty
----------------------------------------------------------------------------
-- Networking
----------------------------------------------------------------------------
-- | Expects sending message to exactly one node. Receives result or
-- fails if no result was obtained (no nodes available, timeout, etc).
enqueueMsgSingle
:: (t2 -> (t1 -> t -> NonEmpty x) -> IO (Map NodeId (Conc.TVar (OQ.PacketStatus b))))
-> t2
-> x
-> IO b
enqueueMsgSingle enqueue msg conv = do
results <- enqueue msg (\_ _ -> one conv) >>= waitForConversations . waitForDequeues
case toList results of
[] -> liftIO $ throwIO $ DialogUnexpected $
"enqueueMsgSingle: contacted no peers"
(_:_:_) -> liftIO $ throwIO $ DialogUnexpected $
"enqueueMsgSingle: contacted more than one peers, probably internal error"
[x] -> pure x
-- | Get some blocks from the network.
-- No verification is done
getBlocks
:: Trace IO (Severity, Text)
-> Logic IO
-> Word -- ^ Historical: limit on how many headers you can get back... always 2200
-> EnqueueMsg
-> NodeId
-> HeaderHash
-> [HeaderHash]
-> IO (OldestFirst [] Block)
getBlocks logTrace logic recoveryHeadersMessage enqueue nodeId tipHeaderHash checkpoints = do
-- It is apparently an error to request headers for the tipHeader and
-- [tipHeader], i.e. 1 checkpoint equal to the header of the block that
-- you want. Sure, it's a silly thing to do, but should it be an error?
--
-- Anyway, the procedure was and still is: if it's just one block you want,
-- then you can skip requesting the headers and go straight to requesting
-- the block itself.
bvd <- Logic.getAdoptedBVData logic
blocks <- if singleBlockHeader
then requestBlocks bvd (OldestFirst (one tipHeaderHash))
else requestAndClassifyHeaders bvd >>= requestBlocks bvd
pure (OldestFirst (reverse (toList blocks)))
where
requestAndClassifyHeaders :: BlockVersionData -> IO (OldestFirst [] HeaderHash)
requestAndClassifyHeaders bvd = do
OldestFirst headers <- toOldestFirst <$> requestHeaders bvd
-- Logic layer gives us the suffix of the chain that we don't have.
-- Possibly empty.
-- 'requestHeaders' gives a NonEmpty; we drop it to a [].
fmap snd (Logic.getLcaMainChain logic (OldestFirst (toList (fmap headerHash headers))))
singleBlockHeader :: Bool
singleBlockHeader = case checkpoints of
[checkpointHash] -> checkpointHash == tipHeaderHash
_ -> False
mgh :: MsgGetHeaders
mgh = MsgGetHeaders
{ mghFrom = checkpoints
, mghTo = Just tipHeaderHash
}
-- | Make message which requests chain of blocks which is based on our
-- tip. LcaChild is the first block after LCA we don't
-- know. WantedBlock is the newest one we want to get.
mkBlocksRequest :: HeaderHash -> HeaderHash -> MsgGetBlocks
mkBlocksRequest lcaChild wantedBlock =
MsgGetBlocks
{ mgbFrom = lcaChild
, mgbTo = wantedBlock
}
requestHeaders :: BlockVersionData -> IO (NewestFirst NE BlockHeader)
requestHeaders bvd = enqueueMsgSingle
enqueue
(MsgRequestBlockHeaders (Just (S.singleton nodeId)))
(Conversation (requestHeadersConversation bvd))
requestHeadersConversation
:: BlockVersionData
-> ConversationActions MsgGetHeaders MsgHeaders
-> IO (NewestFirst NE BlockHeader)
requestHeadersConversation bvd conv = do
traceWith logTrace (Debug, sformat ("requestHeaders: sending "%build) mgh)
send conv mgh
mHeaders <- recvLimited conv (mlMsgHeaders bvd (fromIntegral recoveryHeadersMessage))
inRecovery <- Logic.recoveryInProgress logic
-- TODO: it's very suspicious to see False here as RequestHeaders
-- is only called when we're in recovery mode.
traceWith logTrace (Debug, sformat ("requestHeaders: inRecovery = "%shown) inRecovery)
case mHeaders of
Nothing -> do
traceWith logTrace (Warning, "requestHeaders: received Nothing as a response on MsgGetHeaders")
throwIO $ DialogUnexpected $
sformat ("requestHeaders: received Nothing from "%build) nodeId
Just (MsgNoHeaders t) -> do
traceWith logTrace (Warning, "requestHeaders: received MsgNoHeaders: " <> t)
throwIO $ DialogUnexpected $
sformat ("requestHeaders: received MsgNoHeaders from "%
build%", msg: "%stext)
nodeId
t
Just (MsgHeaders headers) -> do
traceWith logTrace (Debug, sformat
("requestHeaders: received "%int%" headers from nodeId "%build)
(headers ^. _NewestFirst . to NE.length)
nodeId)
return headers
requestBlocks :: BlockVersionData -> OldestFirst [] HeaderHash -> IO (NewestFirst [] Block)
requestBlocks _ (OldestFirst []) = pure (NewestFirst [])
requestBlocks bvd (OldestFirst (b:bs)) = enqueueMsgSingle
enqueue
(MsgRequestBlocks (S.singleton nodeId))
(Conversation $ requestBlocksConversation bvd (OldestFirst (b :| bs)))
requestBlocksConversation
:: BlockVersionData
-> OldestFirst NE HeaderHash
-> ConversationActions MsgGetBlocks MsgBlock
-> IO (NewestFirst [] Block)
requestBlocksConversation bvd headers conv = do
-- Preserved behaviour from existing logic code: all of the headers
-- except for the first and last are tossed away.
-- TODO don't be so wasteful [CSL-2148]
let oldestHeader = headers ^. _OldestFirst . _neHead
newestHeader = headers ^. _OldestFirst . _neLast
numBlocks = length headers
lcaChild = oldestHeader
traceWith logTrace (Debug, sformat ("Requesting blocks from "%shortHashF%" to "%shortHashF)
lcaChild
newestHeader)
send conv $ mkBlocksRequest lcaChild newestHeader
traceWith logTrace (Debug, "Requested blocks, waiting for the response")
chainE <- runExceptT (retrieveBlocks conv bvd numBlocks)
case chainE of
Left e -> do
let msg = sformat ("Error retrieving blocks from "%shortHashF%
" to "%shortHashF%" from peer "%
build%": "%stext)
lcaChild newestHeader nodeId e
traceWith logTrace (Warning, msg)
throwIO $ DialogUnexpected msg
Right bs -> return bs
-- A piece of the block retrieval conversation in which the blocks are
-- pulled in one-by-one.
retrieveBlocks
:: ConversationActions MsgGetBlocks MsgBlock
-> BlockVersionData
-> Int
-> ExceptT Text IO (NewestFirst [] Block)
retrieveBlocks conv bvd numBlocks = retrieveBlocksDo conv bvd numBlocks []
-- Content of retrieveBlocks.
-- Receive a given number of blocks. If the server doesn't send this
-- many blocks, an error will be given.
--
-- Copied from the old logic but modified to use an accumulator rather
-- than fmapping (<|). That changed the order so we're now NewestFirst
-- (presumably the server sends them oldest first, as that assumption was
-- required for the old version to correctly say OldestFirst).
retrieveBlocksDo
:: ConversationActions MsgGetBlocks MsgBlock
-> BlockVersionData
-> Int -- ^ Index of block we're requesting
-> [Block] -- ^ Accumulator
-> ExceptT Text IO (NewestFirst [] Block)
retrieveBlocksDo conv bvd !i !acc
| i <= 0 = pure $ NewestFirst acc
| otherwise = lift (recvLimited conv (mlMsgBlock bvd)) >>= \case
Nothing ->
throwError $ sformat ("Block retrieval cut short by peer at index #"%int) i
Just (MsgNoBlock t) ->
throwError $ sformat ("Peer failed to produce block #"%int%": "%stext) i t
Just (MsgBlock block) -> do
retrieveBlocksDo conv bvd (i - 1) (block : acc)
-- | Datatype used for the queue of blocks, produced by network streaming and
-- then consumed by a continuation resonsible for writing blocks to store.
-- StreamEnd signals end of stream.
data StreamEntry = StreamEnd | StreamBlock !Block
-- | Stream some blocks from the network.
-- If streaming is not supported by the client or peer, you get 'Nothing'. We
-- don't fall back to batching because we can't: that method requires having
-- all of the header hashes for the blocks you desire.
streamBlocks
:: forall t .
Trace IO (Severity, Text)
-> Maybe DiffusionHealth
-> Logic IO
-> Word32 -- ^ Size of batches of blocks (deliver to StreamBlocks).
-> Word32 -- ^ Size of stream window. 0 implies 'Nothing' is returned.
-> EnqueueMsg
-> NodeId
-> HeaderHash
-> [HeaderHash]
-> StreamBlocks Block IO t
-> IO (Maybe t)
streamBlocks _ _ _ _ 0 _ _ _ _ _ =
return Nothing -- Fallback to batch mode
streamBlocks logTrace smM logic batchSize streamWindow enqueue nodeId tipHeader checkpoints streamBlocksK =
-- An exception in this thread will always terminate the sub-thread that
-- deals with the streaming. An exception in the sub thread will be
-- re-thrown in this one by way of `Async.await`.
--
-- If `streamBlocks` is killed by an async exception, we must guarantee
-- that the thread which does the streaming will also be killed, or
-- never begun in case it hasn't yet been dequeued.
-- So it's not just a simple bracket: even the acquiring part must do
-- something like a bracket via mask/restore, so that if any exception
-- comes in before the thing is dequeued, it aborts.
bracket requestBlocks Async.cancel Async.wait
where
mkStreamStart :: [HeaderHash] -> HeaderHash -> MsgStream
mkStreamStart chain wantedBlock =
MsgStart $ MsgStreamStart
{ mssFrom = chain
, mssTo = wantedBlock
, mssWindow = streamWindow
}
-- Enqueue the request blocks conversation and then
-- - if exception, abort it or kill it
-- - if no exception, return it
-- the `bracket` on the RHS of `streamBlocks` will kill it if this
-- thread is killed, and it also awaits the sub-thread so will be
-- killed if the sub thread dies.
requestBlocks :: IO (Async.Async (Maybe t))
requestBlocks = mask $ \restore -> do
convMap <- enqueue
(MsgRequestBlocks (S.singleton nodeId))
(\_ _ -> (Conversation $ streamBlocksConversation) :|
[(Conversation $ batchConversation)]
)
let waitForDequeue = case M.lookup nodeId convMap of
Just tvar -> atomically $ do
pStatus <- Conc.readTVar tvar
case pStatus of
OQ.PacketEnqueued -> Conc.retry
OQ.PacketAborted -> Conc.throwSTM $ DialogUnexpected $ "streamBlocks: aborted"
OQ.PacketDequeued streamThread -> pure streamThread
Nothing -> throwIO $ DialogUnexpected $ "streamBlocks: did not contact given peer"
-- Abort the conversation if it's not yet enqueued, or cancel
-- it if is enqueued.
abortOrCancel = case M.lookup nodeId convMap of
Just tvar -> join $ atomically $ do
pStatus <- Conc.readTVar tvar
case pStatus of
OQ.PacketEnqueued -> do
Conc.writeTVar tvar OQ.PacketAborted
pure (pure ())
OQ.PacketAborted ->
pure (pure ())
OQ.PacketDequeued streamThread ->
pure (Async.cancel streamThread)
Nothing -> pure ()
restore waitForDequeue `onException` abortOrCancel
-- The peer doesn't support streaming, we need to fall back to batching but
-- the current conversation is unusable since there is no way for us to learn
-- which blocks we shall fetch.
batchConversation
:: ConversationActions MsgGetBlocks MsgBlock
-> IO (Maybe t)
batchConversation _ = pure Nothing
streamBlocksConversation
:: ConversationActions MsgStream MsgStreamBlock
-> IO (Maybe t)
streamBlocksConversation conv = do
let newestHash = headerHash tipHeader
traceWith logTrace (Debug,
sformat ("streamBlocks: Requesting stream of blocks from "%listJson%" to "%shortHashF)
checkpoints
newestHash)
send conv $ mkStreamStart checkpoints newestHash
bvd <- Logic.getAdoptedBVData logic
-- Two threads are used here: one to pull in blocks, and one to
-- call into the application 'StreamBlocks' value. The reason:
-- the latter could do a lot of work for each batch, so having another
-- thread continually pulling in with a buffer in the middle will
-- smooth the traffic.
blockChan <- atomically $ Conc.newTBQueue $ fromIntegral streamWindow
(_, b) <- Async.concurrently
(retrieveBlocks bvd blockChan conv streamWindow)
(processBlocks 0 [] blockChan streamBlocksK)
pure $ Just b
halfStreamWindow = max 1 $ streamWindow `div` 2
-- A piece of the block retrieval conversation in which the blocks are
-- pulled in one-by-one.
retrieveBlocks
:: BlockVersionData
-> Conc.TBQueue StreamEntry
-> ConversationActions MsgStream MsgStreamBlock
-> Word32
-> IO ()
retrieveBlocks bvd blockChan conv window = do
window' <- if window <= halfStreamWindow
then do
let w' = window + halfStreamWindow
traceWith logTrace (Debug, sformat ("Updating Window: "%int%" to "%int) window w')
send conv $ MsgUpdate $ MsgStreamUpdate halfStreamWindow
return (w' - 1)
else return $ window - 1
block <- retrieveBlock bvd conv
case block of
MsgStreamNoBlock e -> do
let msg = sformat ("MsgStreamNoBlock "%stext) e
traceWith logTrace (Error, msg)
throwM $ DialogUnexpected msg
MsgStreamEnd -> do
atomically $ Conc.writeTBQueue blockChan StreamEnd
traceWith logTrace (Debug, sformat ("Streaming done client-side for node"%build) nodeId)
MsgStreamBlock b -> do
atomically $ Conc.writeTBQueue blockChan (StreamBlock b)
case smM of
Nothing -> pure ()
Just sm -> do
Gauge.inc $ dhStreamWriteQueue sm
Gauge.set (dhStreamWindow sm) (fromIntegral window')
retrieveBlocks bvd blockChan conv window'
retrieveBlock
:: BlockVersionData
-> ConversationActions MsgStream MsgStreamBlock
-> IO MsgStreamBlock
retrieveBlock bvd conv = do
blockE <- recvLimited conv (mlMsgStreamBlock bvd)
case blockE of
Nothing -> do
let msg = sformat ("Error retrieving blocks from peer "%build) nodeId
traceWith logTrace (Error, msg)
throwM $ DialogUnexpected msg
Just block -> return block
processBlocks
:: Word32
-> [Block]
-> Conc.TBQueue StreamEntry
-> StreamBlocks Block IO t
-> IO t
processBlocks n !blocks blockChan k = do
streamEntry <- atomically $ Conc.readTBQueue blockChan
case streamEntry of
StreamEnd -> case blocks of
[] -> streamBlocksDone k
(blk:blks) -> do
k' <- streamBlocksMore k (blk :| blks)
streamBlocksDone k'
StreamBlock block -> do
-- FIXME this logging stuff should go into the particular
-- 'StreamBlocks' value rather than here.
let n' = n + 1
when (n' `mod` 256 == 0) $
traceWith logTrace (Debug,
sformat ("Read block "%shortHashF%" difficulty "%int) (headerHash block)
(block ^. difficultyL))
case smM of
Nothing -> pure ()
Just sm -> liftIO $ Gauge.dec $ dhStreamWriteQueue sm
if n' `mod` batchSize == 0
then do
k' <- streamBlocksMore k (block :| blocks)
processBlocks n' [] blockChan k'
else
processBlocks n' (block : blocks) blockChan k
requestTip
:: Trace IO (Severity, Text)
-> Logic IO
-> EnqueueMsg
-> Word
-> IO (Map NodeId (IO BlockHeader))
requestTip logTrace logic enqueue recoveryHeadersMessage = fmap waitForDequeues $
enqueue (MsgRequestBlockHeaders Nothing) $ \nodeId _ -> pure . Conversation $
\(conv :: ConversationActions MsgGetHeaders MsgHeaders) -> do
traceWith logTrace (Debug, "Requesting tip...")
bvd <- Logic.getAdoptedBVData logic
send conv (MsgGetHeaders [] Nothing)
received <- recvLimited conv (mlMsgHeaders bvd (fromIntegral recoveryHeadersMessage))
case received of
Just headers -> handleTip nodeId headers
Nothing -> throwIO $ DialogUnexpected "peer didnt' respond with tips"
where
handleTip nodeId (MsgHeaders (NewestFirst (tip:|[]))) = do
traceWith logTrace (Debug, sformat ("Got tip "%shortHashF%" from "%shown%", processing") (headerHash tip) nodeId)
pure tip
handleTip _ t = do
traceWith logTrace (Warning, sformat ("requestTip: got enexpected response: "%shown) t)
throwIO $ DialogUnexpected "peer sent more than one tip"
-- | Announce a block header.
announceBlockHeader
:: Trace IO (Severity, Text)
-> Logic IO
-> ProtocolConstants
-> Word
-> EnqueueMsg
-> MainBlockHeader
-> IO (Map NodeId (IO ()))
announceBlockHeader logTrace logic protocolConstants recoveryHeadersMessage enqueue header = do
traceWith logTrace (Debug, sformat ("Announcing header to others:\n"%build) header)
waitForDequeues <$> enqueue (MsgAnnounceBlockHeader OriginSender) (\addr _ -> announceBlockDo addr)
where
announceBlockDo nodeId = pure $ Conversation $ \cA -> do
traceWith logTrace (Debug,
sformat
("Announcing block "%shortHashF%" to "%build)
(headerHash header)
nodeId)
send cA $ MsgHeaders (one (BlockHeaderMain header))
-- After we announce, the peer is given an opportunity to request more
-- headers within the same conversation.
handleHeadersCommunication logTrace logic protocolConstants recoveryHeadersMessage cA
-- | A conversation for incoming MsgGetHeaders messages.
-- For each of these messages, we'll try to send back the relevant headers,
-- until the client closes up.
handleHeadersCommunication
:: Trace IO (Severity, Text)
-> Logic IO
-> ProtocolConstants
-> Word
-> ConversationActions MsgHeaders MsgGetHeaders
-> IO ()
handleHeadersCommunication logTrace logic protocolConstants recoveryHeadersMessage conv = do
let bc = fromIntegral (pcK protocolConstants)
whenJustM (recvLimited conv (mlMsgGetHeaders bc)) $ \mgh@(MsgGetHeaders {..}) -> do
traceWith logTrace (Debug, sformat ("Got request on handleGetHeaders: "%build) mgh)
-- FIXME
-- Diffusion layer is entirely capable of serving blocks even if the
-- logic layer is in recovery mode.
ifM (Logic.recoveryInProgress logic) onRecovery $ do
headers <- case (mghFrom,mghTo) of
-- This is how a peer requests our tip: empty checkpoint list,
-- Nothing for the limiting hash.
([], Nothing) -> Right . one <$> getLastMainHeader
-- This is how a peer requests one particular header: empty
-- checkpoint list, Just for the limiting hash.
([], Just h) -> do
mHeader <- Logic.getBlockHeader logic h
pure . maybeToRight "getBlockHeader returned Nothing" . fmap one $ mHeader
-- This is how a peer requests a chain of headers.
-- NB: if the limiting hash is Nothing, getBlockHeaders will
-- substitute our current tip.
(c1:cxs, _) ->
first show <$>
Logic.getBlockHeaders logic (Just recoveryHeadersMessage) (c1:|cxs) mghTo
either onNoHeaders handleSuccess headers
where
-- retrieves header of the newest main block if there's any,
-- genesis otherwise.
getLastMainHeader :: IO BlockHeader
getLastMainHeader = do
tip :: Block <- Logic.getTip logic
let tipHeader = tip ^. blockHeader
case tip of
Left _ -> do
mHeader <- Logic.getBlockHeader logic (tip ^. prevBlockL)
pure $ fromMaybe tipHeader mHeader
Right _ -> pure tipHeader
handleSuccess :: NewestFirst NE BlockHeader -> IO ()
handleSuccess h = do
send conv (MsgHeaders h)
traceWith logTrace (Debug, "handleGetHeaders: responded successfully")
handleHeadersCommunication logTrace logic protocolConstants recoveryHeadersMessage conv
onNoHeaders reason = do
let err = "getheadersFromManyTo returned Nothing, reason: " <> reason
traceWith logTrace (Warning, err)
send conv (MsgNoHeaders err)
onRecovery = do
traceWith logTrace (Debug, "handleGetHeaders: not responding, we're in recovery mode")
send conv (MsgNoHeaders "server node is in recovery mode")
-- |
-- = Listeners
newtype ResetNodeTimer = ResetNodeTimer (NodeId -> IO ())
-- | All block-related listeners.
blockListeners
:: Trace IO (Severity, Text)
-> Logic IO
-> ProtocolConstants
-> Word
-> OQ.OutboundQ pack NodeId Bucket
-> ResetNodeTimer -- ^ Keepalive timer
-> MkListeners
blockListeners logTrace logic protocolConstants recoveryHeadersMessage oq keepaliveTimer = constantListeners $
[ -- Peer wants some block headers from us.
handleGetHeaders logTrace logic protocolConstants recoveryHeadersMessage oq
-- Peer wants some blocks from us.
, handleGetBlocks logTrace logic recoveryHeadersMessage oq
-- Peer has a block header for us (yes, singular only).
, handleBlockHeaders logTrace logic oq recoveryHeadersMessage keepaliveTimer
, handleStreamStart logTrace logic oq
]
----------------------------------------------------------------------------
-- Getters (return currently stored data)
----------------------------------------------------------------------------
-- | Handles GetHeaders request which means client wants to get
-- headers from some checkpoints that are older than optional @to@
-- field.
handleGetHeaders
:: forall pack.
Trace IO (Severity, Text)
-> Logic IO
-> ProtocolConstants
-> Word
-> OQ.OutboundQ pack NodeId Bucket
-> (ListenerSpec, OutSpecs)
handleGetHeaders logTrace logic protocolConstants recoveryHeadersMessage oq = listenerConv logTrace oq $ \__ourVerInfo nodeId conv -> do
traceWith logTrace (Debug, "handleGetHeaders: request from " <> show nodeId)
handleHeadersCommunication logTrace logic protocolConstants recoveryHeadersMessage conv
-- | Handler for a GetBlocks request from a client.
-- It looks up the Block corresponding to each HeaderHash and sends it.
handleGetBlocks
:: forall pack.
Trace IO (Severity, Text)
-> Logic IO
-> Word
-> OQ.OutboundQ pack NodeId Bucket
-> (ListenerSpec, OutSpecs)
handleGetBlocks logTrace logic recoveryHeadersMessage oq = listenerConv logTrace oq $ \__ourVerInfo nodeId conv -> do
mbMsg <- recvLimited conv mlMsgGetBlocks
whenJust mbMsg $ \mgb@MsgGetBlocks{..} -> do
traceWith logTrace (Debug, sformat ("handleGetBlocks: got request "%build%" from "%build)
mgb nodeId)
-- [CSL-2148] will probably make this a faster, streaming style:
-- get the blocks directly from headers rather than getting the list
-- of headers, then one-by-one getting the corresponding blocks.
-- As such, the DBMalformed error below (failMalformed) won't be
-- necessary: the streaming thing (probably a conduit) can determine
-- whether the DB is malformed. Really, this listener has no business
-- deciding that the database is malformed.
hashesM <- Logic.getHashesRange logic (Just recoveryHeadersMessage) mgbFrom mgbTo
case hashesM of
Right hashes -> do
traceWith logTrace (Debug, sformat
("handleGetBlocks: started sending "%int%
" blocks to "%build%" one-by-one")
(length hashes) nodeId )
for_ hashes $ \hHash ->
Logic.getSerializedBlock logic hHash >>= \case
-- TODO: we should get lazy bytestring from the db layer to
-- stream the bytes to the network
Just b -> sendRaw conv $ BSL.fromStrict $ serializeMsgSerializedBlock $ MsgSerializedBlock b
Nothing -> do
send conv $ MsgNoBlock ("Couldn't retrieve block with hash " <>
pretty hHash)
failMalformed
traceWith logTrace (Debug, "handleGetBlocks: blocks sending done")
Left e -> traceWith logTrace (Warning, "getBlocksByHeaders@retrieveHeaders returned error: " <> show e)
where
-- See note above in the definition of handleGetBlocks [CSL-2148].
failMalformed =
throwIO $ DBMalformed $
"handleGetBlocks: getHashesRange returned header that doesn't " <>
"have corresponding block in storage."
handleStreamStart
:: forall pack.
Trace IO (Severity, Text)
-> Logic IO
-> OQ.OutboundQ pack NodeId Bucket
-> (ListenerSpec, OutSpecs)
handleStreamStart logTrace logic oq = listenerConv logTrace oq $ \__ourVerInfo nodeId conv -> do
msMsg <- recvLimited conv mlMsgStream
whenJust msMsg $ \ms -> do
case ms of
MsgStart s -> do
traceWith logTrace (Debug, sformat ("Streaming Request from node "%build) nodeId)
stream nodeId conv (mssFrom s) (mssTo s) (mssWindow s)
MsgUpdate _ -> do
send conv $ MsgStreamNoBlock "MsgUpdate without MsgStreamStart"
traceWith logTrace (Debug, sformat ("MsgStream without MsgStreamStart from node "%build) nodeId)
return ()
where
stream nodeId conv [] _ _ = do
send conv $ MsgStreamNoBlock "MsgStreamStart with empty from chain"
traceWith logTrace (Debug, sformat ("MsgStreamStart with empty from chain from node "%build) nodeId)
return ()
stream nodeId conv (cl:cxs) _ window = do
-- Find the newest checkpoint which is in our chain (checkpoints are
-- oldest first).
(prefix, _) <- Logic.getLcaMainChain logic (OldestFirst (fmap headerHash (cl:cxs)))
case getNewestFirst prefix of
[] -> do
send conv $ MsgStreamNoBlock "handleStreamStart:strean Failed to find lca"
traceWith logTrace (Debug, sformat ("handleStreamStart:strean getBlockHeaders from "%shown%" failed for "%listJson) nodeId (cl:cxs))
return ()
-- 'lca' is the newest client-supplied checkpoint that we have.
-- We need to begin streaming from its child, which is what
-- 'Logic.streamBlocks' does.
lca : _ -> Logic.streamBlocks logic lca $ \conduit ->
let producer = conduit >> lift (send conv MsgStreamEnd)
consumer = loop nodeId conv window
in runConduit $ producer .| consumer
loop nodeId conv 0 = do
lift $ traceWith logTrace (Debug, "handleStreamStart:loop waiting on window update")
msMsg <- lift $ recvLimited conv mlMsgStream
whenJust msMsg $ \ms -> do
case ms of
MsgStart _ -> do
lift $ send conv $ MsgStreamNoBlock ("MsgStreamStart, expected MsgStreamUpdate")
lift $ traceWith logTrace (Debug, sformat ("handleStreamStart:loop MsgStart, expected MsgStreamUpdate from "%build) nodeId)
return ()
MsgUpdate u -> do
lift $ OQ.clearFailureOf oq nodeId
lift $ traceWith logTrace (Debug, sformat ("handleStreamStart:loop new window "%shown%" from "%build) u nodeId)
loop nodeId conv (msuWindow u)
loop nodeId conv window =
whenJustM await $ \b -> do
lift $ sendRaw conv $ serializeMsgStreamBlock $ MsgSerializedBlock b
loop nodeId conv (window - 1)
----------------------------------------------------------------------------
-- Header propagation
----------------------------------------------------------------------------
-- | Handles MsgHeaders request, unsolicited usecase
handleBlockHeaders
:: forall pack .
Trace IO (Severity, Text)
-> Logic IO
-> OQ.OutboundQ pack NodeId Bucket
-> Word
-> ResetNodeTimer
-> (ListenerSpec, OutSpecs)
handleBlockHeaders logTrace logic oq recoveryHeadersMessage (ResetNodeTimer keepaliveTimer) =
listenerConv @MsgGetHeaders logTrace oq $ \__ourVerInfo nodeId conv -> do
-- The type of the messages we send is set to 'MsgGetHeaders' for
-- protocol compatibility reasons only. We could use 'Void' here because
-- we don't really send any messages.
traceWith logTrace (Debug, "handleBlockHeaders: got some unsolicited block header(s)")
bvd <- Logic.getAdoptedBVData logic
mHeaders <- recvLimited conv (mlMsgHeaders bvd (fromIntegral recoveryHeadersMessage))
whenJust mHeaders $ \case
(MsgHeaders headers) -> do
-- Reset the keepalive timer.
keepaliveTimer nodeId
handleUnsolicitedHeaders logTrace logic (getNewestFirst headers) nodeId
_ -> pass -- Why would somebody propagate 'MsgNoHeaders'? We don't care.
-- Second case of 'handleBlockheaders'
handleUnsolicitedHeaders
:: Trace IO (Severity, Text)
-> Logic IO
-> NonEmpty BlockHeader
-> NodeId
-> IO ()
handleUnsolicitedHeaders _ logic (header :| []) nodeId =
Logic.postBlockHeader logic header nodeId
-- TODO: ban node for sending more than one unsolicited header.
handleUnsolicitedHeaders logTrace _ (h:|hs) _ = do
traceWith logTrace (Warning, "Someone sent us nonzero amount of headers we didn't expect")
traceWith logTrace (Warning, sformat ("Here they are: "%listJson) (h:hs))
| input-output-hk/pos-haskell-prototype | lib/src/Pos/Diffusion/Full/Block.hs | mit | 35,606 | 0 | 30 | 10,480 | 7,122 | 3,657 | 3,465 | -1 | -1 |
module Channel.YoutubeMeSpec (main, spec) where
import Helper
import qualified Data.ByteString.Lazy as L
import Channel.Command
import Channel.Event
import Channel.YoutubeMe
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "youtubeMe" $ do
it "makes Alonzo show youtube results" $ do
runInDefaultEnv $ do
withHttp mockedHttp $ do
action $ youtubeMe $ Message "you" "alonzo: youtube me giant robot"
`shouldReturn` [Say "http://www.youtube.com/watch?v=Ya7LVIN01Qw&feature=youtube_gdata"]
where
mockedHttp "http://gdata.youtube.com/feeds/api/videos?max-results=5&alt=json&q=giant robot" = L.readFile "test/fixtures/youtube.json"
mockedHttp url = error ("unexpected request to " ++ url)
| wimdu/alonzo | test/Channel/YoutubeMeSpec.hs | mit | 791 | 0 | 21 | 175 | 167 | 87 | 80 | 18 | 2 |
{- |
Module : ./CspCASLProver/CspProverConsts.hs
Description : Isabelle Abstract syntax constants for CSP-Prover operations
Copyright : (c) Liam O'Reilly and Markus Roggenbach,
Swansea University 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
Isabelle Abstract syntax constants for CSP-Prover operations.
-}
module CspCASLProver.CspProverConsts
( cspProverbinEqF
, cspProver_NamedProcOp
, cspProver_skipOp
, cspProver_stopOp
, cspProver_divOp
, cspProver_runOp
, cspProver_chaosOp
, cspProver_action_prefixOp
, cspProver_external_prefix_choiceOp
, cspProver_internal_prefix_choiceOp
, cspProver_sequenceOp
, cspProver_external_choiceOp
, cspProver_internal_choiceOp
, cspProver_interleavingOp
, cspProver_synchronousOp
, cspProver_general_parallelOp
, cspProver_alphabetised_parallelOp
, cspProver_hidingOp
, cspProver_renamingOp
, cspProver_conditionalOp
, cspProver_chan_nondeterministic_sendOp
, cspProver_chan_sendOp
, cspProver_chan_recOp
) where
import Isabelle.IsaSign as IsaSign
import Isabelle.IsaConsts (binVNameAppl, con, termAppl)
{- Symbols for CspProver
These symbols and priorities have come from the CSP-Prover source code -}
-- | binary junctors
cspProverEqV :: VName
cspProverEqV = VName "op =F" $ Just $ AltSyntax "(_ =F/ _)" [50, 51] 50
cspProverbinEqF :: Term -> Term -> Term
cspProverbinEqF = binVNameAppl cspProverEqV
-- | Name Process symbol
cspProver_NamedProcS :: String
cspProver_NamedProcS = "Proc_name"
cspProver_NamedProcAltS :: String
cspProver_NamedProcAltS = "($ _)"
cspProver_NamedProcAltArgPrios :: [Int]
cspProver_NamedProcAltArgPrios = [900]
cspProver_NamedProcAltOpPrio :: Int
cspProver_NamedProcAltOpPrio = 90
-- | SKIP primitive process symbol
cspProver_skipS :: String
cspProver_skipS = "SKIP"
-- | STOP primitive process symbol
cspProver_stopS :: String
cspProver_stopS = "STOP"
-- | DIV primitive process symbol
cspProver_divS :: String
cspProver_divS = "DIV"
-- | RUN primitive process symbol
cspProver_runS :: String
cspProver_runS = "??? RUN ??? - NOT YET DONE"
-- | CHAOS primitive process symbol
cspProver_chaosS :: String
cspProver_chaosS = "??? CHAOS ??? - NOT YET DONE"
-- | Action prefix operator symbols
cspProver_action_prefixS :: String
cspProver_action_prefixS = "Action_prefix"
cspProver_action_prefixAltS :: String
cspProver_action_prefixAltS = "(_ -> _)"
cspProver_action_prefixAltArgPrios :: [Int]
cspProver_action_prefixAltArgPrios = [150, 80]
cspProver_action_prefixAltOpPrio :: Int
cspProver_action_prefixAltOpPrio = 80
-- | External prefix choice operator symbols
cspProver_external_prefix_choiceS :: String
cspProver_external_prefix_choiceS = "External_pre_choice"
cspProver_external_prefix_choiceAltS :: String
cspProver_external_prefix_choiceAltS = "(? _:_ -> _)"
cspProver_external_prefix_choiceAltArgPrios :: [Int]
cspProver_external_prefix_choiceAltArgPrios = [900, 900, 80]
cspProver_external_prefix_choiceAltOpPrio :: Int
cspProver_external_prefix_choiceAltOpPrio = 80
-- | Internal prefix choice operator symbols
cspProver_internal_prefix_choiceS :: String
cspProver_internal_prefix_choiceS = "Internal_pre_choice"
cspProver_internal_prefix_choiceAltS :: String
cspProver_internal_prefix_choiceAltS = "(! _:_ -> _)"
cspProver_internal_prefix_choiceAltArgPrios :: [Int]
cspProver_internal_prefix_choiceAltArgPrios = [900, 900, 80]
cspProver_internal_prefix_choiceAltOpPrio :: Int
cspProver_internal_prefix_choiceAltOpPrio = 80
-- | Sequence combinator operator symbols
cspProver_sequenceS :: String
cspProver_sequenceS = "Seq_compo"
cspProver_sequenceAltS :: String
cspProver_sequenceAltS = "(_ ;; _)"
cspProver_sequenceAltArgPrios :: [Int]
cspProver_sequenceAltArgPrios = [79, 78]
cspProver_sequenceAltOpPrio :: Int
cspProver_sequenceAltOpPrio = 78
-- | External choice operator symbols
cspProver_external_choiceS :: String
cspProver_external_choiceS = "Ext_choice"
cspProver_external_choiceAltS :: String
cspProver_external_choiceAltS = "( _ [+] _)"
cspProver_external_choiceAltArgPrios :: [Int]
cspProver_external_choiceAltArgPrios = [72, 73]
cspProver_external_choiceAltOpPrio :: Int
cspProver_external_choiceAltOpPrio = 72
-- | Internal choice operator symbols
cspProver_internal_choiceS :: String
cspProver_internal_choiceS = "Int_choice"
cspProver_internal_choiceAltS :: String
cspProver_internal_choiceAltS = "(_ |~| _)"
cspProver_internal_choiceAltArgPrios :: [Int]
cspProver_internal_choiceAltArgPrios = [64, 65]
cspProver_internal_choiceAltOpPrio :: Int
cspProver_internal_choiceAltOpPrio = 64
-- | Interleaving parallel operator symbols
cspProver_interleavingS :: String
cspProver_interleavingS = "Interleave"
cspProver_interleavingAltS :: String
cspProver_interleavingAltS = "(_ ||| _)"
cspProver_interleavingAltArgPrios :: [Int]
cspProver_interleavingAltArgPrios = [76, 77]
cspProver_interleavingAltOpPrio :: Int
cspProver_interleavingAltOpPrio = 76
-- | Synchronous parallel operator symbols
cspProver_synchronousS :: String
cspProver_synchronousS = "Synchro"
cspProver_synchronousAltS :: String
cspProver_synchronousAltS = "(_ || _)"
cspProver_synchronousAltArgPrios :: [Int]
cspProver_synchronousAltArgPrios = [76, 77]
cspProver_synchronousAltOpPrio :: Int
cspProver_synchronousAltOpPrio = 76
-- | Generalised parallel operator symbols
cspProver_general_parallelS :: String
cspProver_general_parallelS = "Parallel"
cspProver_general_parallelAltS :: String
cspProver_general_parallelAltS = "(_ |[_]| _)"
cspProver_general_parallelAltArgPrios :: [Int]
cspProver_general_parallelAltArgPrios = [76, 0, 77]
cspProver_general_parallelAltOpPrio :: Int
cspProver_general_parallelAltOpPrio = 76
-- | Alphabetised parallel operator symbols
cspProver_alphabetised_parallelS :: String
cspProver_alphabetised_parallelS = "Alpha_parallel"
cspProver_alphabetised_parallelAltS :: String
cspProver_alphabetised_parallelAltS = "(_ |[_,_]| _)"
cspProver_alphabetised_parallelAltArgPrios :: [Int]
cspProver_alphabetised_parallelAltArgPrios = [76, 0, 0, 77]
cspProver_alphabetised_parallelAltOpPrio :: Int
cspProver_alphabetised_parallelAltOpPrio = 76
-- | Hiding operator symbols
cspProver_hidingS :: String
cspProver_hidingS = "Hiding"
cspProver_hidingAltS :: String
cspProver_hidingAltS = "(_ -- _)"
cspProver_hidingAltArgPrios :: [Int]
cspProver_hidingAltArgPrios = [84, 85]
cspProver_hidingAltOpPrio :: Int
cspProver_hidingAltOpPrio = 85
-- | Renaming operator symbols
cspProver_renamingS :: String
cspProver_renamingS = "Renaming"
cspProver_renamingAltS :: String
cspProver_renamingAltS = "(_ [[_]])"
cspProver_renamingAltArgPrios :: [Int]
cspProver_renamingAltArgPrios = [84, 0]
cspProver_renamingAltOpPrio :: Int
cspProver_renamingAltOpPrio = 84
-- | Conditional operator symbols
cspProver_conditionalS :: String
cspProver_conditionalS = "IF"
cspProver_conditionalAltS :: String
cspProver_conditionalAltS = "(IF _ THEN _ ELSE _)"
cspProver_conditionalAltArgPrios :: [Int]
cspProver_conditionalAltArgPrios = [900, 88, 88]
cspProver_conditionalAltArgOpPrio :: Int
cspProver_conditionalAltArgOpPrio = 88
-- | Channel non-deterministic send operator symbols
cspProver_chan_nondeterministic_sendS :: String
cspProver_chan_nondeterministic_sendS = "Nondet_send_prefix"
cspProver_chan_nondeterministic_sendAltS :: String
cspProver_chan_nondeterministic_sendAltS = "(_ !? _ : _ -> _)"
cspProver_chan_nondeterministic_sendAltArgPrios :: [Int]
cspProver_chan_nondeterministic_sendAltArgPrios = [900, 900, 1000, 80]
cspProver_chan_nondeterministic_sendAltArgOpPrio :: Int
cspProver_chan_nondeterministic_sendAltArgOpPrio = 80
-- | Channel send operator symbols
cspProver_chan_sendS :: String
cspProver_chan_sendS = "Send_prefix"
cspProver_chan_sendAltS :: String
cspProver_chan_sendAltS = "(_ ! _ -> _)"
cspProver_chan_sendAltArgPrios :: [Int]
cspProver_chan_sendAltArgPrios = [900, 1000, 80]
cspProver_chan_sendAltArgOpPrio :: Int
cspProver_chan_sendAltArgOpPrio = 80
-- | Channel receive operator symbols
cspProver_chan_recS :: String
cspProver_chan_recS = "Rec_prefix"
cspProver_chan_recAltS :: String
cspProver_chan_recAltS = "(_ ? _ : _ -> _)"
cspProver_chan_recAltArgPrios :: [Int]
cspProver_chan_recAltArgPrios = [900, 900, 1000, 80]
cspProver_chan_recAltArgOpPrio :: Int
cspProver_chan_recAltArgOpPrio = 80
-- Isabelle Terms representing the operations for CspProver
-- | Name Process operator
cspProver_NamedProcOp :: Term -> Term
cspProver_NamedProcOp =
makeUnaryCspProverOp cspProver_NamedProcS
cspProver_NamedProcAltS
cspProver_NamedProcAltArgPrios
cspProver_NamedProcAltOpPrio
-- | SKIP primitive process operator
cspProver_skipOp :: Term
cspProver_skipOp = makeCspProverOpNoAlt cspProver_skipS
-- | STOP primitive process operator
cspProver_stopOp :: Term
cspProver_stopOp = makeCspProverOpNoAlt cspProver_stopS
-- | DIV primitive process operator
cspProver_divOp :: Term
cspProver_divOp = makeCspProverOpNoAlt cspProver_divS
-- | RUN primitive process operator
cspProver_runOp :: Term
cspProver_runOp = makeCspProverOpNoAlt cspProver_runS
-- | CHAOS primitive process operator
cspProver_chaosOp :: Term
cspProver_chaosOp = makeCspProverOpNoAlt cspProver_chaosS
-- | Action prefix operator
cspProver_action_prefixOp :: Term -> Term -> Term
cspProver_action_prefixOp =
makeBinCspProverOp cspProver_action_prefixS
cspProver_action_prefixAltS
cspProver_action_prefixAltArgPrios
cspProver_action_prefixAltOpPrio
-- | External prefix choice operator
cspProver_external_prefix_choiceOp :: Term -> Term -> Term -> Term
cspProver_external_prefix_choiceOp =
makeTriCspProverOp cspProver_external_prefix_choiceS
cspProver_external_prefix_choiceAltS
cspProver_external_prefix_choiceAltArgPrios
cspProver_external_prefix_choiceAltOpPrio
-- | Internal prefix choice operator
cspProver_internal_prefix_choiceOp :: Term -> Term -> Term -> Term
cspProver_internal_prefix_choiceOp =
makeTriCspProverOp cspProver_internal_prefix_choiceS
cspProver_internal_prefix_choiceAltS
cspProver_internal_prefix_choiceAltArgPrios
cspProver_internal_prefix_choiceAltOpPrio
-- | Sequence combinator operator
cspProver_sequenceOp :: Term -> Term -> Term
cspProver_sequenceOp =
makeBinCspProverOp cspProver_sequenceS
cspProver_sequenceAltS
cspProver_sequenceAltArgPrios
cspProver_sequenceAltOpPrio
-- | External choice operator
cspProver_external_choiceOp :: Term -> Term -> Term
cspProver_external_choiceOp =
makeBinCspProverOp cspProver_external_choiceS
cspProver_external_choiceAltS
cspProver_external_choiceAltArgPrios
cspProver_external_choiceAltOpPrio
-- | Internal choice operator
cspProver_internal_choiceOp :: Term -> Term -> Term
cspProver_internal_choiceOp =
makeBinCspProverOp cspProver_internal_choiceS
cspProver_internal_choiceAltS
cspProver_internal_choiceAltArgPrios
cspProver_internal_choiceAltOpPrio
-- | Interleaving parallel operator
cspProver_interleavingOp :: Term -> Term -> Term
cspProver_interleavingOp =
makeBinCspProverOp cspProver_interleavingS
cspProver_interleavingAltS
cspProver_interleavingAltArgPrios
cspProver_interleavingAltOpPrio
-- | Synchronous parallel operator
cspProver_synchronousOp :: Term -> Term -> Term
cspProver_synchronousOp =
makeBinCspProverOp cspProver_synchronousS
cspProver_synchronousAltS
cspProver_synchronousAltArgPrios
cspProver_synchronousAltOpPrio
-- | Generalised parallel operator
cspProver_general_parallelOp :: Term -> Term -> Term -> Term
cspProver_general_parallelOp =
makeTriCspProverOp cspProver_general_parallelS
cspProver_general_parallelAltS
cspProver_general_parallelAltArgPrios
cspProver_general_parallelAltOpPrio
-- | Alphabetised parallel operator symbols
cspProver_alphabetised_parallelOp :: Term -> Term -> Term -> Term -> Term
cspProver_alphabetised_parallelOp =
makeQuadCspProverOp cspProver_alphabetised_parallelS
cspProver_alphabetised_parallelAltS
cspProver_alphabetised_parallelAltArgPrios
cspProver_alphabetised_parallelAltOpPrio
-- | Hiding operator
cspProver_hidingOp :: Term -> Term -> Term
cspProver_hidingOp =
makeBinCspProverOp cspProver_hidingS
cspProver_hidingAltS
cspProver_hidingAltArgPrios
cspProver_hidingAltOpPrio
-- | Renaming operator
cspProver_renamingOp :: Term -> Term -> Term
cspProver_renamingOp =
makeBinCspProverOp cspProver_renamingS
cspProver_renamingAltS
cspProver_renamingAltArgPrios
cspProver_renamingAltOpPrio
-- | Conditional operator
cspProver_conditionalOp :: Term -> Term -> Term -> Term
cspProver_conditionalOp =
makeTriCspProverOp cspProver_conditionalS
cspProver_conditionalAltS
cspProver_conditionalAltArgPrios
cspProver_conditionalAltArgOpPrio
-- | Channel non-deterministic send operator
cspProver_chan_nondeterministic_sendOp :: Term -> Term -> Term -> Term -> Term
cspProver_chan_nondeterministic_sendOp =
makeQuadCspProverOp cspProver_chan_nondeterministic_sendS
cspProver_chan_nondeterministic_sendAltS
cspProver_chan_nondeterministic_sendAltArgPrios
cspProver_chan_nondeterministic_sendAltArgOpPrio
-- | Channel send operator
cspProver_chan_sendOp :: Term -> Term -> Term -> Term
cspProver_chan_sendOp =
makeTriCspProverOp cspProver_chan_sendS
cspProver_chan_sendAltS
cspProver_chan_sendAltArgPrios
cspProver_chan_sendAltArgOpPrio
-- | Channel receive operator
cspProver_chan_recOp :: Term -> Term -> Term -> Term -> Term
cspProver_chan_recOp =
makeQuadCspProverOp cspProver_chan_recS
cspProver_chan_recAltS
cspProver_chan_recAltArgPrios
cspProver_chan_recAltArgOpPrio
{- | Create an Isabelle Term representing a (Unary) CspProver operator
with no alternative syntax -}
makeCspProverOpNoAlt :: String -> Term
makeCspProverOpNoAlt opName =
con (VName opName Nothing)
{- | Create an Isabelle Term representing a CspProver operator with
alternative syntax for a single parameter -}
makeUnaryCspProverOp :: String -> String -> [Int] -> Int -> Term -> Term
makeUnaryCspProverOp opName altSyntax altArgPrios altOpPrio t1 =
let vname = VName opName $ Just $ AltSyntax altSyntax altArgPrios altOpPrio
in termAppl (con vname) t1
{- | Create an Isabelle Term representing a CspProver operator with
alternative syntax for two parameters -}
makeBinCspProverOp :: String -> String -> [Int] -> Int -> Term -> Term -> Term
makeBinCspProverOp opName altSyntax altArgPrios altOpPrio t1 t2 =
let vname = VName opName $ Just $ AltSyntax altSyntax altArgPrios altOpPrio
in binVNameAppl vname t1 t2
{- | Create an Isabelle Term representing a CspProver operator (with 3
parameters) with alternative syntax -}
makeTriCspProverOp :: String -> String -> [Int] -> Int -> Term -> Term ->
Term -> Term
makeTriCspProverOp opName altSyntax altArgPrios altOpPrio t1 t2 t3 =
let vname = VName opName $ Just $ AltSyntax altSyntax altArgPrios altOpPrio
in termAppl (binVNameAppl vname t1 t2) t3
{- | Create an Isabelle Term representing a CspProver operator (with 4
parameters) with alternative syntax -}
makeQuadCspProverOp :: String -> String -> [Int] -> Int -> Term -> Term ->
Term -> Term -> Term
makeQuadCspProverOp opName altSyntax altArgPrios altOpPrio t1 t2 t3 t4 =
let vname = VName opName $ Just $ AltSyntax altSyntax altArgPrios altOpPrio
in termAppl (termAppl (binVNameAppl vname t1 t2) t3) t4
| spechub/Hets | CspCASLProver/CspProverConsts.hs | gpl-2.0 | 16,541 | 0 | 12 | 3,014 | 2,097 | 1,203 | 894 | 309 | 1 |
module Sound.Tidal.Chords where
{-
Chords.hs - For .. chords
Copyright (C) 2020, Alex McLean and contributors
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This library 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 library. If not, see <http://www.gnu.org/licenses/>.
-}
import Data.Maybe
import Sound.Tidal.Pattern
-- major chords
major :: Num a => [a]
major = [0,4,7]
aug :: Num a => [a]
aug = [0,4,8]
six :: Num a => [a]
six = [0,4,7,9]
sixNine :: Num a => [a]
sixNine = [0,4,7,9,14]
major7 :: Num a => [a]
major7 = [0,4,7,11]
major9 :: Num a => [a]
major9 = [0,4,7,11,14]
add9 :: Num a => [a]
add9 = [0,4,7,14]
major11 :: Num a => [a]
major11 = [0,4,7,11,14,17]
add11 :: Num a => [a]
add11 = [0,4,7,17]
major13 :: Num a => [a]
major13 = [0,4,7,11,14,21]
add13 :: Num a => [a]
add13 = [0,4,7,21]
-- dominant chords
dom7 :: Num a => [a]
dom7 = [0,4,7,10]
dom9 :: Num a => [a]
dom9 = [0,4,7,14]
dom11 :: Num a => [a]
dom11 = [0,4,7,17]
dom13 :: Num a => [a]
dom13 = [0,4,7,21]
sevenFlat5 :: Num a => [a]
sevenFlat5 = [0,4,6,10]
sevenSharp5 :: Num a => [a]
sevenSharp5 = [0,4,8,10]
sevenFlat9 :: Num a => [a]
sevenFlat9 = [0,4,7,10,13]
nine :: Num a => [a]
nine = [0,4,7,10,14]
eleven :: Num a => [a]
eleven = [0,4,7,10,14,17]
thirteen :: Num a => [a]
thirteen = [0,4,7,10,14,17,21]
-- minor chords
minor :: Num a => [a]
minor = [0,3,7]
diminished :: Num a => [a]
diminished = [0,3,6]
minorSharp5 :: Num a => [a]
minorSharp5 = [0,3,8]
minor6 :: Num a => [a]
minor6 = [0,3,7,9]
minorSixNine :: Num a => [a]
minorSixNine = [0,3,9,7,14]
minor7flat5 :: Num a => [a]
minor7flat5 = [0,3,6,10]
minor7 :: Num a => [a]
minor7 = [0,3,7,10]
minor7sharp5 :: Num a => [a]
minor7sharp5 = [0,3,8,10]
minor7flat9 :: Num a => [a]
minor7flat9 = [0,3,7,10,13]
minor7sharp9 :: Num a => [a]
minor7sharp9 = [0,3,7,10,14]
diminished7 :: Num a => [a]
diminished7 = [0,3,6,9]
minor9 :: Num a => [a]
minor9 = [0,3,7,10,14]
minor11 :: Num a => [a]
minor11 = [0,3,7,10,14,17]
minor13 :: Num a => [a]
minor13 = [0,3,7,10,14,17,21]
-- other chords
one :: Num a => [a]
one = [0]
five :: Num a => [a]
five = [0,7]
sus2 :: Num a => [a]
sus2 = [0,2,7]
sus4 :: Num a => [a]
sus4 = [0,5,7]
sevenSus2 :: Num a => [a]
sevenSus2 = [0,2,7,10]
sevenSus4 :: Num a => [a]
sevenSus4 = [0,5,7,10]
nineSus4 :: Num a => [a]
nineSus4 = [0,5,7,10,14]
-- questionable chords
sevenFlat10 :: Num a => [a]
sevenFlat10 = [0,4,7,10,15]
nineSharp5 :: Num a => [a]
nineSharp5 = [0,1,13]
minor9sharp5 :: Num a => [a]
minor9sharp5 = [0,1,14]
sevenSharp5flat9 :: Num a => [a]
sevenSharp5flat9 = [0,4,8,10,13]
minor7sharp5flat9 :: Num a => [a]
minor7sharp5flat9 = [0,3,8,10,13]
elevenSharp :: Num a => [a]
elevenSharp = [0,4,7,10,14,18]
minor11sharp :: Num a => [a]
minor11sharp = [0,3,7,10,14,18]
-- | @chordate cs m n@ selects the @n@th "chord" (a chord is a list of Ints)
-- from a list of chords @cs@ and transposes it by @m@
-- chordate :: Num b => [[b]] -> b -> Int -> [b]
-- chordate cs m n = map (+m) $ cs!!n
-- | @enchord chords pn pc@ turns every note in the note pattern @pn@ into
-- a chord, selecting from the chord lists @chords@ using the index pattern
-- @pc@. For example, @Chords.enchord [Chords.major Chords.minor] "c g" "0 1"@
-- will create a pattern of a C-major chord followed by a G-minor chord.
-- enchord :: Num a => [[a]] -> Pattern a -> Pattern Int -> Pattern a
-- enchord chords pn pc = flatpat $ (chordate chords) <$> pn <*> pc
chordTable :: Num a => [(String, [a])]
chordTable = [("major", major),
("maj", major),
("M", major),
("aug", aug),
("plus", aug),
("sharp5", aug),
("six", six),
("6", six),
("sixNine", sixNine),
("six9", sixNine),
("sixby9", sixNine),
("6by9", sixNine),
("major7", major7),
("maj7", major7),
("major9", major9),
("maj9", major9),
("add9", add9),
("major11", major11),
("maj11", major11),
("add11", add11),
("major13", major13),
("maj13", major13),
("add13", add13),
("dom7", dom7),
("dom9", dom9),
("dom11", dom11),
("dom13", dom13),
("sevenFlat5", sevenFlat5),
("7f5", sevenFlat5),
("sevenSharp5", sevenSharp5),
("7s5", sevenSharp5),
("sevenFlat9", sevenFlat9),
("7f9", sevenFlat9),
("nine", nine),
("eleven", eleven),
("11", eleven),
("thirteen", thirteen),
("13", thirteen),
("minor", minor),
("min", minor),
("m", minor),
("diminished", diminished),
("dim", diminished),
("minorSharp5", minorSharp5),
("msharp5", minorSharp5),
("mS5", minorSharp5),
("minor6", minor6),
("min6", minor6),
("m6", minor6),
("minorSixNine", minorSixNine),
("minor69", minorSixNine),
("min69", minorSixNine),
("minSixNine", minorSixNine),
("m69", minorSixNine),
("mSixNine", minorSixNine),
("m6by9", minorSixNine),
("minor7flat5", minor7flat5),
("minor7f5", minor7flat5),
("min7flat5", minor7flat5),
("min7f5", minor7flat5),
("m7flat5", minor7flat5),
("m7f5", minor7flat5),
("minor7", minor7),
("min7", minor7),
("m7", minor7),
("minor7sharp5", minor7sharp5),
("minor7s5", minor7sharp5),
("min7sharp5", minor7sharp5),
("min7s5", minor7sharp5),
("m7sharp5", minor7sharp5),
("m7s5", minor7sharp5),
("minor7flat9", minor7flat9),
("minor7f9", minor7flat9),
("min7flat9", minor7flat9),
("min7f9", minor7flat9),
("m7flat9", minor7flat9),
("m7f9", minor7flat9),
("minor7sharp9", minor7sharp9),
("minor7s9", minor7sharp9),
("min7sharp9", minor7sharp9),
("min7s9", minor7sharp9),
("m7sharp9", minor7sharp9),
("m7s9", minor7sharp9),
("diminished7", diminished7),
("dim7", diminished7),
("minor9", minor9),
("min9", minor9),
("m9", minor9),
("minor11", minor11),
("min11", minor11),
("m11", minor11),
("minor13", minor13),
("min13", minor13),
("m13", minor13),
("one", one),
("1", one),
("five", five),
("5", five),
("sus2", sus2),
("sus4", sus4),
("sevenSus2", sevenSus2),
("7sus2", sevenSus2),
("sevenSus4", sevenSus4),
("7sus4", sevenSus4),
("nineSus4", nineSus4),
("ninesus4", nineSus4),
("9sus4", nineSus4),
("sevenFlat10", sevenFlat10),
("7f10", sevenFlat10),
("nineSharp5", nineSharp5),
("9sharp5", nineSharp5),
("9s5", nineSharp5),
("minor9sharp5", minor9sharp5),
("minor9s5", minor9sharp5),
("min9sharp5", minor9sharp5),
("min9s5", minor9sharp5),
("m9sharp5", minor9sharp5),
("m9s5", minor9sharp5),
("sevenSharp5flat9", sevenSharp5flat9),
("7s5f9", sevenSharp5flat9),
("minor7sharp5flat9", minor7sharp5flat9),
("m7sharp5flat9", minor7sharp5flat9),
("elevenSharp", elevenSharp),
("11s", elevenSharp),
("minor11sharp", minor11sharp),
("m11sharp", minor11sharp),
("m11s", minor11sharp)
]
chordL :: Num a => Pattern String -> Pattern [a]
chordL p = (\name -> fromMaybe [] $ lookup name chordTable) <$> p
chordList :: String
chordList = unwords $ map fst (chordTable :: [(String, [Int])])
| bgold-cosmos/Tidal | src/Sound/Tidal/Chords.hs | gpl-3.0 | 8,852 | 0 | 10 | 2,852 | 2,918 | 1,821 | 1,097 | 233 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.CognitoIdentity.UpdateIdentityPool
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates a user pool.
--
-- You must use AWS Developer credentials to call this API.
--
-- /See:/ <http://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_UpdateIdentityPool.html AWS API Reference> for UpdateIdentityPool.
module Network.AWS.CognitoIdentity.UpdateIdentityPool
(
-- * Creating a Request
updateIdentityPool
, UpdateIdentityPool
-- * Request Lenses
, uipSupportedLoginProviders
, uipDeveloperProviderName
, uipOpenIdConnectProviderARNs
, uipIdentityPoolId
, uipIdentityPoolName
, uipAllowUnauthenticatedIdentities
-- * Destructuring the Response
, identityPool
, IdentityPool
-- * Response Lenses
, ipSupportedLoginProviders
, ipDeveloperProviderName
, ipOpenIdConnectProviderARNs
, ipIdentityPoolId
, ipIdentityPoolName
, ipAllowUnauthenticatedIdentities
) where
import Network.AWS.CognitoIdentity.Types
import Network.AWS.CognitoIdentity.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | An object representing a Cognito identity pool.
--
-- /See:/ 'updateIdentityPool' smart constructor.
data UpdateIdentityPool = UpdateIdentityPool'
{ _uipSupportedLoginProviders :: !(Maybe (Map Text Text))
, _uipDeveloperProviderName :: !(Maybe Text)
, _uipOpenIdConnectProviderARNs :: !(Maybe [Text])
, _uipIdentityPoolId :: !Text
, _uipIdentityPoolName :: !Text
, _uipAllowUnauthenticatedIdentities :: !Bool
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'UpdateIdentityPool' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'uipSupportedLoginProviders'
--
-- * 'uipDeveloperProviderName'
--
-- * 'uipOpenIdConnectProviderARNs'
--
-- * 'uipIdentityPoolId'
--
-- * 'uipIdentityPoolName'
--
-- * 'uipAllowUnauthenticatedIdentities'
updateIdentityPool
:: Text -- ^ 'uipIdentityPoolId'
-> Text -- ^ 'uipIdentityPoolName'
-> Bool -- ^ 'uipAllowUnauthenticatedIdentities'
-> UpdateIdentityPool
updateIdentityPool pIdentityPoolId_ pIdentityPoolName_ pAllowUnauthenticatedIdentities_ =
UpdateIdentityPool'
{ _uipSupportedLoginProviders = Nothing
, _uipDeveloperProviderName = Nothing
, _uipOpenIdConnectProviderARNs = Nothing
, _uipIdentityPoolId = pIdentityPoolId_
, _uipIdentityPoolName = pIdentityPoolName_
, _uipAllowUnauthenticatedIdentities = pAllowUnauthenticatedIdentities_
}
-- | Optional key:value pairs mapping provider names to provider app IDs.
uipSupportedLoginProviders :: Lens' UpdateIdentityPool (HashMap Text Text)
uipSupportedLoginProviders = lens _uipSupportedLoginProviders (\ s a -> s{_uipSupportedLoginProviders = a}) . _Default . _Map;
-- | The \"domain\" by which Cognito will refer to your users.
uipDeveloperProviderName :: Lens' UpdateIdentityPool (Maybe Text)
uipDeveloperProviderName = lens _uipDeveloperProviderName (\ s a -> s{_uipDeveloperProviderName = a});
-- | A list of OpendID Connect provider ARNs.
uipOpenIdConnectProviderARNs :: Lens' UpdateIdentityPool [Text]
uipOpenIdConnectProviderARNs = lens _uipOpenIdConnectProviderARNs (\ s a -> s{_uipOpenIdConnectProviderARNs = a}) . _Default . _Coerce;
-- | An identity pool ID in the format REGION:GUID.
uipIdentityPoolId :: Lens' UpdateIdentityPool Text
uipIdentityPoolId = lens _uipIdentityPoolId (\ s a -> s{_uipIdentityPoolId = a});
-- | A string that you provide.
uipIdentityPoolName :: Lens' UpdateIdentityPool Text
uipIdentityPoolName = lens _uipIdentityPoolName (\ s a -> s{_uipIdentityPoolName = a});
-- | TRUE if the identity pool supports unauthenticated logins.
uipAllowUnauthenticatedIdentities :: Lens' UpdateIdentityPool Bool
uipAllowUnauthenticatedIdentities = lens _uipAllowUnauthenticatedIdentities (\ s a -> s{_uipAllowUnauthenticatedIdentities = a});
instance AWSRequest UpdateIdentityPool where
type Rs UpdateIdentityPool = IdentityPool
request = postJSON cognitoIdentity
response = receiveJSON (\ s h x -> eitherParseJSON x)
instance ToHeaders UpdateIdentityPool where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("AWSCognitoIdentityService.UpdateIdentityPool" ::
ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON UpdateIdentityPool where
toJSON UpdateIdentityPool'{..}
= object
(catMaybes
[("SupportedLoginProviders" .=) <$>
_uipSupportedLoginProviders,
("DeveloperProviderName" .=) <$>
_uipDeveloperProviderName,
("OpenIdConnectProviderARNs" .=) <$>
_uipOpenIdConnectProviderARNs,
Just ("IdentityPoolId" .= _uipIdentityPoolId),
Just ("IdentityPoolName" .= _uipIdentityPoolName),
Just
("AllowUnauthenticatedIdentities" .=
_uipAllowUnauthenticatedIdentities)])
instance ToPath UpdateIdentityPool where
toPath = const "/"
instance ToQuery UpdateIdentityPool where
toQuery = const mempty
| fmapfmapfmap/amazonka | amazonka-cognito-identity/gen/Network/AWS/CognitoIdentity/UpdateIdentityPool.hs | mpl-2.0 | 6,088 | 0 | 13 | 1,309 | 816 | 487 | 329 | 108 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- Module : Khan.Internal.Orphans
-- Copyright : (c) 2013 Brendan Hay <[email protected]>
-- 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 <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
module Khan.Internal.Orphans where
import Data.Aeson
import Data.Hashable
import Data.SemVer (Version)
import qualified Data.SemVer as Ver
import qualified Data.Text as Text
import Data.Text.Buildable
import qualified Data.Text.Lazy as LText
import GHC.Generics (Generic)
import Khan.Prelude
import Network.AWS.EC2
instance Buildable [Text] where
build = build . Text.intercalate ", "
instance Buildable [LText.Text] where
build = build . LText.intercalate ", "
instance Buildable FilePath where
build = build . toTextIgnore
instance Buildable Version where
build = build . Ver.toText
instance ToJSON Version where
toJSON = toJSON . Ver.toText
instance ToJSON InstanceType where
toJSON = toJSON . show
instance ToJSON AvailabilityZone where
toJSON = toJSON . show
deriving instance Generic Region
instance Hashable Region
| zinfra/khan | khan/src/Khan/Internal/Orphans.hs | mpl-2.0 | 1,691 | 0 | 8 | 424 | 250 | 149 | 101 | 33 | 0 |
{--------------------------------------------------------------------------------
Camel game by Maarten Löfler ([email protected]) (adapted by Daan Leijen).
--------------------------------------------------------------------------------}
module Main where
import Graphics.UI.WX
import Graphics.UI.WXCore
import Paths_samplesContrib
{--------------------------------------------------------------------------------
The game
--------------------------------------------------------------------------------}
type Board = [Field]
data Field = Full Camel | Empty deriving Eq
data Camel = East | West deriving Eq
newBoard :: Int -> Board
newBoard x | even x = error "board size must be odd"
| x < 3 = error "board size must be at least 3"
| otherwise = let c = x `div` 2
in replicate c (Full East) ++ Empty : replicate c (Full West)
correct :: Board -> Bool
correct fs = let c = length fs `div` 2
in all (== Full West) (take c fs)
&& all (== Full East) (drop (c + 1) fs)
(|>) :: Int -> Field -> Board -> Board
(|>) _ _ [] = []
(|>) 0 f (_:bs) = f : bs
(|>) x f (b:bs) = b : (|>) (x - 1) f bs
moveAllowed :: Int -> Board -> Bool
moveAllowed x b | x < 0 = False
| x >= length b = False
| b !! x == Empty = False
| otherwise = case b !! x of Full East | x >= length b - 1 -> False
| b !! (x + 1) == Empty -> True
| b !! (x + 1) == Full East -> False
| x >= length b - 2 -> False
| b !! (x + 2) == Empty -> True
| otherwise -> False
Full West | x < 1 -> False
| b !! (x - 1) == Empty -> True
| b !! (x - 1) == Full West -> False
| x < 2 -> False
| b !! (x - 2) == Empty -> True
| otherwise -> False
Empty -> False
move :: Int -> Board -> Board
move x b = case b !! x of Full East -> case b !! (x + 1) of Empty -> (x |> Empty) . ((x + 1) |> Full East) $ b
_ -> (x |> Empty) . ((x + 2) |> Full East) $ b
Full West -> case b !! (x - 1) of Empty -> (x |> Empty) . ((x - 1) |> Full West) $ b
_ -> (x |> Empty) . ((x - 2) |> Full West) $ b
_ -> b
{--------------------------------------------------------------------------------
The GUI
--------------------------------------------------------------------------------}
main :: IO ()
main = start gui
gui :: IO ()
gui
= do desert <- varCreate (newBoard 3)
imagePath <- getDataFileName "bitmaps/desert.bmp"
b <- bitmapCreateLoad imagePath wxBITMAP_TYPE_BMP
f <- frame [ text := "Camels", on closing := do bitmapDelete b; propagateEvent ]
q <- button f [ text := "quit" , on command := close f ]
h <- button f [ text := "help" , on command := chelp f ]
a <- button f [ text := "about", on command := about f ]
p <- panel f [ clientSize := sz 320 240 ]
set p [ on resize := repaint p
, on click := klik p desert
, on paint := drawDesert desert b
]
set f [ layout := column 0
[ fill $ widget p
, hfloatCentre $ margin 5 $ row 5 [widget q, widget h, widget a]
]
, defaultButton := q
]
return ()
drawDesert :: Var Board -> Bitmap () -> DC () -> Rect -> IO ()
drawDesert desert bmp dc (Rect x y w h) =
do drawBitmap dc bmp pointZero False []
for 0 (w `div` 234) (\i ->
for 0 (h `div` 87) (\j ->
drawBitmap dc bmp (pt (i * 234) (j * 87)) False []))
board <- varGet desert
let l = length board
s = min h $ w `div` l
xd = x + (w - l * s) `div` 2
yd = y + (h - s) `div` 2
for 0 (l - 1) (\i -> drawField dc (board !! i) (Rect (xd + i * s) yd s s))
return ()
for :: Int -> Int -> (Int -> IO ()) -> IO ()
for x y f = sequence_ $ map f [x..y]
drawField :: DC () -> Field -> Rect -> IO ()
drawField dc f r@(Rect _x _y _w _h) =
do set dc [brushKind := BrushSolid, brushColor := rgb 0x80 0x80 (0x00 :: Int)]
case f of Full East -> do polygon dc (map (lin r) camel) []
polygon dc (map (lin r) saddle) [brushColor := red]
Full West -> do polygon dc (map (lin r . mirror) camel) []
polygon dc (map (lin r . mirror) saddle) [brushColor := blue]
_ -> return ()
camel :: [(Float, Float)]
camel = map (\(x, y) -> (x / 8, y / 8)) [(2, 2), (3, 3), (4, 2), (5, 3), (6, 2), (7, 3), (6, 3), (5, 5), (5, 7), (4, 7), (4, 5), (3, 5), (3, 7), (2, 7), (2, 4), (1, 6), (1, 4)]
saddle :: [(Float, Float)]
saddle = map (\(x, y) -> (x / 8, y / 8)) [(4, 2), (5, 3), (4, 4), (3, 3)]
mirror :: (Float, Float) -> (Float, Float)
mirror (x, y) = (1 - x, y)
lin :: Rect -> (Float, Float) -> Point
lin (Rect x y w h) (px, py) = let nx = floor $ (fromInteger . toInteger) w * px
ny = floor $ (fromInteger . toInteger) h * py
in Point (x + nx) (y + ny)
klik :: Panel () -> Var Board -> Point -> IO ()
klik pan desert (Point x _y) =
do board <- varGet desert
(Size w h) <- get pan clientSize
let l = length board
s = min h $ w `div` l
xd = (w - l * s) `div` 2
_yd = (h - s) `div` 2
i = (x - xd) `div` s
_ <- varUpdate desert (if moveAllowed i board then move i else id)
newboard <- varGet desert
repaint pan
eind pan desert newboard
return ()
eind :: Panel () -> Var Board -> Board -> IO ()
eind pan desert board
| any (flip moveAllowed board) [0 .. length board - 1] = return ()
| correct board = do infoDialog pan "Level up" "Congratulations! You succeeded."
_ <- varUpdate desert (const $ newBoard $ length board + 2)
repaint pan
| otherwise = do infoDialog pan "Level restart" "There are no more possible moves..."
_ <- varUpdate desert (const $ newBoard $ max 3 $ length board)
repaint pan
about :: Window a -> IO ()
about w
= infoDialog w "About Camels" "Camels\n\nby Maarten Löfler\[email protected]\n\nCamels was written using wxHaskell"
chelp :: Window a -> IO ()
chelp w
= infoDialog w "Camels Help"
( "How to play Camels\n\n"
++ "The object of this puzzle is to move all the east looking camels to the eastern\n"
++ "end of the desert, and all the west looking camels to the west of the desert.\n"
++ "East looking camels can only move east, and west looking camels can only move\n"
++ "west. A camel can move one square forward (if that square is empty), or it can\n"
++ "jump over another camel if it is looking the OTHER way.\n\n"
++ "Once you succeed, you will advance to a higher level with more camels.\n\n"
++ "Good luck!\n"
)
| jacekszymanski/wxHaskell | samples/contrib/Camels.hs | lgpl-2.1 | 7,749 | 0 | 17 | 3,058 | 2,895 | 1,479 | 1,416 | 133 | 5 |
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Handler.Root
( getRootR
, getPageR
, getStaticContentR
) where
import Wiki
import Handler.Topic (getTopicR')
import Text.Hamlet (hamlet)
import Util (renderContent)
getRootR :: Handler RepHtml
getRootR = do
mpage <- runDB $ getBy $ UniquePage ""
mcontent <-
case mpage of
Nothing -> return Nothing
Just (_, Page { pageTopic = tid }) -> runDB $ do
x <- selectList [TopicContentTopic ==. tid] [Desc TopicContentChanged, LimitTo 1]
case x of
[] -> return Nothing
(_, TopicContent {..}):_ -> return $ Just (topicContentFormat, topicContentContent, tid)
let html' =
case mcontent of
Nothing -> [hamlet|
<h1>No homepage set.
<p>The site admin has no yet set a homepage topic.
|]
Just (format, content, tid) -> renderContent tid format content
defaultLayout $ addHamlet html'
getPageR :: Text -> Handler RepHtml
getPageR t = do
p <- runDB $ getBy404 (UniquePage t)
getTopicR' (return ()) False $ pageTopic $ snd p
getStaticContentR :: StaticContentId -> Handler StaticContent
getStaticContentR = runDB . get404
| snoyberg/yesodwiki | Handler/Root.hs | bsd-2-clause | 1,301 | 0 | 20 | 359 | 362 | 187 | 175 | 32 | 4 |
{-# LANGUAGE TemplateHaskell, TypeOperators, GADTs, KindSignatures #-}
{-# LANGUAGE ViewPatterns, PatternGuards, LambdaCase #-}
{-# LANGUAGE FlexibleContexts, ConstraintKinds #-}
{-# LANGUAGE MagicHash, CPP #-}
{-# OPTIONS_GHC -Wall #-}
-- TODO: Restore the following pragmas
{-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP
{-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TEMP
----------------------------------------------------------------------
-- |
-- Module : LambdaCCC.ReifyLambda
-- Copyright : (c) 2013 Tabula, Inc.
-- LICENSE : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Reify a Core expression into GADT
----------------------------------------------------------------------
module LambdaCCC.ReifyLambda
( plugin
) where
import Data.Functor ((<$>))
import Control.Applicative (Applicative(..))
-- import Control.Monad ((<=<),liftM2)
import Control.Arrow (arr,(>>>))
import Data.List (intercalate)
import qualified Data.Map as M
import qualified Data.Set as S
import Data.Maybe (fromMaybe)
import Text.Printf (printf)
-- import qualified Language.Haskell.TH as TH (Name) -- ,mkName
-- import qualified Language.Haskell.TH.Syntax as TH (showName)
-- GHC API
-- import PrelNames (unitTyConKey,boolTyConKey,intTyConKey)
import qualified Language.KURE.Translate as Kure
import HERMIT.Monad (HermitM,newIdH)
import HERMIT.Context
(ReadBindings(..),hermitBindings,HermitBinding(..),HermitBindingSite(..)
,lookupHermitBinding,boundIn,BoundVars,HasGlobalRdrEnv(..)) -- ,AddBindings
import HERMIT.Core (Crumb(..),localFreeIdsExpr)
import HERMIT.External
import HERMIT.GHC hiding (mkStringExpr)
import HERMIT.Kure hiding (apply)
import HERMIT.Plugin
-- Note: All of the Dictionary submodules are now re-exported by HERMIT.Dictionary,
-- so if you prefer you could import all these via that module, rather than seperately.
import HERMIT.Dictionary.AlphaConversion (unshadowR)
import HERMIT.Dictionary.Common
import HERMIT.Dictionary.Composite (simplifyR)
import HERMIT.Dictionary.Debug (observeR)
import HERMIT.Dictionary.Rules (rulesR) -- ruleR,
import HERMIT.Dictionary.Inline (inlineNameR) -- , inlineNamesR
import HERMIT.Dictionary.Local (letIntroR,letFloatArgR,letFloatTopR)
import HERMIT.Dictionary.Navigation (rhsOfT,parentOfT,bindingGroupOfT)
-- import HERMIT.Dictionary.Composite (simplifyR)
import HERMIT.Dictionary.Unfold (cleanupUnfoldR) -- unfoldNameR,
import LambdaCCC.Misc (Unop) -- ,Binop
-- import qualified LambdaCCC.Ty as T
-- import qualified Circat.Prim as P
-- import qualified LambdaCCC.Lambda as E
-- import LambdaCCC.MkStringExpr (mkStringExpr)
{--------------------------------------------------------------------
Core utilities
--------------------------------------------------------------------}
apps :: Id -> [Type] -> [CoreExpr] -> CoreExpr
apps f ts es
| tyArity f /= length ts =
error $ printf "apps: Id %s wants %d type arguments but got %d."
(var2String f) arity ntys
| otherwise = mkCoreApps (varToCoreExpr f) (map Type ts ++ es)
where
arity = tyArity f
ntys = length ts
tyArity :: Id -> Int
tyArity = length . fst . splitForAllTys . varType
{-
listToPair :: [a] -> Maybe (a,a)
listToPair [a,b] = Just (a,b)
listToPair _ = Nothing
unTuple :: CoreExpr -> Maybe [CoreExpr]
unTuple expr@(App {})
| (Var f, dropWhile isTypeArg -> valArgs) <- collectArgs expr
, Just dc <- isDataConWorkId_maybe f
, isTupleTyCon (dataConTyCon dc) && (valArgs `lengthIs` idArity f)
= Just valArgs
unTuple _ = Nothing
unPair :: CoreExpr -> Maybe (CoreExpr,CoreExpr)
unPair = listToPair <=< unTuple
-}
-- TODO: Maybe remove unPair and unPairTy, since it's just as easy to use
-- unTuple and pattern-match against Just [a,b].
{-
-- Unsafe way to ppr in pure code.
tr :: Outputable a => a -> a
tr x = trace ("tr: " ++ pretty x) x
pretty :: Outputable a => a -> String
pretty = showPpr tracingDynFlags
pretties :: Outputable a => [a] -> String
pretties = intercalate "," . map pretty
-}
-- | Variant of GHC's 'collectArgs'
collectTypeArgs :: CoreExpr -> ([Type], CoreExpr)
collectTypeArgs expr = go [] expr
where
go ts (App f (Type t)) = go (t:ts) f
go ts e = (reverse ts, e)
collectForalls :: Type -> ([Var], Type)
collectForalls ty = go [] ty
where
go vs (ForAllTy v t') = go (v:vs) t'
go vs t = (reverse vs, t)
-- TODO: Rewrite collectTypeArgs and collectForalls as unfolds and refactor.
#if 0
unTupleTy :: Type -> Maybe [Type]
unTupleTy (TyConApp tc tys)
| isTupleTyCon tc && tyConArity tc == length tys = Just tys
unTupleTy _ = Nothing
-- unPairTy :: Type -> Maybe (Type,Type)
-- unPairTy = listToPair <=< unTupleTy
-- For a given tycon, drop it from a unary type application. Error otherwise.
-- WARNING: I'm not yet checking for a tycon match. TODO: check.
dropTyApp1 :: TH.Name -> Type -> Type
dropTyApp1 _ (TyConApp _ [t]) = t
dropTyApp1 _ _ = error "dropTyApp1: not a unary TyConApp"
#endif
-- Substitute a new subexpression for a variable in an expression
subst1 :: (Id,CoreExpr) -> CoreExpr -> CoreExpr
subst1 (v,new) = substExpr (error "subst1: no SDoc")
(extendIdSubst emptySubst v new)
{--------------------------------------------------------------------
KURE utilities
--------------------------------------------------------------------}
-- -- | Transformation while focused on a path
-- pathIn :: (Eq crumb, ReadPath c crumb, MonadCatch m, Walker c b) =>
-- Translate c m b (Path crumb) -> Unop (Rewrite c m b)
-- pathIn mkP f = mkP >>= flip pathR f
-- | Transformation while focused on a snoc path
snocPathIn :: ( Eq crumb, Functor m, ReadPath c crumb
, MonadCatch m, Walker c b ) =>
Translate c m b (SnocPath crumb) -> Unop (Rewrite c m b)
snocPathIn mkP r = mkP >>= flip localPathR r
{--------------------------------------------------------------------
HERMIT utilities
--------------------------------------------------------------------}
-- Next two from Andy G:
-- | Lookup the name in the context first, then, failing that, in GHC's global
-- reader environment.
findTyConT :: ( BoundVars c, HasGlobalRdrEnv c, HasDynFlags m
, MonadThings m, MonadCatch m) =>
String -> Translate c m a TyCon
findTyConT nm = prefixFailMsg ("Cannot resolve name " ++ nm ++ ", ") $
contextonlyT (findTyConMG nm)
findTyConMG :: (BoundVars c, HasGlobalRdrEnv c, HasDynFlags m, MonadThings m) => String -> c -> m TyCon
findTyConMG nm c =
case filter isTyConName $ findNamesFromString (hermitGlobalRdrEnv c) nm of
[n] -> lookupTyCon n
ns -> do dynFlags <- getDynFlags
fail $ "multiple matches found:\n" ++ intercalate ", " (map (showPpr dynFlags) ns)
#if 0
-- | Translate a pair expression.
pairT :: (Monad m, ExtendPath c Crumb) =>
Translate c m CoreExpr a -> Translate c m CoreExpr b
-> (Type -> Type -> a -> b -> z) -> Translate c m CoreExpr z
pairT tu tv f = translate $ \ c ->
\ case (unPair -> Just (u,v)) ->
liftM2 (f (exprType u) (exprType v))
(Kure.apply tu (c @@ App_Fun @@ App_Arg) u)
(Kure.apply tv (c @@ App_Arg) v)
_ -> fail "not a pair node."
-- | Translate an n-ary type-instantiation of a variable, where n >= 0.
appVTysT :: (ExtendPath c Crumb, Monad m) =>
Translate c m Var a -> (a -> [Type] -> b) -> Translate c m CoreExpr b
appVTysT tv h = translate $ \c ->
\ case (collectTypeArgs -> (ts, Var v)) ->
liftM2 h (Kure.apply tv (applyN (length ts) (@@ App_Fun) c) v)
(return ts)
_ -> fail "not an application of a variable to types."
where
applyN :: Int -> (a -> a) -> a -> a
applyN n f a = foldr ($) a (replicate n f)
#endif
defR :: RewriteH Id -> RewriteH CoreExpr -> RewriteH Core
defR rewI rewE = prunetdR ( promoteDefR (defAllR rewI rewE)
<+ promoteBindR (nonRecAllR rewI rewE) )
rhsR :: RewriteH CoreExpr -> RewriteH Core
rhsR = defR idR
-- unfoldNames :: [TH.Name] -> RewriteH CoreExpr
-- unfoldNames nms = catchesM (unfoldNameR <$> nms) -- >>> cleanupUnfoldR
-- The set of variables in a HERMIT context
isLocal :: ReadBindings c => c -> (Var -> Bool)
isLocal = flip boundIn
-- | Extract just the lambda-bound variables in a HERMIT context
isLocalT :: (ReadBindings c, Applicative m) => Translate c m a (Var -> Bool)
isLocalT = contextonlyT (pure . isLocal)
-- topLevelBindsR :: (ExtendPath c Crumb, AddBindings c, MonadCatch m) =>
-- Rewrite c m CoreBind -> Rewrite c m ModGuts
-- topLevelBindsR r = modGutsR progBindsR
-- where
-- progBindsR = progConsAnyR r progBindsR
-- topLevelBindsR r = modGutsR (fix (progConsAnyR r))
type InCoreTC t = Injection t CoreTC
observing :: Bool
observing = False
observeR' :: InCoreTC t => String -> RewriteH t
observeR' | observing = observeR
| otherwise = const idR
tries :: (InCoreTC a, InCoreTC t) => [(String,TranslateH a t)] -> TranslateH a t
tries = foldr (<+) (observeR "Unhandled" >>> fail "unhandled")
. map (uncurry labeled)
labeled :: InCoreTC t => String -> Unop (TranslateH a t)
labeled label = (>>> observeR' label)
{--------------------------------------------------------------------
Reification
--------------------------------------------------------------------}
#if 0
type ReType = TranslateH Type CoreExpr
-- | Translate a Core type t into a core expression that evaluates to a Ty t.
reifyType :: ReType
reifyType =
do funTId <- findIdT '(T.:=>)
pairTId <- findIdT '(T.:*)
unitTId <- findIdT 'T.Unit
intTID <- findIdT 'T.Int
boolTID <- findIdT 'T.Bool
let simples :: M.Map Unique Id
simples = M.fromList [ (unitTyConKey,unitTId),(boolTyConKey,boolTID)
, (intTyConKey,intTID) ]
simpleTId :: TyCon -> Maybe Id
simpleTId = flip M.lookup simples . getUnique
rew :: ReType
rew = tries [ ("TSimple",rTSimple),("TPair",rTPair)
, ("TFun",rTFun), ("TSynonym",rTSyn) ]
rTSimple, rTPair, rTFun, rTSyn :: ReType
rTSimple = do TyConApp (simpleTId -> Just tid) [] <- idR
return (apps tid [] [])
rTPair = do Just [_,_] <- unTupleTy <$> idR
tyConAppT (pure ()) (const rew) $ \ () [a',b'] ->
tyOp2 pairTId a' b'
rTFun = funTyT rew rew $ tyOp2 funTId
rTSyn = expandSyn >>> rew
expandSyn :: RewriteH Type
expandSyn = do Just t <- tcView <$> idR
return t
tyOp2 :: Id -> Binop CoreExpr
tyOp2 tid a' b' = apps tid [tyTy a',tyTy b'] [a',b']
rew
-- TODO: Look up the ids only once in reifyExpr, not every time 'reifyType' is called.
-- tyConAppT :: (ExtendPath c Crumb, Monad m) =>
-- Translate c m TyCon a1 -> (Int -> Translate c m KindOrType a2)
-- -> (a1 -> [a2] -> b) -> Translate c m Type b
-- The type parameter a of an expression of type Ty a.
tyTy :: CoreExpr -> Type
tyTy = dropTyApp1 ''T.Ty . exprType
#endif
type ReExpr = RewriteH CoreExpr
lamName :: Unop String
lamName = ("LambdaCCC.Lambda." ++)
findIdE :: String -> TranslateH a Id
findIdE = findIdT . lamName
findTyConE :: String -> TranslateH a TyCon
findTyConE = findTyConT . lamName
reifyExpr :: ReExpr
reifyExpr =
do varId# <- findIdE "varP#" -- "var#"
appId <- findIdE "appP" -- "(@^)"
lamvId# <- findIdE "lamvP#" -- "lamv#"
-- casevId# <- findIdE "casevP#" -- "casev#"
evalId <- findIdE "evalEP" -- "evalEP"
reifyId# <- findIdE "reifyEP#" -- "reifyE#"
letId <- findIdE "lettP" -- "lett"
varPatId# <- findIdE "varPat#"
pairPatId <- findIdE ":#"
asPatId# <- findIdE "asPat#"
-- primId# <- findIdT ''P.Prim -- not found! :/
-- testEId <- findIdT "EP"
epTC <- findTyConE "EP"
let reifyRhs :: RewriteH CoreExpr
reifyRhs =
do ty <- arr exprType
let (tyVars,ty') = collectForalls ty
mkEval (collectTyBinders -> (tyVars',body)) =
if tyVars == tyVars' then
mkLams tyVars (apps evalId [ty'] [body])
else
error $ "mkEval: type variable mismatch: "
++ show (uqVarName <$> tyVars, uqVarName <$> tyVars')
-- If I ever get the type variable mismatch error, take a
-- different approach, extracting the type of e' and
-- dropping the EP.
mkEval <$> rew
where
eTy e = TyConApp epTC [e]
eVar :: Var -> HermitM Var
eVar v = newIdH (uqVarName v ++ "E") (eTy (varType v))
rew :: ReExpr
rew = tries [ ("Eval" ,rEval)
, ("Reify",rReify)
, ("AppT" ,rAppT)
, ("Var#" ,rVar#)
, ("LamT" ,rLamT)
, ("App" ,rApp)
, ("Lam#" ,rLam#)
, ("Let" ,rLet)
, ("Case" ,rCase)
]
where
-- rVar# = do local <- isLocalT
-- varT $
-- do v <- idR
-- if local v then
-- return $ apps varId# [varType v] [varLitE v]
-- else
-- fail "rVar: not a lambda-bound variable"
-- reify (eval e) == e
rEval = do (_evalE, [Type _, e]) <- callNameLam "evalEP"
return e
-- Reify non-local variables and their polymorphic instantiations.
rReify = do local <- isLocalT
e@(collectTypeArgs -> (_, Var v)) <- idR
if local v then
fail "rReify: lambda-bound variable"
else
return $ apps reifyId# [exprType e] [e,varLitE v]
rAppT = do App _ (Type _) <- idR -- Type applications
appT rew idR (arr App)
rLamT = do Lam (isTyVar -> True) _ <- idR
lamT idR rew (arr Lam)
rApp = do App (exprType -> funTy) _ <- idR
appT rew rew $ arr $ \ u' v' ->
let (a,b) = splitFunTy funTy in
apps appId [b,a] [u', v'] -- note b,a
#if 0
rLam# = translate $ \ c -> \case
Lam v@(varType -> vty) e ->
do eV <- eVar v
e' <- Kure.apply rew (c @@ Lam_Body) $
subst1 (v, apps evalId [vty] [
apps varId# [vty] [varLitE eV]]) e
return (apps lamvId# [vty, exprType e] [varLitE eV,e'])
_ -> fail "not a lambda."
#else
rLam# = do Lam (varType -> vty) (exprType -> bodyTy) <- idR
lamT idR rew $ arr $ \ v e' ->
apps lamvId# [vty, bodyTy] [varLitE v,e']
#endif
-- TODO: Eliminate rVar#
rVar# :: ReExpr
rVar# = do local <- isLocalT
Var v <- idR
if local v then
return $ apps varId# [varType v] [varLitE v]
else
fail "rVar: not a lambda-bound variable"
#if 0
rLet = do -- only NonRec for now
Let (NonRec (varType -> patTy) _) (exprType -> bodyTy) <- idR
letT reifyBind rew $ \ (patE,rhs') body' ->
apps letId [patTy,bodyTy] [patE,rhs',body']
#else
rLet = toRedex >>> rew
where
toRedex = do Let (NonRec v rhs) body <- idR
return (Lam v body `App` rhs)
#endif
-- For now, handling only single-branch case expressions containing
-- pair patterns. The result will be to form nested lambda patterns in
-- a beta redex.
rCase = do Case (exprType -> scrutT) wild _ [_] <- idR
_ <- observeR' "Reifying case"
caseT rew idR idR (const (reifyAlt wild)) $
\ scrutE' _ bodyT [(patE,rhs)] ->
apps letId [scrutT,bodyT] [patE,scrutE',rhs]
-- Reify a case alternative, yielding a reified pattern and a reified
-- alternative body (RHS).
reifyAlt :: Var -> TranslateH CoreAlt (CoreExpr,CoreExpr)
reifyAlt wild =
do -- Only pair patterns for now
_ <- observeR' "Reifying case alternative"
(DataAlt (isTupleTyCon.dataConTyCon -> True), vars@[_,_], _) <- idR
vPats <- mapM (applyInContextT (labeled "varPatT" varPatT#)) vars
altT idR (const idR) rew $ \ _ _ rhs' ->
let pat = apps pairPatId (varType <$> vars) vPats
pat' | wild `elemVarSet` localFreeIdsExpr rhs'
= -- WARNING: untested as of 2013-07-22
apps asPatId# [varType wild] [varLitE wild,pat]
| otherwise = pat
in
(pat', rhs')
varPatT# :: TranslateH Var CoreExpr
varPatT# = do v <- idR
return $ apps varPatId# [varType v] [varLitE v]
-- Reify a Core binding into a reified pattern and expression.
-- Only handle NonRec bindings for now.
reifyBind :: TranslateH CoreBind (CoreExpr,CoreExpr)
reifyBind = nonRecT varPatT# rew (,)
-- TODO: Literals
do _ <- observeR' "Reifying expression"
reifyRhs
reifyExprC :: RewriteH Core
reifyExprC = tryR unshadowR >>> promoteExprR reifyExpr
-- unshadow since we extract variable names without the uniques
{-
letT :: (ExtendPath c Crumb, AddBindings c, Monad m)
=> Translate c m CoreBind a1
-> Translate c m CoreExpr a2
-> (a1 -> a2 -> b)
-> Translate c m CoreExpr b
caseT :: (ExtendPath c Crumb, AddBindings c, Monad m)
=> Translate c m CoreExpr e
-> Translate c m Id w
-> Translate c m Type ty
-> (Int -> Translate c m CoreAlt alt)
-> (e -> w -> ty -> [alt] -> b)
-> Translate c m CoreExpr b
altT :: (ExtendPath c Crumb, AddBindings c, Monad m)
=> Translate c m AltCon a1
-> (Int -> Translate c m Var a2)
-> Translate c m CoreExpr a3
-> (a1 -> [a2] -> a3 -> b)
-> Translate c m CoreAlt b
-}
-- mkVarName :: MonadThings m => Translate c m Var (CoreExpr,Type)
-- mkVarName = contextfreeT (mkStringExpr . uqName . varName) &&& arr varType
varLitE :: Var -> CoreExpr
varLitE = Lit . mkMachString . uqVarName
uqVarName :: Var -> String
uqVarName = uqName . varName
anybuER :: (MonadCatch m, Walker c g, ExtendPath c Crumb, Injection CoreExpr g) =>
Rewrite c m CoreExpr -> Rewrite c m g
anybuER r = anybuR (promoteExprR r)
-- anytdER :: (MonadCatch m, Walker c g, ExtendPath c Crumb, Injection CoreExpr g) =>
-- Rewrite c m CoreExpr -> Rewrite c m g
-- anytdER r = anytdR (promoteExprR r)
tryRulesBU :: [String] -> RewriteH Core
tryRulesBU = tryR . anybuER . rulesR
reifyRules :: RewriteH Core
reifyRules = tryRulesBU $ map ("reify/" ++)
["not","(&&)","(||)","xor","(+)","exl","exr","pair","inl","inr","if","false","true"]
-- or: words $ "not (&&) (||) xor ..."
-- TODO: Is there a way not to redundantly specify this rule list?
-- Yes -- trust GHC to apply the rules later.
reifyDef :: RewriteH Core
reifyDef = rhsR reifyExpr
callNameLam :: String -> TranslateH CoreExpr (CoreExpr, [CoreExpr])
callNameLam = callNameT . lamName
-- Unused
reifyEval :: ReExpr
reifyEval = reifyArg >>> evalArg
where
reifyArg = do (_reifyE, [Type _, arg, _str]) <- callNameLam "reifyEP"
return arg
evalArg = do (_evalE, [Type _, body]) <- callNameLam "evalEP"
return body
-- TODO: reifyEval replaced with tryRulesBU ["reify'/eval","eval/reify'"], and
-- even those rules are no longer invoked explicitly.
inlineCleanup :: String -> RewriteH Core
inlineCleanup nm = tryR $ anybuER (inlineNameR nm) >>> anybuER cleanupUnfoldR
-- inlineNamesTD :: [String] -> RewriteH Core
-- inlineNamesTD nms = anytdER (inlineNamesR nms)
-- #define FactorReified
reifyNamed :: String -> RewriteH Core
reifyNamed nm = snocPathIn (rhsOfT cmpNm)
( inlineCleanup (lamName "ifThenElse")
-- >>> (tryR $ anytdER $ rule "if/pair")
>>> reifyExprC
>>> reifyRules
#ifdef FactorReified
>>> pathR [App_Arg] (promoteExprR (letIntroR (nm ++ "_reified")))
>>> promoteExprR letFloatArgR
#endif
)
#ifdef FactorReified
>>> snocPathIn (extractT $ parentOfT $ bindingGroupOfT $ cmpNm)
(promoteProgR letFloatTopR)
#endif
>>> inlineCleanup nm
-- I don't know why the following is needed, considering the INLINE
>>> inlineCleanup (lamName "reifyEP#")
-- >>> tryR (anybuER (promoteExprR reifyEval))
-- >>> tryRulesBU ["reifyE/evalE","evalE/reifyE"]
-- >>> tryRulesBU ["reifyEP/evalEP"]
>>> tryR simplifyR -- For the rule applications at least
where
cmpNm = cmpString2Var nm
-- I don't know why I need both cleanupUnfoldR and simplifyR.
-- Note: I inline reifyE to its reifyE definition and then simplify
-- reifyE/evalE, rather than simplifying reifyE/evalE. With this choice, I can
-- also reifyE/evalE combinations that come from reifyE in source code and ones
-- that reifyExpr inserts.
{--------------------------------------------------------------------
Plugin
--------------------------------------------------------------------}
plugin :: Plugin
plugin = hermitPlugin (phase 0 . interactive externals)
externals :: [External]
externals =
[ external "reify-expr"
(promoteExprR reifyExpr :: RewriteH Core)
["Reify a Core expression into a GADT construction"]
, external "reify-rules"
(reifyRules :: RewriteH Core)
["convert some non-local vars to consts"]
, external "inline-cleanup"
(inlineCleanup :: String -> RewriteH Core)
["inline a named definition, and clean-up beta-redexes"]
, external "reify-def"
(reifyDef :: RewriteH Core)
["reify for definitions"]
, external "reify-expr-cleanup"
(promoteExprR reifyExpr >>> reifyRules :: RewriteH Core)
["reify-core and cleanup for expressions"]
, external "reify-def-cleanup"
(reifyDef >>> reifyRules :: RewriteH Core)
["reify-core and cleanup for definitions"]
, external "reify-named"
(reifyNamed :: String -> RewriteH Core)
["reify via name"]
-- , external "reify-tops"
-- (reifyTops :: RewriteH ModGuts)
-- ["reify via name"]
, external "reify-eval"
(anybuER (promoteExprR reifyEval) :: RewriteH Core)
["simplify reifyE composed with evalE"]
]
| conal/lambda-ccc | src/LambdaCCC/Unused/ReifyLambda.hs | bsd-3-clause | 23,611 | 0 | 27 | 7,038 | 4,845 | 2,602 | 2,243 | -1 | -1 |
module Ivory.Language.Syntax (
module Exports
) where
import Ivory.Language.Syntax.AST as Exports
import Ivory.Language.Syntax.Names as Exports
import Ivory.Language.Syntax.Type as Exports
| Hodapp87/ivory | ivory/src/Ivory/Language/Syntax.hs | bsd-3-clause | 199 | 0 | 4 | 29 | 40 | 30 | 10 | 5 | 0 |
import Test.Tasty
import Test.Tasty.Hspec
import Test.Tasty.QuickCheck
import Yi.Regex
import Text.Regex.TDFA.ReadRegex (parseRegex)
import Text.Regex.TDFA.Pattern
ignoreDoPa :: Pattern -> Pattern
ignoreDoPa (PCarat dp ) = PCarat (DoPa 0)
ignoreDoPa (PDollar dp ) = PDollar (DoPa 0)
ignoreDoPa (PDot dp ) = PDot (DoPa 0)
ignoreDoPa (PAny dp ps) = PAny (DoPa 0) ps
ignoreDoPa (PAnyNot dp ps) = PAnyNot (DoPa 0) ps
ignoreDoPa (PEscape dp pc) = PEscape (DoPa 0) pc
ignoreDoPa (PChar dp pc) = PChar (DoPa 0) pc
ignoreDoPa (PGroup m p ) = PGroup m (ignoreDoPa p)
ignoreDoPa (POr l ) = POr (map ignoreDoPa l)
ignoreDoPa (PConcat l ) = PConcat (map ignoreDoPa l)
ignoreDoPa (PQuest p ) = PQuest (ignoreDoPa p)
ignoreDoPa (PPlus p ) = PPlus (ignoreDoPa p)
ignoreDoPa (PStar b p ) = PStar b (ignoreDoPa p)
ignoreDoPa (PBound i m p) = PBound i m (ignoreDoPa p)
ignoreDoPa (PNonCapture p) = PNonCapture (ignoreDoPa p)
ignoreDoPa (PNonEmpty p) = PNonEmpty (ignoreDoPa p)
ignoreDoPa p = p
mapFst f (a,b) = (f a,b)
main = defaultMain =<< tests
tests = testSpec "(Hspec tests)" $ do
describe "reversePattern" $ do
it "reverses normal characters" $
(mapFst ignoreDoPa . reversePattern <$> parseRegex "ab")
`shouldBe` (mapFst ignoreDoPa <$> parseRegex "ba")
it "changes carat to dollar" $
(reversePattern <$> parseRegex "^") `shouldBe` parseRegex "$"
it "changes dollar to carat" $
(reversePattern <$> parseRegex "$") `shouldBe` parseRegex "^"
it "forms the identity when applied twice" $
property $ \p -> (reversePattern . reversePattern <$> parseRegex p) `shouldBe` parseRegex p
it "recursively reverses patterns" $
(mapFst ignoreDoPa . reversePattern <$> parseRegex "foo|bar")
`shouldBe` (mapFst ignoreDoPa <$> parseRegex "oof|rab") | siddhanathan/yi | yi-language/test/Spec.hs | gpl-2.0 | 1,881 | 0 | 16 | 428 | 711 | 352 | 359 | 40 | 1 |
module Var00001 where
-- Believe it or not, this is valid!
qualified = True
| charleso/intellij-haskforce | tests/gold/parser/Var00001.hs | apache-2.0 | 77 | 0 | 4 | 15 | 10 | 7 | 3 | 2 | 1 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
module Opaleye.Internal.Values where
import qualified Opaleye.PGTypes as T
import Opaleye.Internal.Column (Column(Column))
import qualified Opaleye.Internal.Unpackspec as U
import qualified Opaleye.Internal.Tag as T
import qualified Opaleye.Internal.PrimQuery as PQ
import qualified Opaleye.Internal.PackMap as PM
import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ
import Data.Profunctor (Profunctor, dimap, rmap)
import Data.Profunctor.Product (ProductProfunctor, empty, (***!))
import qualified Data.Profunctor.Product as PP
import Data.Profunctor.Product.Default (Default, def)
import Control.Applicative (Applicative, pure, (<*>))
-- There are two annoyances with creating SQL VALUES statements
--
-- 1. SQL does not allow empty VALUES statements so if we want to
-- create a VALUES statement from an empty list we have to fake it
-- somehow. The current approach is to make a VALUES statement
-- with a single row of NULLs and then restrict it with WHERE
-- FALSE.
-- 2. Postgres's type inference of constants is pretty poor so we will
-- sometimes have to give explicit type signatures. The future
-- ShowConstant class will have the same problem. NB We don't
-- actually currently address this problem.
valuesU :: U.Unpackspec columns columns'
-> Valuesspec columns columns'
-> [columns]
-> ((), T.Tag) -> (columns', PQ.PrimQuery, T.Tag)
valuesU unpack valuesspec rows ((), t) = (newColumns, primQ', T.next t)
where runRow row = valuesRow
where (_, valuesRow) =
PM.run (U.runUnpackspec unpack extractValuesEntry row)
(newColumns, valuesPEs_nulls) =
PM.run (runValuesspec valuesspec (extractValuesField t))
valuesPEs = map fst valuesPEs_nulls
nulls = map snd valuesPEs_nulls
yieldNoRows :: PQ.PrimQuery -> PQ.PrimQuery
yieldNoRows = PQ.restrict (HPQ.ConstExpr (HPQ.BoolLit False))
values' :: [[HPQ.PrimExpr]]
(values', wrap) = if null rows
then ([nulls], yieldNoRows)
else (map runRow rows, id)
primQ' = wrap (PQ.Values valuesPEs values')
-- We don't actually use the return value of this. It might be better
-- to come up with another Applicative instance for specifically doing
-- what we need.
extractValuesEntry :: HPQ.PrimExpr -> PM.PM [HPQ.PrimExpr] HPQ.PrimExpr
extractValuesEntry pe = do
PM.write pe
return pe
extractValuesField :: T.Tag -> HPQ.PrimExpr
-> PM.PM [(HPQ.Symbol, HPQ.PrimExpr)] HPQ.PrimExpr
extractValuesField = PM.extractAttr "values"
newtype Valuesspec columns columns' =
Valuesspec (PM.PackMap HPQ.PrimExpr HPQ.PrimExpr () columns')
runValuesspec :: Applicative f => Valuesspec columns columns'
-> (HPQ.PrimExpr -> f HPQ.PrimExpr) -> f columns'
runValuesspec (Valuesspec v) f = PM.traversePM v f ()
instance Default Valuesspec (Column T.PGInt4) (Column T.PGInt4) where
def = Valuesspec (PM.PackMap (\f () -> fmap Column (f (HPQ.ConstExpr HPQ.NullLit))))
-- {
-- Boilerplate instance definitions. Theoretically, these are derivable.
instance Functor (Valuesspec a) where
fmap f (Valuesspec g) = Valuesspec (fmap f g)
instance Applicative (Valuesspec a) where
pure = Valuesspec . pure
Valuesspec f <*> Valuesspec x = Valuesspec (f <*> x)
instance Profunctor Valuesspec where
dimap _ g (Valuesspec q) = Valuesspec (rmap g q)
instance ProductProfunctor Valuesspec where
empty = PP.defaultEmpty
(***!) = PP.defaultProfunctorProduct
-- }
| bergmark/haskell-opaleye | src/Opaleye/Internal/Values.hs | bsd-3-clause | 3,667 | 0 | 16 | 785 | 895 | 501 | 394 | 57 | 2 |
<?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="hi-IN">
<title>SAML Support</title>
<maps>
<homeID>saml</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/saml/src/main/javahelp/help_hi_IN/helpset_hi_IN.hs | apache-2.0 | 958 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : Text.ParserCombinators.Parsec.Perm
-- Copyright : (c) Paolo Martini 2007
-- License : BSD-style (see the LICENSE file)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Parsec compatibility module
--
-----------------------------------------------------------------------------
module Text.ParserCombinators.Parsec.Perm
( PermParser,
permute,
(<||>),
(<$$>),
(<|?>),
(<$?>)
) where
import Text.Parsec.Perm
| maurer/15-411-Haskell-Base-Code | src/Text/ParserCombinators/Parsec/Perm.hs | bsd-3-clause | 617 | 0 | 4 | 118 | 55 | 44 | 11 | 8 | 0 |
module M1 where
data BTree a
= Empty | T a (BTree a) (BTree a) deriving Show
buildtree :: (Monad m, Ord a) => [a] -> m (BTree a)
buildtree [] = return Empty
buildtree ((x : xs))
= do res1 <- buildtree xs
res <- insert x res1
return res
insert
:: (Monad m, Ord a) => a -> (BTree a) -> m (BTree a)
insert val v2
= do case v2 of
T val Empty Empty
| val == val -> return Empty
| otherwise ->
return (T val Empty (T val Empty Empty))
T val (T val2 Empty Empty) Empty -> return Empty
_ -> return v2
main :: IO ()
main
= do n@(T val Empty Empty) <- buildtree [3, 1, 2]
putStrLn $ (show n)
| kmate/HaRe | old/testing/unfoldAsPatterns/M1AST.hs | bsd-3-clause | 760 | 0 | 15 | 308 | 344 | 170 | 174 | 23 | 3 |
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE GADTs #-}
module T13998 where
import Data.Type.Equality
class EqForall f where
eqForall :: f a -> f a -> Bool
class EqForall f => EqForallPoly f where
eqForallPoly :: f a -> f b -> Bool
default eqForallPoly :: TestEquality f => f a -> f b -> Bool
eqForallPoly = defaultEqForallPoly
defaultEqForallPoly :: (TestEquality f, EqForall f) => f a -> f b -> Bool
defaultEqForallPoly x y = case testEquality x y of
Nothing -> False
Just Refl -> eqForall x y
data Atom = AtomInt | AtomString | AtomBool
data Value (a :: Atom) where
ValueInt :: Int -> Value 'AtomInt
ValueString :: String -> Value 'AtomString
ValueBool :: Bool -> Value 'AtomBool
instance TestEquality Value where
testEquality (ValueInt _) (ValueInt _) = Just Refl
testEquality (ValueString _) (ValueString _) = Just Refl
testEquality (ValueBool _) (ValueBool _) = Just Refl
testEquality _ _ = Nothing
instance EqForall Value where
eqForall (ValueInt a) (ValueInt b) = a == b
eqForall (ValueString a) (ValueString b) = a == b
eqForall (ValueBool a) (ValueBool b) = a == b
instance EqForallPoly Value
| shlevy/ghc | testsuite/tests/deriving/should_compile/T13998.hs | bsd-3-clause | 1,234 | 0 | 11 | 244 | 436 | 220 | 216 | 32 | 2 |
import CmmExpr
#if !(MACHREGS_i386 || MACHREGS_x86_64 || MACHREGS_sparc || MACHREGS_powerpc)
import Panic
#endif
import Reg
#include "ghcautoconf.h"
#include "stg/MachRegs.h"
#if MACHREGS_i386 || MACHREGS_x86_64
# if MACHREGS_i386
# define eax 0
# define ebx 1
# define ecx 2
# define edx 3
# define esi 4
# define edi 5
# define ebp 6
# define esp 7
# endif
# if MACHREGS_x86_64
# define rax 0
# define rbx 1
# define rcx 2
# define rdx 3
# define rsi 4
# define rdi 5
# define rbp 6
# define rsp 7
# define r8 8
# define r9 9
# define r10 10
# define r11 11
# define r12 12
# define r13 13
# define r14 14
# define r15 15
# endif
# define fake0 16
# define fake1 17
# define fake2 18
# define fake3 19
# define fake4 20
# define fake5 21
# define xmm0 24
# define xmm1 25
# define xmm2 26
# define xmm3 27
# define xmm4 28
# define xmm5 29
# define xmm6 30
# define xmm7 31
# define xmm8 32
# define xmm9 33
# define xmm10 34
# define xmm11 35
# define xmm12 36
# define xmm13 37
# define xmm14 38
# define xmm15 39
# define ymm0 40
# define ymm1 41
# define ymm2 42
# define ymm3 43
# define ymm4 44
# define ymm5 45
# define ymm6 46
# define ymm7 47
# define ymm8 48
# define ymm9 49
# define ymm10 50
# define ymm11 51
# define ymm12 52
# define ymm13 53
# define ymm14 54
# define ymm15 55
# define zmm0 56
# define zmm1 57
# define zmm2 58
# define zmm3 59
# define zmm4 60
# define zmm5 61
# define zmm6 62
# define zmm7 63
# define zmm8 64
# define zmm9 65
# define zmm10 66
# define zmm11 67
# define zmm12 68
# define zmm13 69
# define zmm14 70
# define zmm15 71
-- Note: these are only needed for ARM/ARM64 because globalRegMaybe is now used in CmmSink.hs.
-- Since it's only used to check 'isJust', the actual values don't matter, thus
-- I'm not sure if these are the correct numberings.
-- Normally, the register names are just stringified as part of the REG() macro
#elif MACHREGS_powerpc || MACHREGS_arm || MACHREGS_aarch64
# define r0 0
# define r1 1
# define r2 2
# define r3 3
# define r4 4
# define r5 5
# define r6 6
# define r7 7
# define r8 8
# define r9 9
# define r10 10
# define r11 11
# define r12 12
# define r13 13
# define r14 14
# define r15 15
# define r16 16
# define r17 17
# define r18 18
# define r19 19
# define r20 20
# define r21 21
# define r22 22
# define r23 23
# define r24 24
# define r25 25
# define r26 26
# define r27 27
# define r28 28
# define r29 29
# define r30 30
# define r31 31
-- See note above. These aren't actually used for anything except satisfying the compiler for globalRegMaybe
-- so I'm unsure if they're the correct numberings, should they ever be attempted to be used in the NCG.
#if MACHREGS_aarch64 || MACHREGS_arm
# define s0 32
# define s1 33
# define s2 34
# define s3 35
# define s4 36
# define s5 37
# define s6 38
# define s7 39
# define s8 40
# define s9 41
# define s10 42
# define s11 43
# define s12 44
# define s13 45
# define s14 46
# define s15 47
# define s16 48
# define s17 49
# define s18 50
# define s19 51
# define s20 52
# define s21 53
# define s22 54
# define s23 55
# define s24 56
# define s25 57
# define s26 58
# define s27 59
# define s28 60
# define s29 61
# define s30 62
# define s31 63
# define d0 32
# define d1 33
# define d2 34
# define d3 35
# define d4 36
# define d5 37
# define d6 38
# define d7 39
# define d8 40
# define d9 41
# define d10 42
# define d11 43
# define d12 44
# define d13 45
# define d14 46
# define d15 47
# define d16 48
# define d17 49
# define d18 50
# define d19 51
# define d20 52
# define d21 53
# define d22 54
# define d23 55
# define d24 56
# define d25 57
# define d26 58
# define d27 59
# define d28 60
# define d29 61
# define d30 62
# define d31 63
#endif
# if MACHREGS_darwin
# define f0 32
# define f1 33
# define f2 34
# define f3 35
# define f4 36
# define f5 37
# define f6 38
# define f7 39
# define f8 40
# define f9 41
# define f10 42
# define f11 43
# define f12 44
# define f13 45
# define f14 46
# define f15 47
# define f16 48
# define f17 49
# define f18 50
# define f19 51
# define f20 52
# define f21 53
# define f22 54
# define f23 55
# define f24 56
# define f25 57
# define f26 58
# define f27 59
# define f28 60
# define f29 61
# define f30 62
# define f31 63
# else
# define fr0 32
# define fr1 33
# define fr2 34
# define fr3 35
# define fr4 36
# define fr5 37
# define fr6 38
# define fr7 39
# define fr8 40
# define fr9 41
# define fr10 42
# define fr11 43
# define fr12 44
# define fr13 45
# define fr14 46
# define fr15 47
# define fr16 48
# define fr17 49
# define fr18 50
# define fr19 51
# define fr20 52
# define fr21 53
# define fr22 54
# define fr23 55
# define fr24 56
# define fr25 57
# define fr26 58
# define fr27 59
# define fr28 60
# define fr29 61
# define fr30 62
# define fr31 63
# endif
#elif MACHREGS_sparc
# define g0 0
# define g1 1
# define g2 2
# define g3 3
# define g4 4
# define g5 5
# define g6 6
# define g7 7
# define o0 8
# define o1 9
# define o2 10
# define o3 11
# define o4 12
# define o5 13
# define o6 14
# define o7 15
# define l0 16
# define l1 17
# define l2 18
# define l3 19
# define l4 20
# define l5 21
# define l6 22
# define l7 23
# define i0 24
# define i1 25
# define i2 26
# define i3 27
# define i4 28
# define i5 29
# define i6 30
# define i7 31
# define f0 32
# define f1 33
# define f2 34
# define f3 35
# define f4 36
# define f5 37
# define f6 38
# define f7 39
# define f8 40
# define f9 41
# define f10 42
# define f11 43
# define f12 44
# define f13 45
# define f14 46
# define f15 47
# define f16 48
# define f17 49
# define f18 50
# define f19 51
# define f20 52
# define f21 53
# define f22 54
# define f23 55
# define f24 56
# define f25 57
# define f26 58
# define f27 59
# define f28 60
# define f29 61
# define f30 62
# define f31 63
#endif
callerSaves :: GlobalReg -> Bool
#ifdef CALLER_SAVES_Base
callerSaves BaseReg = True
#endif
#ifdef CALLER_SAVES_R1
callerSaves (VanillaReg 1 _) = True
#endif
#ifdef CALLER_SAVES_R2
callerSaves (VanillaReg 2 _) = True
#endif
#ifdef CALLER_SAVES_R3
callerSaves (VanillaReg 3 _) = True
#endif
#ifdef CALLER_SAVES_R4
callerSaves (VanillaReg 4 _) = True
#endif
#ifdef CALLER_SAVES_R5
callerSaves (VanillaReg 5 _) = True
#endif
#ifdef CALLER_SAVES_R6
callerSaves (VanillaReg 6 _) = True
#endif
#ifdef CALLER_SAVES_R7
callerSaves (VanillaReg 7 _) = True
#endif
#ifdef CALLER_SAVES_R8
callerSaves (VanillaReg 8 _) = True
#endif
#ifdef CALLER_SAVES_R9
callerSaves (VanillaReg 9 _) = True
#endif
#ifdef CALLER_SAVES_R10
callerSaves (VanillaReg 10 _) = True
#endif
#ifdef CALLER_SAVES_F1
callerSaves (FloatReg 1) = True
#endif
#ifdef CALLER_SAVES_F2
callerSaves (FloatReg 2) = True
#endif
#ifdef CALLER_SAVES_F3
callerSaves (FloatReg 3) = True
#endif
#ifdef CALLER_SAVES_F4
callerSaves (FloatReg 4) = True
#endif
#ifdef CALLER_SAVES_F5
callerSaves (FloatReg 5) = True
#endif
#ifdef CALLER_SAVES_F6
callerSaves (FloatReg 6) = True
#endif
#ifdef CALLER_SAVES_D1
callerSaves (DoubleReg 1) = True
#endif
#ifdef CALLER_SAVES_D2
callerSaves (DoubleReg 2) = True
#endif
#ifdef CALLER_SAVES_D3
callerSaves (DoubleReg 3) = True
#endif
#ifdef CALLER_SAVES_D4
callerSaves (DoubleReg 4) = True
#endif
#ifdef CALLER_SAVES_D5
callerSaves (DoubleReg 5) = True
#endif
#ifdef CALLER_SAVES_D6
callerSaves (DoubleReg 6) = True
#endif
#ifdef CALLER_SAVES_L1
callerSaves (LongReg 1) = True
#endif
#ifdef CALLER_SAVES_Sp
callerSaves Sp = True
#endif
#ifdef CALLER_SAVES_SpLim
callerSaves SpLim = True
#endif
#ifdef CALLER_SAVES_Hp
callerSaves Hp = True
#endif
#ifdef CALLER_SAVES_HpLim
callerSaves HpLim = True
#endif
#ifdef CALLER_SAVES_CCCS
callerSaves CCCS = True
#endif
#ifdef CALLER_SAVES_CurrentTSO
callerSaves CurrentTSO = True
#endif
#ifdef CALLER_SAVES_CurrentNursery
callerSaves CurrentNursery = True
#endif
callerSaves _ = False
activeStgRegs :: [GlobalReg]
activeStgRegs = [
#ifdef REG_Base
BaseReg
#endif
#ifdef REG_Sp
,Sp
#endif
#ifdef REG_Hp
,Hp
#endif
#ifdef REG_R1
,VanillaReg 1 VGcPtr
#endif
#ifdef REG_R2
,VanillaReg 2 VGcPtr
#endif
#ifdef REG_R3
,VanillaReg 3 VGcPtr
#endif
#ifdef REG_R4
,VanillaReg 4 VGcPtr
#endif
#ifdef REG_R5
,VanillaReg 5 VGcPtr
#endif
#ifdef REG_R6
,VanillaReg 6 VGcPtr
#endif
#ifdef REG_R7
,VanillaReg 7 VGcPtr
#endif
#ifdef REG_R8
,VanillaReg 8 VGcPtr
#endif
#ifdef REG_R9
,VanillaReg 9 VGcPtr
#endif
#ifdef REG_R10
,VanillaReg 10 VGcPtr
#endif
#ifdef REG_SpLim
,SpLim
#endif
#if MAX_REAL_XMM_REG != 0
#ifdef REG_F1
,FloatReg 1
#endif
#ifdef REG_D1
,DoubleReg 1
#endif
#ifdef REG_XMM1
,XmmReg 1
#endif
#ifdef REG_YMM1
,YmmReg 1
#endif
#ifdef REG_ZMM1
,ZmmReg 1
#endif
#ifdef REG_F2
,FloatReg 2
#endif
#ifdef REG_D2
,DoubleReg 2
#endif
#ifdef REG_XMM2
,XmmReg 2
#endif
#ifdef REG_YMM2
,YmmReg 2
#endif
#ifdef REG_ZMM2
,ZmmReg 2
#endif
#ifdef REG_F3
,FloatReg 3
#endif
#ifdef REG_D3
,DoubleReg 3
#endif
#ifdef REG_XMM3
,XmmReg 3
#endif
#ifdef REG_YMM3
,YmmReg 3
#endif
#ifdef REG_ZMM3
,ZmmReg 3
#endif
#ifdef REG_F4
,FloatReg 4
#endif
#ifdef REG_D4
,DoubleReg 4
#endif
#ifdef REG_XMM4
,XmmReg 4
#endif
#ifdef REG_YMM4
,YmmReg 4
#endif
#ifdef REG_ZMM4
,ZmmReg 4
#endif
#ifdef REG_F5
,FloatReg 5
#endif
#ifdef REG_D5
,DoubleReg 5
#endif
#ifdef REG_XMM5
,XmmReg 5
#endif
#ifdef REG_YMM5
,YmmReg 5
#endif
#ifdef REG_ZMM5
,ZmmReg 5
#endif
#ifdef REG_F6
,FloatReg 6
#endif
#ifdef REG_D6
,DoubleReg 6
#endif
#ifdef REG_XMM6
,XmmReg 6
#endif
#ifdef REG_YMM6
,YmmReg 6
#endif
#ifdef REG_ZMM6
,ZmmReg 6
#endif
#else /* MAX_REAL_XMM_REG == 0 */
#ifdef REG_F1
,FloatReg 1
#endif
#ifdef REG_F2
,FloatReg 2
#endif
#ifdef REG_F3
,FloatReg 3
#endif
#ifdef REG_F4
,FloatReg 4
#endif
#ifdef REG_F5
,FloatReg 5
#endif
#ifdef REG_F6
,FloatReg 6
#endif
#ifdef REG_D1
,DoubleReg 1
#endif
#ifdef REG_D2
,DoubleReg 2
#endif
#ifdef REG_D3
,DoubleReg 3
#endif
#ifdef REG_D4
,DoubleReg 4
#endif
#ifdef REG_D5
,DoubleReg 5
#endif
#ifdef REG_D6
,DoubleReg 6
#endif
#endif /* MAX_REAL_XMM_REG == 0 */
]
haveRegBase :: Bool
#ifdef REG_Base
haveRegBase = True
#else
haveRegBase = False
#endif
-- | Returns 'Nothing' if this global register is not stored
-- in a real machine register, otherwise returns @'Just' reg@, where
-- reg is the machine register it is stored in.
globalRegMaybe :: GlobalReg -> Maybe RealReg
#if MACHREGS_i386 || MACHREGS_x86_64 || MACHREGS_sparc || MACHREGS_powerpc || MACHREGS_arm || MACHREGS_aarch64
# ifdef REG_Base
globalRegMaybe BaseReg = Just (RealRegSingle REG_Base)
# endif
# ifdef REG_R1
globalRegMaybe (VanillaReg 1 _) = Just (RealRegSingle REG_R1)
# endif
# ifdef REG_R2
globalRegMaybe (VanillaReg 2 _) = Just (RealRegSingle REG_R2)
# endif
# ifdef REG_R3
globalRegMaybe (VanillaReg 3 _) = Just (RealRegSingle REG_R3)
# endif
# ifdef REG_R4
globalRegMaybe (VanillaReg 4 _) = Just (RealRegSingle REG_R4)
# endif
# ifdef REG_R5
globalRegMaybe (VanillaReg 5 _) = Just (RealRegSingle REG_R5)
# endif
# ifdef REG_R6
globalRegMaybe (VanillaReg 6 _) = Just (RealRegSingle REG_R6)
# endif
# ifdef REG_R7
globalRegMaybe (VanillaReg 7 _) = Just (RealRegSingle REG_R7)
# endif
# ifdef REG_R8
globalRegMaybe (VanillaReg 8 _) = Just (RealRegSingle REG_R8)
# endif
# ifdef REG_R9
globalRegMaybe (VanillaReg 9 _) = Just (RealRegSingle REG_R9)
# endif
# ifdef REG_R10
globalRegMaybe (VanillaReg 10 _) = Just (RealRegSingle REG_R10)
# endif
# ifdef REG_F1
globalRegMaybe (FloatReg 1) = Just (RealRegSingle REG_F1)
# endif
# ifdef REG_F2
globalRegMaybe (FloatReg 2) = Just (RealRegSingle REG_F2)
# endif
# ifdef REG_F3
globalRegMaybe (FloatReg 3) = Just (RealRegSingle REG_F3)
# endif
# ifdef REG_F4
globalRegMaybe (FloatReg 4) = Just (RealRegSingle REG_F4)
# endif
# ifdef REG_F5
globalRegMaybe (FloatReg 5) = Just (RealRegSingle REG_F5)
# endif
# ifdef REG_F6
globalRegMaybe (FloatReg 6) = Just (RealRegSingle REG_F6)
# endif
# ifdef REG_D1
globalRegMaybe (DoubleReg 1) =
# if MACHREGS_sparc
Just (RealRegPair REG_D1 (REG_D1 + 1))
# else
Just (RealRegSingle REG_D1)
# endif
# endif
# ifdef REG_D2
globalRegMaybe (DoubleReg 2) =
# if MACHREGS_sparc
Just (RealRegPair REG_D2 (REG_D2 + 1))
# else
Just (RealRegSingle REG_D2)
# endif
# endif
# ifdef REG_D3
globalRegMaybe (DoubleReg 3) =
# if MACHREGS_sparc
Just (RealRegPair REG_D3 (REG_D3 + 1))
# else
Just (RealRegSingle REG_D3)
# endif
# endif
# ifdef REG_D4
globalRegMaybe (DoubleReg 4) =
# if MACHREGS_sparc
Just (RealRegPair REG_D4 (REG_D4 + 1))
# else
Just (RealRegSingle REG_D4)
# endif
# endif
# ifdef REG_D5
globalRegMaybe (DoubleReg 5) =
# if MACHREGS_sparc
Just (RealRegPair REG_D5 (REG_D5 + 1))
# else
Just (RealRegSingle REG_D5)
# endif
# endif
# ifdef REG_D6
globalRegMaybe (DoubleReg 6) =
# if MACHREGS_sparc
Just (RealRegPair REG_D6 (REG_D6 + 1))
# else
Just (RealRegSingle REG_D6)
# endif
# endif
# if MAX_REAL_XMM_REG != 0
# ifdef REG_XMM1
globalRegMaybe (XmmReg 1) = Just (RealRegSingle REG_XMM1)
# endif
# ifdef REG_XMM2
globalRegMaybe (XmmReg 2) = Just (RealRegSingle REG_XMM2)
# endif
# ifdef REG_XMM3
globalRegMaybe (XmmReg 3) = Just (RealRegSingle REG_XMM3)
# endif
# ifdef REG_XMM4
globalRegMaybe (XmmReg 4) = Just (RealRegSingle REG_XMM4)
# endif
# ifdef REG_XMM5
globalRegMaybe (XmmReg 5) = Just (RealRegSingle REG_XMM5)
# endif
# ifdef REG_XMM6
globalRegMaybe (XmmReg 6) = Just (RealRegSingle REG_XMM6)
# endif
# endif
# if MAX_REAL_YMM_REG != 0
# ifdef REG_YMM1
globalRegMaybe (YmmReg 1) = Just (RealRegSingle REG_YMM1)
# endif
# ifdef REG_YMM2
globalRegMaybe (YmmReg 2) = Just (RealRegSingle REG_YMM2)
# endif
# ifdef REG_YMM3
globalRegMaybe (YmmReg 3) = Just (RealRegSingle REG_YMM3)
# endif
# ifdef REG_YMM4
globalRegMaybe (YmmReg 4) = Just (RealRegSingle REG_YMM4)
# endif
# ifdef REG_YMM5
globalRegMaybe (YmmReg 5) = Just (RealRegSingle REG_YMM5)
# endif
# ifdef REG_YMM6
globalRegMaybe (YmmReg 6) = Just (RealRegSingle REG_YMM6)
# endif
# endif
# if MAX_REAL_ZMM_REG != 0
# ifdef REG_ZMM1
globalRegMaybe (ZmmReg 1) = Just (RealRegSingle REG_ZMM1)
# endif
# ifdef REG_ZMM2
globalRegMaybe (ZmmReg 2) = Just (RealRegSingle REG_ZMM2)
# endif
# ifdef REG_ZMM3
globalRegMaybe (ZmmReg 3) = Just (RealRegSingle REG_ZMM3)
# endif
# ifdef REG_ZMM4
globalRegMaybe (ZmmReg 4) = Just (RealRegSingle REG_ZMM4)
# endif
# ifdef REG_ZMM5
globalRegMaybe (ZmmReg 5) = Just (RealRegSingle REG_ZMM5)
# endif
# ifdef REG_ZMM6
globalRegMaybe (ZmmReg 6) = Just (RealRegSingle REG_ZMM6)
# endif
# endif
# ifdef REG_Sp
globalRegMaybe Sp = Just (RealRegSingle REG_Sp)
# endif
# ifdef REG_Lng1
globalRegMaybe (LongReg 1) = Just (RealRegSingle REG_Lng1)
# endif
# ifdef REG_Lng2
globalRegMaybe (LongReg 2) = Just (RealRegSingle REG_Lng2)
# endif
# ifdef REG_SpLim
globalRegMaybe SpLim = Just (RealRegSingle REG_SpLim)
# endif
# ifdef REG_Hp
globalRegMaybe Hp = Just (RealRegSingle REG_Hp)
# endif
# ifdef REG_HpLim
globalRegMaybe HpLim = Just (RealRegSingle REG_HpLim)
# endif
# ifdef REG_CurrentTSO
globalRegMaybe CurrentTSO = Just (RealRegSingle REG_CurrentTSO)
# endif
# ifdef REG_CurrentNursery
globalRegMaybe CurrentNursery = Just (RealRegSingle REG_CurrentNursery)
# endif
# ifdef REG_MachSp
globalRegMaybe MachSp = Just (RealRegSingle REG_MachSp)
# endif
globalRegMaybe _ = Nothing
#elif MACHREGS_NO_REGS
globalRegMaybe _ = Nothing
#else
globalRegMaybe = panic "globalRegMaybe not defined for this platform"
#endif
freeReg :: RegNo -> Bool
#if MACHREGS_i386 || MACHREGS_x86_64
# if MACHREGS_i386
freeReg esp = False -- %esp is the C stack pointer
freeReg esi = False -- Note [esi/edi not allocatable]
freeReg edi = False
# endif
# if MACHREGS_x86_64
freeReg rsp = False -- %rsp is the C stack pointer
# endif
{-
Note [esi/edi not allocatable]
%esi is mapped to R1, so %esi would normally be allocatable while it
is not being used for R1. However, %esi has no 8-bit version on x86,
and the linear register allocator is not sophisticated enough to
handle this irregularity (we need more RegClasses). The
graph-colouring allocator also cannot handle this - it was designed
with more flexibility in mind, but the current implementation is
restricted to the same set of classes as the linear allocator.
Hence, on x86 esi and edi are treated as not allocatable.
-}
-- split patterns in two functions to prevent overlaps
freeReg r = freeRegBase r
freeRegBase :: RegNo -> Bool
# ifdef REG_Base
freeRegBase REG_Base = False
# endif
# ifdef REG_Sp
freeRegBase REG_Sp = False
# endif
# ifdef REG_SpLim
freeRegBase REG_SpLim = False
# endif
# ifdef REG_Hp
freeRegBase REG_Hp = False
# endif
# ifdef REG_HpLim
freeRegBase REG_HpLim = False
# endif
-- All other regs are considered to be "free", because we can track
-- their liveness accurately.
freeRegBase _ = True
#elif MACHREGS_powerpc
freeReg 0 = False -- Used by code setting the back chain pointer
-- in stack reallocations on Linux
-- r0 is not usable in all insns so also reserved
-- on Darwin.
freeReg 1 = False -- The Stack Pointer
# if !MACHREGS_darwin
-- most non-darwin powerpc OSes use r2 as a TOC pointer or something like that
freeReg 2 = False
freeReg 13 = False -- reserved for system thread ID on 64 bit
-- at least linux in -fPIC relies on r30 in PLT stubs
freeReg 30 = False
{- TODO: reserve r13 on 64 bit systems only and r30 on 32 bit respectively.
For now we use r30 on 64 bit and r13 on 32 bit as a temporary register
in stack handling code. See compiler/nativeGen/PPC/Ppr.hs.
Later we might want to reserve r13 and r30 only where it is required.
Then use r12 as temporary register, which is also what the C ABI does.
-}
# endif
# ifdef REG_Base
freeReg REG_Base = False
# endif
# ifdef REG_R1
freeReg REG_R1 = False
# endif
# ifdef REG_R2
freeReg REG_R2 = False
# endif
# ifdef REG_R3
freeReg REG_R3 = False
# endif
# ifdef REG_R4
freeReg REG_R4 = False
# endif
# ifdef REG_R5
freeReg REG_R5 = False
# endif
# ifdef REG_R6
freeReg REG_R6 = False
# endif
# ifdef REG_R7
freeReg REG_R7 = False
# endif
# ifdef REG_R8
freeReg REG_R8 = False
# endif
# ifdef REG_R9
freeReg REG_R9 = False
# endif
# ifdef REG_R10
freeReg REG_R10 = False
# endif
# ifdef REG_F1
freeReg REG_F1 = False
# endif
# ifdef REG_F2
freeReg REG_F2 = False
# endif
# ifdef REG_F3
freeReg REG_F3 = False
# endif
# ifdef REG_F4
freeReg REG_F4 = False
# endif
# ifdef REG_F5
freeReg REG_F5 = False
# endif
# ifdef REG_F6
freeReg REG_F6 = False
# endif
# ifdef REG_D1
freeReg REG_D1 = False
# endif
# ifdef REG_D2
freeReg REG_D2 = False
# endif
# ifdef REG_D3
freeReg REG_D3 = False
# endif
# ifdef REG_D4
freeReg REG_D4 = False
# endif
# ifdef REG_D5
freeReg REG_D5 = False
# endif
# ifdef REG_D6
freeReg REG_D6 = False
# endif
# ifdef REG_Sp
freeReg REG_Sp = False
# endif
# ifdef REG_Su
freeReg REG_Su = False
# endif
# ifdef REG_SpLim
freeReg REG_SpLim = False
# endif
# ifdef REG_Hp
freeReg REG_Hp = False
# endif
# ifdef REG_HpLim
freeReg REG_HpLim = False
# endif
freeReg _ = True
#elif MACHREGS_sparc
-- SPARC regs used by the OS / ABI
-- %g0(r0) is always zero
freeReg g0 = False
-- %g5(r5) - %g7(r7)
-- are reserved for the OS
freeReg g5 = False
freeReg g6 = False
freeReg g7 = False
-- %o6(r14)
-- is the C stack pointer
freeReg o6 = False
-- %o7(r15)
-- holds the C return address
freeReg o7 = False
-- %i6(r30)
-- is the C frame pointer
freeReg i6 = False
-- %i7(r31)
-- is used for C return addresses
freeReg i7 = False
-- %f0(r32) - %f1(r32)
-- are C floating point return regs
freeReg f0 = False
freeReg f1 = False
{-
freeReg regNo
-- don't release high half of double regs
| regNo >= f0
, regNo < NCG_FirstFloatReg
, regNo `mod` 2 /= 0
= False
-}
# ifdef REG_Base
freeReg REG_Base = False
# endif
# ifdef REG_R1
freeReg REG_R1 = False
# endif
# ifdef REG_R2
freeReg REG_R2 = False
# endif
# ifdef REG_R3
freeReg REG_R3 = False
# endif
# ifdef REG_R4
freeReg REG_R4 = False
# endif
# ifdef REG_R5
freeReg REG_R5 = False
# endif
# ifdef REG_R6
freeReg REG_R6 = False
# endif
# ifdef REG_R7
freeReg REG_R7 = False
# endif
# ifdef REG_R8
freeReg REG_R8 = False
# endif
# ifdef REG_R9
freeReg REG_R9 = False
# endif
# ifdef REG_R10
freeReg REG_R10 = False
# endif
# ifdef REG_F1
freeReg REG_F1 = False
# endif
# ifdef REG_F2
freeReg REG_F2 = False
# endif
# ifdef REG_F3
freeReg REG_F3 = False
# endif
# ifdef REG_F4
freeReg REG_F4 = False
# endif
# ifdef REG_F5
freeReg REG_F5 = False
# endif
# ifdef REG_F6
freeReg REG_F6 = False
# endif
# ifdef REG_D1
freeReg REG_D1 = False
# endif
# ifdef REG_D1_2
freeReg REG_D1_2 = False
# endif
# ifdef REG_D2
freeReg REG_D2 = False
# endif
# ifdef REG_D2_2
freeReg REG_D2_2 = False
# endif
# ifdef REG_D3
freeReg REG_D3 = False
# endif
# ifdef REG_D3_2
freeReg REG_D3_2 = False
# endif
# ifdef REG_D4
freeReg REG_D4 = False
# endif
# ifdef REG_D4_2
freeReg REG_D4_2 = False
# endif
# ifdef REG_D5
freeReg REG_D5 = False
# endif
# ifdef REG_D5_2
freeReg REG_D5_2 = False
# endif
# ifdef REG_D6
freeReg REG_D6 = False
# endif
# ifdef REG_D6_2
freeReg REG_D6_2 = False
# endif
# ifdef REG_Sp
freeReg REG_Sp = False
# endif
# ifdef REG_Su
freeReg REG_Su = False
# endif
# ifdef REG_SpLim
freeReg REG_SpLim = False
# endif
# ifdef REG_Hp
freeReg REG_Hp = False
# endif
# ifdef REG_HpLim
freeReg REG_HpLim = False
# endif
freeReg _ = True
#else
freeReg = panic "freeReg not defined for this platform"
#endif
| tjakway/ghcjvm | includes/CodeGen.Platform.hs | bsd-3-clause | 23,178 | 0 | 9 | 5,983 | 2,654 | 1,559 | 1,095 | 13 | 1 |
{-# LANGUAGE PatternSynonyms, MagicHash, BangPatterns #-}
module ShouldCompile where
import GHC.Base
data Foo = MkFoo Int# Int#
pattern P x = MkFoo 0# x
f x = let !(P arg) = x in arg
| urbanslug/ghc | testsuite/tests/patsyn/should_compile/unboxed-bind-bang.hs | bsd-3-clause | 187 | 0 | 11 | 38 | 64 | 32 | 32 | 6 | 1 |
module Main where
import Spark
import System.Environment (getArgs)
main :: IO ()
main = do as <- getArgs
let output | null as = "Usage: spark [natural numbers]"
| otherwise = sparkLine $ (read <$> as :: [Double])
putStrLn output
| HalosGhost/hs | spark/src/Main.hs | isc | 274 | 0 | 13 | 85 | 89 | 45 | 44 | 8 | 1 |
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
import Control.Monad
import Control.Applicative
import Control.Arrow
import Luck.Template
import Test.QuickCheck
import Data.Data
import Data.Maybe
import Data.List
import System.Directory
import System.Process
import Data.Data
data Type = TArrow Type Type
| TList
| TInt
deriving (Show, Data)
sizeT :: Type -> Int
sizeT (TArrow t1 t2) = 1 + sizeT t1 + sizeT t2
sizeT _ = 1
data Term = Var Int
| Abs Int Type Term
| App Type Term Term
deriving (Show, Data)
size :: Term -> Int
size (Var _) = 1
size (Abs _ t e) = 1 + sizeT t + size e
size (App t e1 e2) = 1 + sizeT t + size e1 + size e2
mapping :: Int -> String
mapping 0 = "(undefined :: Int)"
mapping 1 = "id"
mapping 2 = "seq"
mapping 3 = "id"
mapping 4 = "seq"
mapping n = "x" ++ show n
unparse :: Term -> String
unparse (Var x) = mapping x
unparse (Abs n _ e) = "(\\" ++ mapping n ++ " -> " ++ unparse e ++ ")"
unparse (App _ e1 e2) = "(" ++ unparse e1 ++ " " ++ unparse e2 ++ ")"
ghcGen :: Gen (Maybe Term)
ghcGen = $(mkGenQ defFlags{_fileName="examples/STLC.luck", _maxUnroll=2}) tProxy1
--main = do
-- (x:_) <- sample' gen
-- case x of
-- Just t -> putStrLn $ unparse t
-- Nothing -> putStrLn "NOTHING"
runWait c = do
p <- runCommand c
waitForProcess p
generateAndPack :: IO ()
generateAndPack = do
-- | Generate a file
putStrLn "Generating 1100 tests...\n"
let tmp = "examples-template/Main.hs"
funs <- (catMaybes . concat) <$> (replicateM 10 $ sample' ghcGen)
putStrLn "Writing to haskell module...\n"
copyFile "examples-template/ModuleIntro.txt" tmp
let appendString = " " ++ (concat $ intersperse ",\n " (fmap unparse funs))
appendFile tmp appendString
appendFile tmp " ]\n"
compileAndRun :: String -> IO Bool
compileAndRun fileBase = do
let dotO = fileBase ++ ".o"
dotHs = fileBase ++ ".hs"
putStrLn "Compiling...\n"
-- | Compile
runWait $ "rm " ++ dotO
e1 <- runWait $ "ghc-6.12.1 -o Main " ++ dotHs
runWait $ "rm " ++ dotO
-- | Run and test
putStrLn " Running and testing outputs...\n"
e2 <- runWait $ "ghc-6.12.1 -o MainOpt -O2 " ++ dotHs
(ePlain, outPlain, _) <- readProcessWithExitCode "./Main" [] ""
(eOpt, outOpt, _) <- readProcessWithExitCode "./MainOpt" [] ""
return (outPlain == outOpt)
main :: IO ()
main = do
-- Calculate sizes
funs <- (catMaybes . concat) <$> (replicateM 1 $ sample' ghcGen)
-- putStrLn $ show $ sum $ fmap size funs
generateAndPack
b <- compileAndRun "examples-template/Main"
if b then putStrLn "New Batch\n" -- >> main
else do
putStrLn "Counterexample Found!"
files <- getDirectoryContents "examples-template/ghc-counters"
copyFile "examples-template/Main.hs" ("examples-template/ghc-counters/"
++ (show $ length files)
++ ".hs")
| QuickChick/Luck | luck/examples-template/Stlc.hs | mit | 2,935 | 0 | 16 | 717 | 923 | 458 | 465 | 78 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module TrackTest
( trackSpecs
) where
import App.Pieces
import App.UTCTimeP
import Data.Aeson
import Data.Time.Clock.POSIX
import Handler.Track
import TestImport
trackSpecs :: Spec
trackSpecs =
ydescribe "Track API" $ do
let timeStr = "1411034454"
let time = (posixSecondsToUTCTime . fromInteger . read) timeStr
yit "Searches for track by created date. but there is no track" $ do
get $ TrackR $ UTCTimeP time
statusIs 404
yit "let's create new track, request it and remove it" $ do
trackId <- runDB $ insert $ Track time (LatLng 1.2 1.3) [LatLng 23.1 22.45]
get $ TrackR $ UTCTimeP time
runDB (delete trackId)
statusIs 200
yit "DB contains no tracks again" $ do
get $ TrackR $ UTCTimeP time
statusIs 404
yit "Lets try to submit new track with PUT and JSON" $ do
request $ do
setMethod "PUT"
setUrl (TrackR $ UTCTimeP time)
setRequestBody $ encode $ TrackP (UTCTimeP time) [LatLng 23.12 34.3, LatLng 45.3 43.23]
statusIs 204
yit "GET by ID should work now" $ do
get $ TrackR $ UTCTimeP time
statusIs 200
bodyContains "23.12"
yit "OK. Remove this track" $ do
runDB (deleteBy $ UnicTrackDate time)
get $ TrackR $ UTCTimeP time
statusIs 404
yit "Now lets find nearest tracks to our position. But there are no tracks in DB ;(" $ do
get $ NearestTracksR $ LatLngP 10 10
statusIs 200
bodyContains "[]"
yit "Same story. Put track into DB. Search for it. And remove it" $ do
trackId <- runDB $ insert $ Track time (LatLng 80.2 100.3) [LatLng 80.1 100.45]
get $ NearestTracksR $ LatLngP 80 100
runDB (delete trackId)
statusIs 200
bodyContains "80.1"
yit "DB contains no tracks again" $ do
get $ NearestTracksR $ LatLngP 80 100
statusIs 200
bodyContains "[]"
yit "Next is a search by Box model action. same story. Put track to DB, search and remove it" $ do
trackId <- runDB $ insert $ Track time (LatLng 80.2 100.3) [LatLng 80.1 100.45]
get $ TrackByBoxR $ LatLngBoxP (LatLngP 79.3 99.45) (LatLngP 81.2 101.3)
runDB (delete trackId)
statusIs 200
bodyContains "100.45"
| TimeAttack/time-attack-server | tests/TrackTest.hs | mit | 2,594 | 0 | 17 | 942 | 662 | 292 | 370 | 59 | 1 |
------------------------------------------------------------------------
-- |
-- Module : Test.BenchPress
-- Copyright : (c) Johan Tibell 2008
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Benchmarks actions and produces statistics such as min, mean,
-- median, standard deviation, and max execution time. Also computes
-- execution time percentiles. Comes with functions to pretty-print
-- the results.
--
-- Here's an example showing a benchmark of copying a file:
--
-- > import qualified Data.ByteString as B
-- > import System.IO
-- > import Test.BenchPress
-- >
-- > inpath, outpath :: String
-- > inpath = "/tmp/infile"
-- > outpath = "/tmp/outfile"
-- >
-- > blockSize :: Int
-- > blockSize = 4 * 1024
-- >
-- > copyUsingByteString :: Handle -> Handle -> IO ()
-- > copyUsingByteString inf outf = go
-- > where
-- > go = do
-- > bs <- B.hGet inf blockSize
-- > let numRead = B.length bs
-- > if numRead > 0
-- > then B.hPut outf bs >> go
-- > else return ()
-- >
-- > main :: IO ()
-- > main = bench 100 $ do
-- > inf <- openBinaryFile inpath ReadMode
-- > outf <- openBinaryFile outpath WriteMode
-- > copyUsingByteString inf outf
-- > hClose outf
-- > hClose inf
--
------------------------------------------------------------------------
module Test.BenchPress
( -- * Running a benchmark
benchmark,
bench,
benchMany,
-- * Benchmark stats
Stats(..),
-- * Pretty-printing stats
printDetailedStats,
printStatsSummaries,
) where
import Control.Exception (bracket)
import Control.Monad (forM, forM_)
import Data.List (intersperse, sort)
import Data.Time.Clock (NominalDiffTime, diffUTCTime, getCurrentTime)
import qualified Math.Statistics as Math
import Prelude hiding (max, min)
import qualified Prelude
import System.CPUTime (getCPUTime)
import Text.Printf (printf)
-- ---------------------------------------------------------------------
-- Running a benchmark
-- TODO: Make sure that iters is > 0.
-- | @benchmark iters setup teardown action@ runs @action@ @iters@
-- times measuring the execution time of each run. @setup@ and
-- @teardown@ are run before and after each run respectively.
-- @teardown@ is run even if @action@ raises an exception. Returns
-- statistics for both the measured CPU times and wall clock times, in
-- that order.
benchmark :: Int -> IO a -> (a -> IO b) -> (a -> IO c) -> IO (Stats, Stats)
benchmark iters setup teardown action = do
(cpuTimes, wallTimes) <- unzip `fmap` go iters
let xs = sort cpuTimes
cpuStats = Stats
{ min = head xs
, mean = Math.mean xs
, stddev = Math.stddev xs
, median = Math.median xs
, max = last xs
, percentiles = percentiles' xs
}
ys = sort wallTimes
wallStats = Stats
{ min = head ys
, mean = Math.mean ys
, stddev = Math.stddev ys
, median = Math.median ys
, max = last ys
, percentiles = percentiles' ys
}
return (cpuStats, wallStats)
where
go 0 = return []
go n = do
elapsed <- bracket setup teardown $ \a -> do
startWall <- getCurrentTime
startCpu <- getCPUTime
_ <- action a
endCpu <- getCPUTime
endWall <- getCurrentTime
return (picosToMillis $! endCpu - startCpu
,secsToMillis $! endWall `diffUTCTime` startWall)
timings <- go $! n - 1
return $ elapsed : timings
-- | Convenience function that runs a benchmark using 'benchmark' and
-- prints timing statistics using 'printDetailedStats'. The
-- statistics are computed from the measured CPU times. Writes output
-- to standard output.
bench :: Int -> IO a -> IO ()
bench iters action = do
(stats, _) <- benchmark iters (return ()) (const $ return ()) (const action)
printDetailedStats stats
-- | Convenience function that runs several benchmarks using
-- 'benchmark' and prints a timing statistics summary using
-- 'printStatsSummaries'. The statistics are computed from the
-- measured CPU times. Each benchmark has an associated label that is
-- used to identify the benchmark in the printed results. Writes
-- output to standard output.
benchMany :: Int -> [(String, IO a)] -> IO ()
benchMany iters bms = do
results <- forM bms $ \(_, action) ->
benchmark iters (return ()) (const $ return ()) (const action)
printStatsSummaries $ zip (map fst bms) (map fst results)
-- ---------------------------------------------------------------------
-- Benchmark stats
-- | Execution time statistics for a benchmark. All measured times
-- are given in milliseconds.
data Stats = Stats
{ min :: Double
-- ^ Shortest execution time.
, mean :: Double
-- ^ Mean execution time.
, stddev :: Double
-- ^ Execution time standard deviation.
, median :: Double
-- ^ Median execution time.
, max :: Double
-- ^ Longest execution time.
, percentiles :: [(Int, Double)]
-- ^ Execution time divided into percentiles. The first component
-- of the pair is the percentile given as an integer between 0 and
-- 100, inclusive. The second component is the execution time of
-- the slowest iteration within the percentile.
} deriving Show
-- ---------------------------------------------------------------------
-- Pretty-printing stats
-- | Prints detailed statistics. Printed statistics include min,
-- mean, standard deviation, median, and max execution time. Also
-- prints execution time percentiles. Writes output to standard
-- output.
printDetailedStats :: Stats -> IO ()
printDetailedStats stats = do
printSummaryHeader 0 colWidth
printSummary colWidth "" stats
putStrLn ""
putStrLn "Percentiles (ms)"
putStr psTbl
where
columns = map $ \(p, value) -> printf " %3d%% %5.3f" p value
colWidth = columnWidth [stats]
psTbl = unlines $ columns (percentiles stats)
-- | Prints a summary row for each benchmark with an associated label.
-- The summary contains the same statistics as in 'printDetailedStats'
-- except for the execution time percentiles. Writes output to
-- standard output.
printStatsSummaries :: [(String, Stats)] -> IO ()
printStatsSummaries rows = do
printSummaryHeader lblLen colWidth
forM_ rows $ \(label, stats) ->
printSummary colWidth (printf "%-*s" lblLen (label ++ ": ")) stats
where
labels = map fst rows
results = map snd rows
lblLen = maximum (map length labels) + 2
colWidth = columnWidth results
-- | Column headers.
headers :: [String]
headers = ["min", "mean", "+/-sd", "median", "max"]
-- | Computes the minimum column width needed to print the results
-- table.
columnWidth :: [Stats] -> Int
columnWidth = Prelude.max (maximum $ map length headers) . maximum . map width
where
width (Stats min' mean' sd median' max' _) =
maximum $ map (length . (printf "%.3f" :: Double -> String))
[min', mean', sd, median', max']
-- | Pad header with spaces up till desired width.
padHeader :: Int -> String -> String
padHeader w s
| n > w = s
| odd (w - n) = replicate (amt + 1) ' ' ++ s ++ replicate amt ' '
| otherwise = replicate amt ' ' ++ s ++ replicate amt ' '
where
n = length s
amt = (w - n) `div` 2
-- | Print table headers.
printSummaryHeader :: Int -> Int -> IO ()
printSummaryHeader lblLen colWidth = do
putStrLn "Times (ms)"
putStr $ (replicate lblLen ' ') ++ " "
putStrLn $ intercalate " " $ map (padHeader colWidth) headers
-- | Print a row showing a summary of the given stats.
printSummary :: Int -> String -> Stats -> IO ()
printSummary w label (Stats min' mean' sd median' max' _) =
putStrLn $ printf "%s %*.3f %*.3f %*.3f %*.3f %*.3f"
label w min' w mean' w sd w median' w max'
-- ---------------------------------------------------------------------
-- Computing statistics
-- | Compute percentiles given a list of execution times in ascending
-- order.
percentiles' :: [Double] -> [(Int, Double)]
percentiles' xs = zipWith (\p ys -> (p, ys !! (rank p))) ps (repeat xs)
where
n = length xs
rank p = ceiling ((fromIntegral n / 100) * fromIntegral p :: Double) - 1
ps = [50, 66, 75, 80, 90, 95, 98, 99, 100]
-- ---------------------------------------------------------------------
-- Internal utilities
-- | Converts picoseconds to milliseconds.
picosToMillis :: Integer -> Double
picosToMillis t = realToFrac t / (10^(9 :: Int))
-- | Converts seconds to milliseconds.
secsToMillis :: NominalDiffTime -> Double
secsToMillis t = realToFrac t * (10^(3 :: Int))
-- For GHC 6.6 compatibility.
-- | @intercalate xs xss@ inserts the list @xs@ in between the lists
-- in @xss@ and concatenates the result.
intercalate :: [a] -> [[a]] -> [a]
intercalate xs = concat . intersperse xs
| hephaestus-pl/hephaestus | alexandre/feature-modeling/trouble-deps/benchpress-0.2.2.6/Test/BenchPress.hs | mit | 9,371 | 0 | 17 | 2,434 | 1,844 | 1,021 | 823 | 119 | 2 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
module Reflex.Cocos2d.Builder.Base
(
NodeBuilderEnv(..)
, ImmediateNodeBuilderT(..)
, runImmediateNodeBuilderT
) where
import Control.Monad.Exception
import Control.Monad.Identity
import Control.Monad.Reader
import Control.Monad.Ref
import Data.Dependent.Sum
import Debug.Trace
import Graphics.UI.Cocos2d (Size)
import Graphics.UI.Cocos2d.Director
import Graphics.UI.Cocos2d.Node
import Reflex
import Reflex.Host.Class
import Reflex.Cocos2d.Accum.Class
import Reflex.Cocos2d.Builder.Class
import Reflex.Cocos2d.FastTriggerEvent.Class
import Reflex.Cocos2d.Internal.Global (globalScheduler)
-- implementation via
data NodeBuilderEnv t = NodeBuilderEnv
{ parent :: !Node
, windowSize :: !(Size Float)
, frameTicks :: !(Event t Time)
-- different from FireCommand in that it's already lifted into IO
, fireEvent :: !([DSum (EventTrigger t) Identity] -> IO ())
}
newtype ImmediateNodeBuilderT t m a = ImmediateNodeBuilderT { unImmediateNodeBuilderT :: ReaderT (NodeBuilderEnv t) m a }
deriving
( Functor, Applicative, Monad
, MonadFix, MonadIO
, MonadException, MonadAsyncException
, MonadSample t, MonadHold t
)
instance MonadTrans (ImmediateNodeBuilderT t) where
lift = ImmediateNodeBuilderT . lift
instance (Reflex t, Monad m) => NodeBuilder t (ImmediateNodeBuilderT t m) where
{-# INLINABLE getParent #-}
getParent = ImmediateNodeBuilderT $ asks parent
{-# INLINABLE withParent #-}
withParent p' = ImmediateNodeBuilderT . local (\env -> env { parent = p' }) . unImmediateNodeBuilderT
{-# INLINABLE getWindowSize #-}
getWindowSize = ImmediateNodeBuilderT $ asks windowSize
{-# INLINABLE getFrameTicks #-}
getFrameTicks = ImmediateNodeBuilderT $ asks frameTicks
instance PostBuild t m => PostBuild t (ImmediateNodeBuilderT t m) where
{-# INLINABLE getPostBuild #-}
getPostBuild = lift getPostBuild
instance PerformEvent t m => PerformEvent t (ImmediateNodeBuilderT t m) where
type Performable (ImmediateNodeBuilderT t m) = Performable m
{-# INLINABLE performEvent_ #-}
performEvent_ e = lift $ performEvent_ e
{-# INLINABLE performEvent #-}
performEvent e = lift $ performEvent e
instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ImmediateNodeBuilderT t m) where
{-# INLINABLE newEventWithTrigger #-}
newEventWithTrigger = lift . newEventWithTrigger
{-# INLINABLE newFanEventWithTrigger #-}
newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
instance MonadRef m => MonadRef (ImmediateNodeBuilderT t m) where
type Ref (ImmediateNodeBuilderT t m) = Ref m
{-# INLINABLE newRef #-}
newRef = lift . newRef
{-# INLINABLE readRef #-}
readRef = lift . readRef
{-# INLINABLE writeRef #-}
writeRef r = lift . writeRef r
instance MonadAtomicRef m => MonadAtomicRef (ImmediateNodeBuilderT t m) where
{-# INLINABLE atomicModifyRef #-}
atomicModifyRef r = lift . atomicModifyRef r
instance (Ref m ~ Ref IO, MonadRef m, MonadReflexCreateTrigger t m, MonadIO m)
=> TriggerEvent t (ImmediateNodeBuilderT t m) where
{-# INLINABLE newTriggerEvent #-}
newTriggerEvent = do
(e, t) <- newTriggerEventWithOnComplete
return (e, \a -> t a $ return ())
{-# INLINABLE newTriggerEventWithOnComplete #-}
newTriggerEventWithOnComplete = do
fire <- ImmediateNodeBuilderT $ asks fireEvent
(eResult, reResultTrigger) <- newEventWithTriggerRef
return . (,) eResult $ \a cb ->
-- NOTE: we have to make sure the triggering is performed in the main thread
scheduler_performFunctionInCocosThread globalScheduler $ do
me <- readRef reResultTrigger
forM_ (trace "Triggering event posted to cocos thread" me) $ \t -> fire [t ==> a]
cb
{-# INLINABLE newEventWithLazyTriggerWithOnComplete #-}
newEventWithLazyTriggerWithOnComplete f = do
fire <- ImmediateNodeBuilderT $ asks fireEvent
newEventWithTrigger $ \t ->
f $ \a cb ->
-- NOTE: we have to make sure the triggering is performed in the main thread
scheduler_performFunctionInCocosThread globalScheduler $ do
fire $ trace "Triggering event posted to cocos thread" [t ==> a]
cb
instance (Ref m ~ Ref IO, MonadRef m, MonadReflexCreateTrigger t m)
=> FastTriggerEvent t (ImmediateNodeBuilderT t m) where
{-# INLINABLE fastNewTriggerEvent #-}
fastNewTriggerEvent = do
(e, t) <- fastNewTriggerEventWithOnComplete
return (e, \a -> t a $ return ())
{-# INLINABLE fastNewTriggerEventWithOnComplete #-}
fastNewTriggerEventWithOnComplete = do
fire <- ImmediateNodeBuilderT $ asks fireEvent
(eResult, reResultTrigger) <- newEventWithTriggerRef
return . (,) eResult $ \a cb -> do
readRef reResultTrigger >>= mapM_ (\t -> fire [t ==> a])
cb
{-# INLINABLE fastNewEventWithLazyTriggerWithOnComplete #-}
fastNewEventWithLazyTriggerWithOnComplete f = do
fire <- ImmediateNodeBuilderT $ asks fireEvent
newEventWithTrigger $ \t ->
f $ \a cb -> do
fire [t ==> a]
cb
instance MonadAdjust t m => MonadAdjust t (ImmediateNodeBuilderT t m) where
runWithReplace (ImmediateNodeBuilderT a0) a' = ImmediateNodeBuilderT $ runWithReplace a0 (unImmediateNodeBuilderT <$> a')
traverseDMapWithKeyWithAdjust f dm0 dm' =
ImmediateNodeBuilderT $ traverseDMapWithKeyWithAdjust (\k v -> unImmediateNodeBuilderT $ f k v) dm0 dm'
traverseDMapWithKeyWithAdjustWithMove f dm0 dm' =
ImmediateNodeBuilderT $ traverseDMapWithKeyWithAdjustWithMove (\k v -> unImmediateNodeBuilderT $ f k v) dm0 dm'
instance MonadAccum t m => MonadAccum t (ImmediateNodeBuilderT t m) where
runWithAccum zm em = ImmediateNodeBuilderT $ ReaderT $ \r ->
runWithAccum (runReaderT (unImmediateNodeBuilderT zm) r)
((\m -> runReaderT (unImmediateNodeBuilderT m) r) <$> em)
runImmediateNodeBuilderT :: ImmediateNodeBuilderT t m a -> NodeBuilderEnv t -> m a
runImmediateNodeBuilderT = runReaderT . unImmediateNodeBuilderT
| lynnard/reflex-cocos2d | src/Reflex/Cocos2d/Builder/Base.hs | mit | 6,389 | 0 | 18 | 1,331 | 1,517 | 795 | 722 | 117 | 1 |
module Identity where
import Test.QuickCheck
import Test.QuickCheck.Checkers (EqProp, eq, (=-=))
data Identity a = Identity a deriving (Show, Eq)
instance Functor Identity where
fmap f (Identity x) = Identity (f x)
instance Foldable Identity where
foldr f z (Identity x) = f x z
foldl f z (Identity x) = f z x
foldMap f (Identity x) = f x
instance Traversable Identity where
-- traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
traverse f (Identity x) = Identity <$> f x
instance Arbitrary a => Arbitrary (Identity a) where
arbitrary = do
a <- arbitrary
return $ Identity a
instance Eq a => EqProp (Identity a) where
(=-=) = eq
| JoshuaGross/haskell-learning-log | Code/Haskellbook/Foldable/src/Identity.hs | mit | 687 | 0 | 9 | 170 | 258 | 133 | 125 | 18 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UnicodeSyntax #-}
-- |
-- Module: Configuration.Utils.Operators
-- Description: Useful operators for defining functions in an applicative context
-- Copyright: Copyright © 2015 PivotCloud, Inc.
-- License: MIT
-- Maintainer: Lars Kuhtz <[email protected]>
-- Stability: experimental
--
-- Useful operators for defining functions in an applicative context
--
module Configuration.Utils.Operators
( (%)
, (×)
, (<*<)
, (>*>)
, (<$<)
, (>$>)
) where
-- -------------------------------------------------------------------------- --
-- Useful Operators
-- | This operator is an alternative for '$' with a higher precedence. It is
-- suitable for usage within applicative style code without the need to add
-- parenthesis.
--
(%) ∷ (a → b) → a → b
(%) = ($)
infixr 5 %
{-# INLINE (%) #-}
-- | This operator is a UTF-8 version of '%' which is an alternative for '$'
-- with a higher precedence. It is suitable for usage within applicative style
-- code without the need to add parenthesis.
--
-- The hex value of the UTF-8 character × is 0x00d7.
--
-- In VIM type: @Ctrl-V u 00d7@
--
-- You may also define a key binding by adding something like the following line
-- to your vim configuration file:
--
-- > iabbrev <buffer> >< ×
--
(×) ∷ (a → b) → a → b
(×) = ($)
infixr 5 ×
{-# INLINE (×) #-}
{-# DEPRECATED (×) "use '%' instead" #-}
-- | Functional composition for applicative functors.
--
(<*<) ∷ Applicative f ⇒ f (b → c) → f (a → b) → f (a → c)
(<*<) a b = ((.) <$> a) <*> b
infixr 4 <*<
{-# INLINE (<*<) #-}
-- | Functional composition for applicative functors with its arguments
-- flipped.
--
(>*>) ∷ Applicative f ⇒ f (a → b) → f (b → c) → f (a → c)
(>*>) = flip (<*<)
infixr 4 >*>
{-# INLINE (>*>) #-}
-- | Applicative functional composition between a pure function
-- and an applicative function.
--
(<$<) ∷ Functor f ⇒ (b → c) → f (a → b) → f (a → c)
(<$<) a b = (a .) <$> b
infixr 4 <$<
{-# INLINE (<$<) #-}
-- | Applicative functional composition between a pure function
-- and an applicative function with its arguments flipped.
--
(>$>) ∷ Functor f ⇒ f (a → b) → (b → c) → f (a → c)
(>$>) = flip (<$<)
infixr 4 >$>
{-# INLINE (>$>) #-}
| alephcloud/hs-configuration-tools | src/Configuration/Utils/Operators.hs | mit | 2,309 | 0 | 10 | 433 | 452 | 287 | 165 | 35 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE RankNTypes #-}
module Info
( getIdentifierInfo
, getType
) where
import Control.Monad (liftM)
import Data.Generics (GenericQ, mkQ, extQ, gmapQ)
import Data.List (find, sortBy, intersperse)
import Data.Maybe (catMaybes, fromMaybe)
import Data.Typeable (Typeable)
import MonadUtils (liftIO)
import qualified CoreUtils
import qualified Desugar
#if __GLASGOW_HASKELL__ >= 706
import qualified DynFlags
#endif
import qualified GHC
import qualified HscTypes
import qualified NameSet
import qualified Outputable
import qualified PprTyThing
import qualified Pretty
import qualified TcHsSyn
import qualified TcRnTypes
getIdentifierInfo :: FilePath -> String -> GHC.Ghc (Either String String)
getIdentifierInfo file identifier =
withModSummary file $ \m -> do
#if __GLASGOW_HASKELL__ >= 706
GHC.setContext [GHC.IIModule (GHC.moduleName (GHC.ms_mod m))]
#elif __GLASGOW_HASKELL__ >= 704
GHC.setContext [GHC.IIModule (GHC.ms_mod m)]
#else
GHC.setContext [GHC.ms_mod m] []
#endif
GHC.handleSourceError (return . Left . show) $
liftM Right (infoThing identifier)
getType :: FilePath -> (Int, Int) -> GHC.Ghc (Either String [((Int, Int, Int, Int), String)])
getType file (line, col) =
withModSummary file $ \m -> do
p <- GHC.parseModule m
typechecked <- GHC.typecheckModule p
types <- processTypeCheckedModule typechecked (line, col)
return (Right types)
withModSummary :: String -> (HscTypes.ModSummary -> GHC.Ghc (Either String a)) -> GHC.Ghc (Either String a)
withModSummary file action = do
let noPhase = Nothing
target <- GHC.guessTarget file noPhase
GHC.setTargets [target]
let handler err = GHC.printException err >> return GHC.Failed
flag <- GHC.handleSourceError handler (GHC.load GHC.LoadAllTargets)
case flag of
GHC.Failed -> return (Left "Error loading targets")
GHC.Succeeded -> do
modSummary <- getModuleSummary file
case modSummary of
Nothing -> return (Left "Module not found in module graph")
Just m -> action m
getModuleSummary :: FilePath -> GHC.Ghc (Maybe GHC.ModSummary)
getModuleSummary file = do
moduleGraph <- GHC.getModuleGraph
case find (moduleSummaryMatchesFilePath file) moduleGraph of
Nothing -> return Nothing
Just moduleSummary -> return (Just moduleSummary)
moduleSummaryMatchesFilePath :: FilePath -> GHC.ModSummary -> Bool
moduleSummaryMatchesFilePath file moduleSummary =
let location = GHC.ms_location moduleSummary
location_file = GHC.ml_hs_file location
in case location_file of
Just f -> f == file
Nothing -> False
------------------------------------------------------------------------------
-- Most of the following code was taken from the source code of 'ghc-mod' (with
-- some stylistic changes)
--
-- ghc-mod:
-- http://www.mew.org/~kazu/proj/ghc-mod/
-- https://github.com/kazu-yamamoto/ghc-mod/
processTypeCheckedModule :: GHC.TypecheckedModule -> (Int, Int) -> GHC.Ghc [((Int, Int, Int, Int), String)]
processTypeCheckedModule tcm (line, col) = do
let tcs = GHC.tm_typechecked_source tcm
bs = listifySpans tcs (line, col) :: [GHC.LHsBind GHC.Id]
es = listifySpans tcs (line, col) :: [GHC.LHsExpr GHC.Id]
ps = listifySpans tcs (line, col) :: [GHC.LPat GHC.Id]
bts <- mapM (getTypeLHsBind tcm) bs
ets <- mapM (getTypeLHsExpr tcm) es
pts <- mapM (getTypeLPat tcm) ps
#if __GLASGOW_HASKELL__ >= 706
dflags <- DynFlags.getDynFlags
return $ map (toTup dflags) $
#else
return $ map toTup $
#endif
sortBy cmp $ catMaybes $ concat [ets, bts, pts]
where
cmp (a, _) (b, _)
| a `GHC.isSubspanOf` b = LT
| b `GHC.isSubspanOf` a = GT
| otherwise = EQ
#if __GLASGOW_HASKELL__ >= 706
toTup :: GHC.DynFlags -> (GHC.SrcSpan, GHC.Type) -> ((Int, Int, Int, Int), String)
toTup dflags (spn, typ) = (fourInts spn, pretty dflags typ)
#else
toTup :: (GHC.SrcSpan, GHC.Type) -> ((Int, Int, Int, Int), String)
toTup (spn, typ) = (fourInts spn, pretty typ)
#endif
fourInts :: GHC.SrcSpan -> (Int, Int, Int, Int)
fourInts = fromMaybe (0, 0, 0, 0) . getSrcSpan
getSrcSpan :: GHC.SrcSpan -> Maybe (Int, Int, Int, Int)
getSrcSpan (GHC.RealSrcSpan spn) =
Just (GHC.srcSpanStartLine spn
, GHC.srcSpanStartCol spn
, GHC.srcSpanEndLine spn
, GHC.srcSpanEndCol spn)
getSrcSpan _ = Nothing
getTypeLHsBind :: GHC.TypecheckedModule -> GHC.LHsBind GHC.Id -> GHC.Ghc (Maybe (GHC.SrcSpan, GHC.Type))
getTypeLHsBind _ (GHC.L spn GHC.FunBind{GHC.fun_matches = GHC.MatchGroup _ typ}) = return $ Just (spn, typ)
getTypeLHsBind _ _ = return Nothing
getTypeLHsExpr :: GHC.TypecheckedModule -> GHC.LHsExpr GHC.Id -> GHC.Ghc (Maybe (GHC.SrcSpan, GHC.Type))
getTypeLHsExpr tcm e = do
hs_env <- GHC.getSession
(_, mbe) <- liftIO $ Desugar.deSugarExpr hs_env modu rn_env ty_env e
return ()
case mbe of
Nothing -> return Nothing
Just expr -> return $ Just (GHC.getLoc e, CoreUtils.exprType expr)
where
modu = GHC.ms_mod $ GHC.pm_mod_summary $ GHC.tm_parsed_module tcm
rn_env = TcRnTypes.tcg_rdr_env $ fst $ GHC.tm_internals_ tcm
ty_env = TcRnTypes.tcg_type_env $ fst $ GHC.tm_internals_ tcm
getTypeLPat :: GHC.TypecheckedModule -> GHC.LPat GHC.Id -> GHC.Ghc (Maybe (GHC.SrcSpan, GHC.Type))
getTypeLPat _ (GHC.L spn pat) = return $ Just (spn, TcHsSyn.hsPatType pat)
listifySpans :: Typeable a => GHC.TypecheckedSource -> (Int, Int) -> [GHC.Located a]
listifySpans tcs lc = listifyStaged TypeChecker p tcs
where
p (GHC.L spn _) = GHC.isGoodSrcSpan spn && spn `GHC.spans` lc
listifyStaged :: Typeable r => Stage -> (r -> Bool) -> GenericQ [r]
listifyStaged s p = everythingStaged s (++) [] ([] `mkQ` (\x -> [x | p x]))
#if __GLASGOW_HASKELL__ >= 706
pretty :: GHC.DynFlags -> GHC.Type -> String
pretty dflags =
#else
pretty :: GHC.Type -> String
pretty =
#endif
Pretty.showDocWith Pretty.OneLineMode
#if __GLASGOW_HASKELL__ >= 706
. Outputable.withPprStyleDoc dflags
#else
. Outputable.withPprStyleDoc
#endif
(Outputable.mkUserStyle Outputable.neverQualify Outputable.AllTheWay)
. PprTyThing.pprTypeForUser False
------------------------------------------------------------------------------
-- The following was taken from 'ghc-syb-utils'
--
-- ghc-syb-utils:
-- https://github.com/nominolo/ghc-syb
-- | Ghc Ast types tend to have undefined holes, to be filled
-- by later compiler phases. We tag Asts with their source,
-- so that we can avoid such holes based on who generated the Asts.
data Stage = Parser | Renamer | TypeChecker deriving (Eq,Ord,Show)
-- | Like 'everything', but avoid known potholes, based on the 'Stage' that
-- generated the Ast.
everythingStaged :: Stage -> (r -> r -> r) -> r -> GenericQ r -> GenericQ r
everythingStaged stage k z f x
| (const False `extQ` postTcType `extQ` fixity `extQ` nameSet) x = z
| otherwise = foldl k (f x) (gmapQ (everythingStaged stage k z f) x)
where nameSet = const (stage `elem` [Parser,TypeChecker]) :: NameSet.NameSet -> Bool
postTcType = const (stage<TypeChecker) :: GHC.PostTcType -> Bool
fixity = const (stage<Renamer) :: GHC.Fixity -> Bool
------------------------------------------------------------------------------
-- The following code was taken from GHC's ghc/InteractiveUI.hs (with some
-- stylistic changes)
infoThing :: String -> GHC.Ghc String
infoThing str = do
names <- GHC.parseName str
mb_stuffs <- mapM GHC.getInfo names
let filtered = filterOutChildren (\(t,_f,_i) -> t) (catMaybes mb_stuffs)
unqual <- GHC.getPrintUnqual
#if __GLASGOW_HASKELL__ >= 706
dflags <- DynFlags.getDynFlags
return $ Outputable.showSDocForUser dflags unqual $
#else
return $ Outputable.showSDocForUser unqual $
#endif
Outputable.vcat (intersperse (Outputable.text "") $ map (pprInfo False) filtered)
-- Filter out names whose parent is also there Good
-- example is '[]', which is both a type and data
-- constructor in the same type
filterOutChildren :: (a -> HscTypes.TyThing) -> [a] -> [a]
filterOutChildren get_thing xs
= filter (not . has_parent) xs
where
all_names = NameSet.mkNameSet (map (GHC.getName . get_thing) xs)
#if __GLASGOW_HASKELL__ >= 704
has_parent x = case HscTypes.tyThingParent_maybe (get_thing x) of
#else
has_parent x = case PprTyThing.pprTyThingParent_maybe (get_thing x) of
#endif
Just p -> GHC.getName p `NameSet.elemNameSet` all_names
Nothing -> False
#if __GLASGOW_HASKELL__ >= 706
pprInfo :: PprTyThing.PrintExplicitForalls -> (HscTypes.TyThing, GHC.Fixity, [GHC.ClsInst]) -> Outputable.SDoc
#else
pprInfo :: PprTyThing.PrintExplicitForalls -> (HscTypes.TyThing, GHC.Fixity, [GHC.Instance]) -> Outputable.SDoc
#endif
pprInfo pefas (thing, fixity, insts) =
PprTyThing.pprTyThingInContextLoc pefas thing
Outputable.$$ show_fixity fixity
Outputable.$$ Outputable.vcat (map GHC.pprInstance insts)
where
show_fixity fix
| fix == GHC.defaultFixity = Outputable.empty
| otherwise = Outputable.ppr fix Outputable.<+> Outputable.ppr (GHC.getName thing)
| bennofs/hdevtools | src/Info.hs | mit | 9,358 | 0 | 17 | 1,883 | 2,662 | 1,392 | 1,270 | 145 | 3 |
import Data.List
import Data.Time
data DatabaseItem = DbString String
| DbNumber Integer
| DbDate UTCTime
deriving (Eq, Ord, Show)
utctime2 :: UTCTime
utctime2 = UTCTime (fromGregorian 1921 5 1) (secondsToDiffTime 34123)
utctime3 :: UTCTime
utctime3 = UTCTime (fromGregorian 2001 5 1) (secondsToDiffTime 35234)
theDatabase :: [DatabaseItem]
theDatabase =
[ DbDate (UTCTime (fromGregorian 1911 5 1) (secondsToDiffTime 34123))
, DbNumber 9001
, DbString "Hello, world!"
, DbDate (UTCTime (fromGregorian 1921 5 1) (secondsToDiffTime 34123))
]
theDatabase2 :: [DatabaseItem]
theDatabase2 =
[ DbDate (UTCTime (fromGregorian 1911 5 1) (secondsToDiffTime 34123))
, DbNumber 9001
, DbNumber 9002
, DbNumber 9003
, DbString "Hello, world!"
, DbString "sup y'all"
, DbDate (UTCTime (fromGregorian 1921 5 1) (secondsToDiffTime 34123))
, DbDate (UTCTime (fromGregorian 1921 5 2) (secondsToDiffTime 34123))
, DbDate (UTCTime (fromGregorian 2001 5 3) (secondsToDiffTime 34123))
]
filterDbDate :: [DatabaseItem] -> [UTCTime]
filterDbDate = foldr f []
where f (DbDate x) b = x : b
f _ b = b
filterDbNumber :: [DatabaseItem] -> [Integer]
filterDbNumber = foldr f []
where f (DbNumber x) b = x : b
f _ b = b
-- unsafe because it can't deal with empty lists
mostRecent :: [DatabaseItem] -> UTCTime
mostRecent = last . sort . filterDbDate
-- safe cuz it can handle empty lists
sumDb :: [DatabaseItem] -> Integer
sumDb = sum . filterDbNumber
avgDb :: [DatabaseItem] -> Double
avgDb ds = fromIntegral $ div t l
where
t :: Integer
t = sum ns
l :: Integer
l = toInteger $ length ns
ns :: [Integer]
ns = filterDbNumber ds
| JoshuaGross/haskell-learning-log | Code/Haskellbook/DataProc.hs | mit | 1,761 | 0 | 10 | 421 | 598 | 315 | 283 | 47 | 2 |
{-# LANGUAGE QuasiQuotes #-}
module Y2018.M01.D10.Solution where
{--
Today's Haskell exercise is a bit of a warming-up exercise. Today we'll store
packet information in the packet table (the structure of the table matching
Packet (see Y2017.M12.D20.Solution), and also write the fetch function that
retrieves packet information from the database from a given id (which we will
provide later).
We do this for auditing purposes. We wish to store not only the articles that
we store, but also information about what we stored and when. Storing packet
information is a piece of that puzzle.
... hm. Actually, I don't think a fetch function is necessary given how I'm
planning auditing. We shall see. For today, just write the toRow function
--}
import Control.Arrow (second)
import Control.Monad (void)
import Control.Monad.Writer (runWriter)
import Data.Aeson
import Data.Functor.Identity (Identity)
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.SqlQQ
import Database.PostgreSQL.Simple.ToField (toField)
import Database.PostgreSQL.Simple.ToRow
-- below import available via 1HaskellADay git repository
import Control.DList (dlToList)
import Data.Logger
import Data.LookupTable (LookupTable)
import Store.SQL.Connection (withConnection)
import Store.SQL.Util.Indexed
import Store.SQL.Util.Logging
import Store.SQL.Util.LookupTable
import Y2017.M12.D20.Solution -- for Packet
import Y2017.M12.D27.Solution hiding (pa) -- for DatedArticle
import Y2017.M12.D29.Solution hiding (etl) -- for BlockParser
import Y2018.M01.D02.Solution hiding (etl, storeAncilliary, parseArticles)
import Y2018.M01.D04.Solution hiding (etl, storeAncilliary)
import Y2018.M01.D08.Solution -- for storeAncilliary
insertPacketStmt :: Query
insertPacketStmt =
[sql|INSERT INTO packet (view,prev,next,total,count) VALUES (?,?,?,?,?)|]
insertPackets :: Connection -> [Packet] -> IO ()
insertPackets conn = void . executeMany conn insertPacketStmt
instance ToRow Packet where
toRow (Pack v c t n p _) = [toField v, toField p] ++ map toField [n,t,c]
{--
Using Y2017.M12.D20.Exercise.readSample, load in the packet and store its
information.
--}
{-- BONUS -----------------------------------------------------------------
Rewrite the etl-process to store the packet information (that is: don't discard
packet information anymore) along with the articles. Remember to include logging
functionality as well!
--}
readStorePacket :: Connection -> FilePath -> IO Packet
readStorePacket conn jsonFile =
readSample jsonFile >>= \pack ->
insertPackets conn [pack] >>
return pack
parseArticles :: FromJSON a => BlockParser Identity a -> Packet
-> ([(Block,Maybe (DatedArticle a))], [String])
parseArticles generator =
second dlToList . runWriter . elide generator apArt . rows
-- so we want to do all the work of the ETL AND return the indexed articles and
-- packet for down-the-road work, as necessary
gruntWerk :: LookupTable -> BlockParser Identity Authors
-> (Connection -> [IxValue (DatedArticle Authors)] -> IO ())
-> Connection -> Packet -> IO (IxValue (DatedArticle Authors))
gruntWerk lk generator ancillaryFn conn pack =
let (arts,logentries) = parseArticles generator pack in
insertLogEntries conn lk [mkentry ("Inserted "
++ show (pack { rows = [] }))] >>
insertLogEntries conn lk (map mkentry logentries) >>
storeArticles conn arts >>= \ixarts ->
storeAncilliary conn ixarts >>
insertLogEntries conn lk [mkentry ("stored " ++ (show $ length ixarts)
++ " articles")] >>
return (last ixarts)
where mkentry = Entry INFO "etl_pilot" "Y2018.M01.D10.Solution"
etl :: BlockParser Identity Authors
-> (Connection -> [IxValue (DatedArticle Authors)] -> IO ())
-> Connection -> FilePath -> IO ()
etl generator ancillaryFn conn jsonFile =
lookupTable conn "severity_lk" >>= \lk ->
readStorePacket conn jsonFile >>= \pack ->
void (gruntWerk lk generator ancillaryFn conn pack)
| geophf/1HaskellADay | exercises/HAD/Y2018/M01/D10/Solution.hs | mit | 4,108 | 0 | 19 | 764 | 850 | 469 | 381 | 61 | 1 |
module ProjectEuler.Problem34
( problem
) where
import Data.Char
import Petbox
import ProjectEuler.Types
problem :: Problem
problem = pureProblem 34 Solved result
verify :: Int -> Bool
verify x = sum (map (factorial . digitToInt) (show x)) == x
result :: Int
result = sum $ filter verify [3..99999]
| Javran/Project-Euler | src/ProjectEuler/Problem34.hs | mit | 309 | 0 | 10 | 58 | 110 | 60 | 50 | 11 | 1 |
module Game.Position where
import qualified Game.Resources as R
type Position = (Int, Int)
-- | Lyhenne fromIntegral funktiolle
fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
-- | Muuntaa pelikoordinaatit isometrisiksi ruutukoordinaateiksi
toIsom :: Position -> (Float, Float)
toIsom (x, y) = ((fi y * hw) + (fi x * hw), (fi x * hh) - (fi y * hh))
where
hw = R.tileWidth / 2.0
hh = R.tileHeight / 2.0
-- | Muuntaa ruutukoordinaatit pelikoordinaateiksi
fromIsom :: (Float, Float) -> Position
fromIsom (x, y) = (floor ((x + 2*y) / R.tileWidth), floor (-(2*y - x) / R.tileWidth))
-- | Muuntaa hiiren sijainnin pelikoordinaatiksi
convertMouse :: (Float, Float) -> (Float, Float) -> Position
convertMouse (sx, sy) (x, y) = let (x', y') = fromIsom (x - sx, y + 64 - sy) in (y' + 1, x')
| maqqr/psycho-bongo-fight | Game/Position.hs | mit | 813 | 0 | 12 | 168 | 345 | 196 | 149 | 13 | 1 |
module FeatureModel.Parsers.SPLOT.SPLOT2FeatureModel where
import qualified FeatureModel.Types as FM
import FeatureModel.Parsers.SPLOT.AbsSPLOT
modeloSPLOT = SPLOT (FeatureModel (Feature (FName2 (Ident "r")) [SetRelation (FName2 (Ident "r_6")) (Cardinality 2 1) [GroupedFeature (FName2 (Ident "r_6_7")) [BinRelation (Cardinality 1 1) (SolitaryFeature (FName2 (Ident "r_6_7_9")) [SetRelation (FName2 (Ident "r_6_7_9_10")) (Cardinality 3 1) [LGroupedFeature (FName2 (Ident "r_6_7_9_10_11")),LGroupedFeature (FName2 (Ident "r_6_7_9_10_15")),LGroupedFeature (FName2 (Ident "r_6_7_9_10_16"))]])],GroupedFeature (FName2 (Ident "r_6_8")) [BinRelation (Cardinality 1 1) (SolitaryFeature (FName2 (Ident "r_6_8_19")) [SetRelation (FName2 (Ident "r_6_8_19_20")) (Cardinality 2 1) [LGroupedFeature (FName2 (Ident "r_6_8_19_20_21")),LGroupedFeature (FName2 (Ident "r_6_8_19_20_23"))]])]]]) [Require (FName2 (Ident "r_6_7_9_10_16")) (FName1 (Ident "constraint_1")) (FName2 (Ident "r_6_8_19_21"))])
modelo1=SPLOT(FeatureModel (Feature (FName2 (Ident "r"))[]) [])
modelo2=SPLOT(FeatureModel (Feature (FName2 (Ident "r"))[BinRelation (Cardinality 1 1) (LSolitaryFeature (FName2 (Ident "r_6_7")))]) [])
splotToFeatureModel :: SPLOTModel -> FM.FeatureModel
splotToFeatureModel (SPLOT (FeatureModel r cs)) =
let
fmTree = featureTreeSPLOT2FeatureTree r-- foi decompor a árvore de features
constraints = map constraintToExpression cs -- para iniciar traduzir primeiro fmTreemap constraintToFeatureModel cs
in FM.FeatureModel fmTree constraints
featureTreeSPLOT2FeatureTree :: Feature -> FM.FeatureTree
featureTreeSPLOT2FeatureTree (Feature n cs) = -- n = FName cs =[Child]
FM.Root r cs'
where
r = createFeature n FM.Mandatory (group cs) -- group = groupType
cs' = case group cs of
FM.BasicFeature -> (map child2Feature cs)
otherwise -> let
[(SetRelation _ _ gs)] = cs
in map groupedFeature2Feature gs
constraintToExpression :: Constraint -> FM.FeatureExpression
constraintToExpression (Require f1 _ f2) = FM.Or (FM.Not(FM.FeatureRef (fname f1))) (FM.FeatureRef (fname f2))
constraintToExpression (Exclude f1 f2 _) = FM.Not (FM.And (FM.FeatureRef (fname f1)) (FM.FeatureRef (fname f2)))
{-
(Exclude f1 f2 _) -> FM.Not (FM.And ((FM.FeatureRef s1), (FM.FeatureRef s2)))
where
s1= fname f1
s2= fname f2-}
fname ::FName -> String
fname (FName1 (Ident s)) = s
fname (FName2 (Ident s)) = s
child2Feature :: Child -> FM.FeatureTree
child2Feature (SetRelation _ _ gfs) = error "could not call Set Relation at others..."
child2Feature (BinRelation c (LSolitaryFeature n)) = FM.Leaf r
where
r = createFeature n (ftype c) FM.BasicFeature
child2Feature (BinRelation c (SolitaryFeature n cs)) = FM.Root r cs'
where
r = createFeature n (ftype c) (group cs)
cs' = case group cs of
FM.BasicFeature -> (map child2Feature cs)
otherwise -> let
[(SetRelation _ _ gs)] = cs
in map groupedFeature2Feature gs
groupedFeature2Feature (GroupedFeature n cs) = FM.Root r (map child2Feature cs)
where
r = createFeature n FM.Optional (group cs)
groupedFeature2Feature (LGroupedFeature n) = FM.Leaf r
where
r = createFeature n FM.Optional FM.BasicFeature
createFeature :: FName -> FM.FeatureType -> FM.GroupType -> FM.Feature
createFeature (FName2 (Ident n)) t g = FM.Feature n n t "" g []
ftype :: Cardinality -> FM.FeatureType
ftype (Cardinality 1 1) = FM.Mandatory
ftype (_) = FM.Optional
group :: [Child] -> FM.GroupType
group [(SetRelation _ c _)] =
case c of
(Cardinality 1 1) -> FM.AlternativeFeature
(Cardinality _ 1) -> FM.OrFeature
group _ = FM.BasicFeature
| hephaestus-pl/hephaestus | alexandre/feature-modeling/src/FeatureModel/Parsers/SPLOT/SPLOT2FeatureModel.hs | mit | 3,745 | 0 | 25 | 674 | 1,359 | 685 | 674 | 53 | 2 |
{-# LANGUAGE LambdaCase #-}
module Butter.Core where
import Butter.Core.BlockDownload
import Butter.Core.MetaInfo
import Butter.Core.Peer
import Butter.Core.Torrent
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad.IO.Class
import qualified Data.Map as Map
import qualified Data.Vector as Vector
type DownloadStrategy = TorrentDownload -> IO [DownloadCommand]
data DownloadCommand = DownloadPiece Piece Int Int
| Abort
startDownload :: TorrentDownload -> DownloadStrategy -> IO ()
startDownload td st = loop
where loop = do
stage <- tsStage <$> readTVarIO (tdStatus td)
case stage of
TDownloading -> do
threadDelay $ 1000 * 1000
liftIO $ onLoopTick td st
loop
_ -> return ()
onLoopTick :: TorrentDownload -> DownloadStrategy -> IO ()
onLoopTick td st = st td >>= mapM_ handleCommand
where handleCommand :: DownloadCommand -> IO ()
handleCommand = \case
(DownloadPiece piece idx size) ->
atomically $ modifyTVar
(tdPieceStatus td Vector.! idx)
flagPieceDownload
flagPieceDownload = undefined
| yamadapc/butter-core | src/Butter/Core.hs | mit | 1,274 | 0 | 15 | 366 | 310 | 166 | 144 | 34 | 2 |
{-# LANGUAGE RankNTypes, DeriveAnyClass, TypeOperators #-}
--------------------------------------------------
--------------------------------------------------
module Enumerate.Function.Types where
--------------------------------------------------
import Enumerate.Types
import Enumerate.Function.Extra
--------------------------------------------------
--------------------------------------------------
import "exceptions" Control.Monad.Catch (MonadThrow)
--------------------------------------------------
-- import "deepseq" Control.DeepSeq
--------------------------------------------------
import "base" Data.Ix (Ix)
--------------------------------------------------
--------------------------------------------------
{-| Used by 'Enumerate.Function.Reify.getJectivityM'.
-}
data Jectivity
= Injective
| Surjective
| Bijective
deriving
( Enum, Bounded, Ix
, Show, Read
, Eq, Ord
, Generic, Data
, NFData, Enumerable
)
--------------------------------------------------
--------------------------------------------------
{- with proof:
the signature of the inverse of (a -> b)
data Jectivity a b
= Unjective (b -> [a])
| Injective (b -> Maybe a)
| Surjective (b -> NonEmpty a)
| Bijective (b -> a)
data Jectivity_ = Injective_ | Surjective_ | Bijective_
jectivity :: () => (a -> b) -> Jectivity a b
jectivity_ :: Jectivity -> Maybe Jectivity_
OR
newtype Injection a b = Injection (a -> b) (b -> Maybe a)
newtype Surjection a b = Surjection (a -> b) (b -> NonEmpty a)
newtype Bijection a b = Bijection (a -> b) (b -> a)
-- | each input has zero-or-one output
newtype a :?->: b = Injection (a -> b) (b -> Maybe a)
-- | each input has one-or-more output
newtype a :+->: b = Surjection (a -> b) (b -> NonEmpty a)
-- | each input has one output
newtype a :<->: b = Bijection (a -> b) (b -> a)
toInjection :: (a -> b) -> Maybe (Injection a b)
toSurjection :: (a -> b) -> Maybe (Surjection a b)
toBijection :: (a -> b) -> Maybe (Bijection a b)
asInjection :: (a :<->: b) -> (a :?->: b)
asInjection (Bijection f g) = Injection f (Just <$> g) -- pure
asSurjection :: (a :<->: b) -> (a :+->: b)
asSurjection (Bijection f g) = Surjection f ((:|[]) <$> g) -- pure
-}
--------------------------------------------------
--------------------------------------------------
{-| A /safely/-partial function.
i.e. a function that:
* Fails only via the 'throwM' method of 'MonadThrow'.
* Succeeds only via the 'return' method of 'Monad'.
-}
type Partial a b = (forall m. MonadThrow m => a -> m b)
--------------------------------------------------
--------------------------------------------------
{-| Operator (infix) for 'Partial'.
NAMING: Looks like the "function arrow" @(->)@.
-}
type (a -?> b) = Partial a b
--------------------------------------------------
--------------------------------------------------
-- (by necessity) @'KnownNat' ('Cardinality' a)@
--class (KnownNat (Cardinality a)) => Enumerable a where
-- type Cardinality a :: Nat -- TODO
{- too much boilerplate
e.g.
instance Enumerable Jectivity
errors with:
No instance for (KnownNat (Cardinality Jectivity))
arising from the superclasses of an instance declaration
In the instance declaration for `Enumerable Jectivity'
would need:
instance (KnownNat (Cardinality Jectivity)) => Enumerable Jectivity
-}
-------------------------------------------------- | sboosali/enumerate | enumerate-function/sources/Enumerate/Function/Types.hs | mit | 3,437 | 0 | 9 | 553 | 175 | 114 | 61 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-loadbalancer-subnetmapping.html
module Stratosphere.ResourceProperties.ElasticLoadBalancingV2LoadBalancerSubnetMapping where
import Stratosphere.ResourceImports
-- | Full data type definition for
-- ElasticLoadBalancingV2LoadBalancerSubnetMapping. See
-- 'elasticLoadBalancingV2LoadBalancerSubnetMapping' for a more convenient
-- constructor.
data ElasticLoadBalancingV2LoadBalancerSubnetMapping =
ElasticLoadBalancingV2LoadBalancerSubnetMapping
{ _elasticLoadBalancingV2LoadBalancerSubnetMappingAllocationId :: Val Text
, _elasticLoadBalancingV2LoadBalancerSubnetMappingSubnetId :: Val Text
} deriving (Show, Eq)
instance ToJSON ElasticLoadBalancingV2LoadBalancerSubnetMapping where
toJSON ElasticLoadBalancingV2LoadBalancerSubnetMapping{..} =
object $
catMaybes
[ (Just . ("AllocationId",) . toJSON) _elasticLoadBalancingV2LoadBalancerSubnetMappingAllocationId
, (Just . ("SubnetId",) . toJSON) _elasticLoadBalancingV2LoadBalancerSubnetMappingSubnetId
]
-- | Constructor for 'ElasticLoadBalancingV2LoadBalancerSubnetMapping'
-- containing required fields as arguments.
elasticLoadBalancingV2LoadBalancerSubnetMapping
:: Val Text -- ^ 'elbvlbsmAllocationId'
-> Val Text -- ^ 'elbvlbsmSubnetId'
-> ElasticLoadBalancingV2LoadBalancerSubnetMapping
elasticLoadBalancingV2LoadBalancerSubnetMapping allocationIdarg subnetIdarg =
ElasticLoadBalancingV2LoadBalancerSubnetMapping
{ _elasticLoadBalancingV2LoadBalancerSubnetMappingAllocationId = allocationIdarg
, _elasticLoadBalancingV2LoadBalancerSubnetMappingSubnetId = subnetIdarg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-loadbalancer-subnetmapping.html#cfn-elasticloadbalancingv2-loadbalancer-subnetmapping-allocationid
elbvlbsmAllocationId :: Lens' ElasticLoadBalancingV2LoadBalancerSubnetMapping (Val Text)
elbvlbsmAllocationId = lens _elasticLoadBalancingV2LoadBalancerSubnetMappingAllocationId (\s a -> s { _elasticLoadBalancingV2LoadBalancerSubnetMappingAllocationId = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-loadbalancer-subnetmapping.html#cfn-elasticloadbalancingv2-loadbalancer-subnetmapping-subnetid
elbvlbsmSubnetId :: Lens' ElasticLoadBalancingV2LoadBalancerSubnetMapping (Val Text)
elbvlbsmSubnetId = lens _elasticLoadBalancingV2LoadBalancerSubnetMappingSubnetId (\s a -> s { _elasticLoadBalancingV2LoadBalancerSubnetMappingSubnetId = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/ElasticLoadBalancingV2LoadBalancerSubnetMapping.hs | mit | 2,719 | 0 | 13 | 222 | 267 | 153 | 114 | 29 | 1 |
{-# LANGUAGE BangPatterns #-}
{-| Implementation of the Ganeti Query2 server.
-}
{-
Copyright (C) 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 Ganeti.Query.Server
( ConfigReader
, prepQueryD
, runQueryD
) where
import Control.Applicative
import Control.Concurrent
import Control.Exception
import Data.Bits (bitSize)
import Data.Maybe
import qualified Network.Socket as S
import qualified Text.JSON as J
import Text.JSON (showJSON, JSValue(..))
import System.Info (arch)
import qualified Ganeti.Constants as C
import Ganeti.Errors
import qualified Ganeti.Path as Path
import Ganeti.Daemon
import Ganeti.Objects
import qualified Ganeti.Config as Config
import Ganeti.BasicTypes
import Ganeti.Logging
import Ganeti.Luxi
import Ganeti.OpCodes (TagObject(..))
import qualified Ganeti.Query.Language as Qlang
import Ganeti.Query.Query
import Ganeti.Query.Filter (makeSimpleFilter)
-- | A type for functions that can return the configuration when
-- executed.
type ConfigReader = IO (Result ConfigData)
-- | Helper for classic queries.
handleClassicQuery :: ConfigData -- ^ Cluster config
-> Qlang.ItemType -- ^ Query type
-> [Either String Integer] -- ^ Requested names
-- (empty means all)
-> [String] -- ^ Requested fields
-> Bool -- ^ Whether to do sync queries or not
-> IO (GenericResult GanetiException JSValue)
handleClassicQuery _ _ _ _ True =
return . Bad $ OpPrereqError "Sync queries are not allowed" ECodeInval
handleClassicQuery cfg qkind names fields _ = do
let flt = makeSimpleFilter (nameField qkind) names
qr <- query cfg True (Qlang.Query qkind fields flt)
return $ showJSON <$> (qr >>= queryCompat)
-- | Minimal wrapper to handle the missing config case.
handleCallWrapper :: Result ConfigData -> LuxiOp -> IO (ErrorResult JSValue)
handleCallWrapper (Bad msg) _ =
return . Bad . ConfigurationError $
"I do not have access to a valid configuration, cannot\
\ process queries: " ++ msg
handleCallWrapper (Ok config) op = handleCall config op
-- | Actual luxi operation handler.
handleCall :: ConfigData -> LuxiOp -> IO (ErrorResult JSValue)
handleCall cdata QueryClusterInfo =
let cluster = configCluster cdata
hypervisors = clusterEnabledHypervisors cluster
def_hv = case hypervisors of
x:_ -> showJSON x
[] -> JSNull
bits = show (bitSize (0::Int)) ++ "bits"
arch_tuple = [bits, arch]
obj = [ ("software_version", showJSON C.releaseVersion)
, ("protocol_version", showJSON C.protocolVersion)
, ("config_version", showJSON C.configVersion)
, ("os_api_version", showJSON $ maximum C.osApiVersions)
, ("export_version", showJSON C.exportVersion)
, ("architecture", showJSON arch_tuple)
, ("name", showJSON $ clusterClusterName cluster)
, ("master", showJSON $ clusterMasterNode cluster)
, ("default_hypervisor", def_hv)
, ("enabled_hypervisors", showJSON hypervisors)
, ("hvparams", showJSON $ clusterHvparams cluster)
, ("os_hvp", showJSON $ clusterOsHvp cluster)
, ("beparams", showJSON $ clusterBeparams cluster)
, ("osparams", showJSON $ clusterOsparams cluster)
, ("ipolicy", showJSON $ clusterIpolicy cluster)
, ("nicparams", showJSON $ clusterNicparams cluster)
, ("ndparams", showJSON $ clusterNdparams cluster)
, ("diskparams", showJSON $ clusterDiskparams cluster)
, ("candidate_pool_size",
showJSON $ clusterCandidatePoolSize cluster)
, ("master_netdev", showJSON $ clusterMasterNetdev cluster)
, ("master_netmask", showJSON $ clusterMasterNetmask cluster)
, ("use_external_mip_script",
showJSON $ clusterUseExternalMipScript cluster)
, ("volume_group_name", showJSON $ clusterVolumeGroupName cluster)
, ("drbd_usermode_helper",
maybe JSNull showJSON (clusterDrbdUsermodeHelper cluster))
, ("file_storage_dir", showJSON $ clusterFileStorageDir cluster)
, ("shared_file_storage_dir",
showJSON $ clusterSharedFileStorageDir cluster)
, ("maintain_node_health",
showJSON $ clusterMaintainNodeHealth cluster)
, ("ctime", showJSON $ clusterCtime cluster)
, ("mtime", showJSON $ clusterMtime cluster)
, ("uuid", showJSON $ clusterUuid cluster)
, ("tags", showJSON $ clusterTags cluster)
, ("uid_pool", showJSON $ clusterUidPool cluster)
, ("default_iallocator",
showJSON $ clusterDefaultIallocator cluster)
, ("reserved_lvs", showJSON $ clusterReservedLvs cluster)
, ("primary_ip_version",
showJSON . ipFamilyToVersion $ clusterPrimaryIpFamily cluster)
, ("prealloc_wipe_disks",
showJSON $ clusterPreallocWipeDisks cluster)
, ("hidden_os", showJSON $ clusterHiddenOs cluster)
, ("blacklisted_os", showJSON $ clusterBlacklistedOs cluster)
]
in return . Ok . J.makeObj $ obj
handleCall cfg (QueryTags kind) =
let tags = case kind of
TagCluster -> Ok . clusterTags $ configCluster cfg
TagGroup name -> groupTags <$> Config.getGroup cfg name
TagNode name -> nodeTags <$> Config.getNode cfg name
TagInstance name -> instTags <$> Config.getInstance cfg name
in return (J.showJSON <$> tags)
handleCall cfg (Query qkind qfields qfilter) = do
result <- query cfg True (Qlang.Query qkind qfields qfilter)
return $ J.showJSON <$> result
handleCall _ (QueryFields qkind qfields) = do
let result = queryFields (Qlang.QueryFields qkind qfields)
return $ J.showJSON <$> result
handleCall cfg (QueryNodes names fields lock) =
handleClassicQuery cfg (Qlang.ItemTypeOpCode Qlang.QRNode)
(map Left names) fields lock
handleCall cfg (QueryGroups names fields lock) =
handleClassicQuery cfg (Qlang.ItemTypeOpCode Qlang.QRGroup)
(map Left names) fields lock
handleCall cfg (QueryJobs names fields) =
handleClassicQuery cfg (Qlang.ItemTypeLuxi Qlang.QRJob)
(map (Right . fromIntegral . fromJobId) names) fields False
handleCall _ op =
return . Bad $
GenericError ("Luxi call '" ++ strOfOp op ++ "' not implemented")
-- | Given a decoded luxi request, executes it and sends the luxi
-- response back to the client.
handleClientMsg :: Client -> ConfigReader -> LuxiOp -> IO Bool
handleClientMsg client creader args = do
cfg <- creader
logDebug $ "Request: " ++ show args
call_result <- handleCallWrapper cfg args
(!status, !rval) <-
case call_result of
Bad err -> do
logWarning $ "Failed to execute request: " ++ show err
return (False, showJSON err)
Ok result -> do
-- only log the first 2,000 chars of the result
logDebug $ "Result (truncated): " ++ take 2000 (J.encode result)
return (True, result)
sendMsg client $ buildResponse status rval
return True
-- | Handles one iteration of the client protocol: receives message,
-- checks for validity and decods, returns response.
handleClient :: Client -> ConfigReader -> IO Bool
handleClient client creader = do
!msg <- recvMsgExt client
case msg of
RecvConnClosed -> logDebug "Connection closed" >> return False
RecvError err -> logWarning ("Error during message receiving: " ++ err) >>
return False
RecvOk payload ->
case validateCall payload >>= decodeCall of
Bad err -> do
let errmsg = "Failed to parse request: " ++ err
logWarning errmsg
sendMsg client $ buildResponse False (showJSON errmsg)
return False
Ok args -> handleClientMsg client creader args
-- | Main client loop: runs one loop of 'handleClient', and if that
-- doesn't repot a finished (closed) connection, restarts itself.
clientLoop :: Client -> ConfigReader -> IO ()
clientLoop client creader = do
result <- handleClient client creader
if result
then clientLoop client creader
else closeClient client
-- | Main loop: accepts clients, forks an I/O thread to handle that
-- client, and then restarts.
mainLoop :: ConfigReader -> S.Socket -> IO ()
mainLoop creader socket = do
client <- acceptClient socket
_ <- forkIO $ clientLoop client creader
mainLoop creader socket
-- | Function that prepares the server socket.
prepQueryD :: Maybe FilePath -> IO (FilePath, S.Socket)
prepQueryD fpath = do
def_socket <- Path.defaultQuerySocket
let socket_path = fromMaybe def_socket fpath
cleanupSocket socket_path
s <- describeError "binding to the Luxi socket"
Nothing (Just socket_path) $ getServer socket_path
return (socket_path, s)
-- | Main function that runs the query endpoint.
runQueryD :: (FilePath, S.Socket) -> ConfigReader -> IO ()
runQueryD (socket_path, server) creader =
finally
(mainLoop creader server)
(closeServer socket_path server)
| damoxc/ganeti | src/Ganeti/Query/Server.hs | gpl-2.0 | 9,947 | 0 | 18 | 2,438 | 2,269 | 1,180 | 1,089 | 181 | 5 |
{-
Copyright (C) 2005 John Goerzen <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
module NetClient where
import MissingH.Network
import Network.Socket
import System.IO
import Types
import MissingH.Threads.Timeout
import System.IO.Error
import Control.Exception(finally, bracket)
timeo = 120 * 1000000
cto :: String -> IO a -> IO a
cto msg action =
do r <- timeout timeo action
case r of
Nothing -> fail msg
Just x -> return x
dlItem :: GAddress -> Handle -> IO ()
dlItem ga fh = (flip finally) (hClose fh) $
do s <- cto "Timeout on connect" $
connectTCP (host ga) (fromIntegral . port $ ga)
(flip finally) (cto "Timeout on close" $ sClose s)
$ do cto "Timeout on send" $ sendAll s $ (path ga) ++ "\r\n"
--cto "Timeout on shotdown" $ shutdown s ShutdownSend
if (dtype ga) == '1'
then dlTillDot s fh
else dlTo s fh
dlTillDot s fh =
do c <- sGetContents s
hPutStr fh (process c)
where process :: String -> String
process = unlines . proc' . lines
proc' :: [String] -> [String]
proc' [] = []
proc' (".":_) = []
proc' (".\r":_) = []
proc' (".\r\n":_) = []
proc' (x:xs) = x : proc' xs
sendAll :: Socket -> String -> IO ()
sendAll s [] = return ()
sendAll s buf =
do bytessent <- send s buf
sendAll s (drop bytessent buf)
recvBlocks :: Socket -> (a -> String -> IO a) -> a -> IO a
recvBlocks s action state =
do buf <- cto "Timeout on recv" (dorecv s 8192)
if buf == []
then return state
else do newstate <- action state buf
recvBlocks s action newstate
where dorecv s len =
catch (recv s len)
(\e -> if isEOFError e
then return []
else ioError e
)
-- FIXME: this is slow and a RAM hog.
sGetContents :: Socket -> IO String
sGetContents s =
recvBlocks s (\o n -> return $ o ++ n) []
dlTo :: Socket -> Handle -> IO ()
dlTo s fh =
recvBlocks s (\() buf -> hPutStr fh buf) ()
| jgoerzen/gopherbot | NetClient.hs | gpl-2.0 | 2,859 | 0 | 14 | 897 | 790 | 392 | 398 | 58 | 5 |
-- | Type and instance declarations for scheme expressions and errors.
--
-- Copyright 2008 Mats Klingberg
--
-- This file is part of hscheme and is licensed under the GNU GPL, see the
-- LICENSE file for the full license text.
module Types (
Env,
Expr(..),
SchemeError(..),
PrimitiveFunction,
ThrowsError,
IOThrowsError,
showEither,
liftThrows,
testExpr
) where
-- System imports
import Text.ParserCombinators.Parsec ( ParseError )
import Control.Monad.Error
import Data.IORef
-- | An environment type (stores variable bindings)
--
-- The entire environment is stored in an 'IORef' to facilitate adding new
-- bindings, and each value is also stored in an 'IORef' to make it mutable.
type Env = IORef [(String, IORef Expr)]
-- | Type for storing a scheme expression.
data Expr = Symbol String -- ^ Scheme symbol
| Number Integer -- ^ Number (only integers so far)
| Bool Bool -- ^ Booleans
| String String -- ^ String (e.g. \"asdf\")
| List [Expr] -- ^ \"Proper\" lists (i.e null-terminated)
| Dotted [Expr] Expr -- ^ \"Dotted\" lists or pairs
| PrimFunc String PrimitiveFunction -- ^ Primitive function
| Function [Env] [String] (Maybe String) [Expr] -- ^ Scheme function
| Undefined -- ^ An undefined value
instance Show Expr where show = showExpr
-- | Datatype for scheme functions
type PrimitiveFunction = [Expr] -> IOThrowsError Expr
-- | Show an expression
showExpr :: Expr -> String
showExpr (Symbol x) = x
showExpr (Number x) = show x
showExpr (Bool True) = "#t"
showExpr (Bool False) = "#f"
showExpr (String str) = "\"" ++ str ++ "\""
showExpr (List xs) = showListParen xs
showExpr (Dotted xs cdr) = showDotted xs cdr
showExpr (PrimFunc name _) = "#<primitive-procedure " ++ name ++ ">"
showExpr (Function _ args varargs _) =
"(lambda (" ++ unwords args ++ maybe "" (" . "++) varargs ++ ") ...)"
showExpr Undefined = "#undefined"
-- | Show a scheme list
showListParen :: [Expr] -> String
showListParen xs = "(" ++ showListNoParen xs ++ ")"
-- | Show list elements
showListNoParen :: [Expr] -> String
showListNoParen = unwords . map show
-- | Show a dotted list or a pair.
showDotted :: [Expr] -> Expr -> String
showDotted xs cdr = "(" ++ showListNoParen xs ++ " . " ++ show cdr ++ ")"
-- | Test expressions
testExpr :: [Expr]
testExpr =
[List [Number 1, Number 2],
Dotted [String "asdf", Bool True] (Bool False),
Symbol "atom",
List []]
-- | Data type for storing errors
data SchemeError = NumArgs Integer [Expr]
| TypeError String Expr
| ParseError ParseError
| BadSpecialForm String Expr
| NotFunction Expr
| UnboundVar String
| Default String
-- | Convenience type for functions that can throw a 'SchemeError'
type ThrowsError = Either SchemeError
-- | Return type for functions than can do IO and throw a 'SchemeError'
type IOThrowsError = ErrorT SchemeError IO
-- Make SchemeError an Error instance
instance Error SchemeError where
noMsg = Default "undefined error"
strMsg = Default
-- Also make SchemeError a Show instance
instance Show SchemeError where
show = showError
-- | Show an error
showError :: SchemeError -> String
showError (NumArgs expected found) = "Error: Expected " ++ show expected
++ " args; found: " ++ unwords (map show found)
showError (TypeError expected found) = "Type error: Expected " ++ expected
++ "; found: " ++ show found
showError (ParseError err) = "Parse error " ++ show err
showError (BadSpecialForm message expr) = message ++ ": " ++ show expr
showError (NotFunction expr) = "Expected function; found: " ++ show expr
showError (UnboundVar name) = "Variable not defined: " ++ name
showError (Default message) = "Error: " ++ message
-- | Show either an error or an expression
showEither :: ThrowsError Expr -> String
showEither (Left err) = show err
showEither (Right val) = show val
-- | Lift a regular 'ThrowsError' into 'IOThrowsError'
liftThrows :: ThrowsError a -> IOThrowsError a
liftThrows (Left err) = throwError err
liftThrows (Right val) = return val
| matkli/hscheme | Types.hs | gpl-3.0 | 4,268 | 0 | 9 | 1,017 | 990 | 536 | 454 | 79 | 1 |
-- | Generation of 'TC.Service' objects from the specification.
module Generation.ServiceGenerator(generateService) where
import qualified Data.Map as M
import Data.Maybe (fromJust, fromMaybe, isJust)
import qualified Data.Set as S
import qualified Generation.TemplateCompiler as TC
import qualified TypeCheck.ApiSpec as AS
-- | Transforms an api specification to a service.
generateService :: AS.ApiSpec -- ^ The specification of the web service
-> (AS.Type -> String) -- ^ A mapping from internal types to target's types
-> (AS.Type -> String) -- ^ A mapping from internal types to target's types (boxed version, for Java)
-> TC.Service
generateService apiSpec fieldMapping fieldMappingBoxedType =
TC.Service (AS.name apiSpec)
(AS.version apiSpec)
(AS.requiresAuth apiSpec)
$ map (generateSchema fieldMapping fieldMappingBoxedType apiSpec . fst) $ AS.structs apiSpec
-- | Generates the information of a resource/struct.
generateSchema :: (AS.Type -> String) -- ^ A mapping from internal types to target's types
-> (AS.Type -> String) -- ^ A mapping from internal types to target's types (boxed version, for Java)
-> AS.ApiSpec -- ^ The specification of the web service
-> AS.Id -- ^ The name of the struct
-> TC.Schema
generateSchema fieldMapping fieldMappingBoxedType apiSpec strId =
TC.Schema { TC.schemaName = strId
, TC.schemaRoute = schemaRoute'
, TC.writable = writable'
, TC.hasKeyField = hasKeyField
, TC.keyField = keyField
, TC.schemaVars = generateVars fieldMapping fieldMappingBoxedType apiSpec structInfo }
where
(schemaRoute', writable') = maybe (Nothing, False) (\(r, w) -> (Just TC.StrValue { TC.value = r }, w)) (M.lookup strId $ AS.resources apiSpec)
structInfo = fromJust $ lookup strId $ AS.structs apiSpec
maybeKeyField = AS.getPrimaryKey structInfo
-- Leave empty if it doesn't exist
keyField = fromMaybe "" maybeKeyField
hasKeyField = isJust maybeKeyField
-- | Generates the information of the fields of a 'TC.Schema'.
generateVars :: (AS.Type -> String) -- ^ A mapping from internal types to target's types
-> (AS.Type -> String) -- ^ A mapping from internal types to target's types (boxed version, for Java)
-> AS.ApiSpec -- ^ The specification of the web service
-> AS.StructInfo -- ^ The information of the struct
-> [TC.SchemaVar] -- ^ The information of all the fields of the schema
generateVars fieldMapping fieldMappingBoxedType apiSpec = map getVarFromField
where
getVarFromField :: AS.FieldInfo -> TC.SchemaVar
getVarFromField (AS.FI (n, t, modifs)) = generateSchemaVar n t modifs
-- TODO(6): implement custom fields
generateSchemaVar :: AS.Id -> AS.Type -> S.Set AS.Modifier -> TC.SchemaVar
generateSchemaVar name type' modifs =
TC.SchemaVar { TC.varName = name
, TC.varType = fieldMapping type'
, TC.varBoxedType = fieldMappingBoxedType type'
, TC.isList = isList type'
, TC.isEnum = if isEnum type' then Just $ getValues type' else Nothing
, TC.isStruct = isStruct type'
, TC.isKey = AS.PrimaryKey `S.member` modifs
, TC.isRequired = AS.Required `S.member` modifs
, TC.isHidden = AS.Hidden `S.member` modifs
, TC.isUnique = AS.Unique `S.member` modifs || AS.PrimaryKey `S.member` modifs
, TC.isUserLogin = AS.UserLogin `S.member` modifs
}
where
getValues (AS.TEnum enumId) = TC.EnumValue $ map TC.StrValue (fromJust $ M.lookup enumId $ AS.enums apiSpec)
getValues (AS.TList t') = getValues t'
getValues other = error $ "getValues called on a non-enum type: " ++ show other
isEnum (AS.TEnum _) = True
isEnum (AS.TList t') = isEnum t'
isEnum _ = False
isList (AS.TList _) = True
isList _ = False
isStruct (AS.TStruct _) = True
isStruct (AS.TList t') = isStruct t'
isStruct _ = False
| SantiMunin/harmony | src/Generation/ServiceGenerator.hs | gpl-3.0 | 4,343 | 0 | 15 | 1,256 | 977 | 535 | 442 | 64 | 9 |
{-# LANGUAGE FlexibleInstances #-}
module Mudblood.Contrib.Lisp.MB
( Value (..)
, mkBoolValue, mkIntValue, mkFloatValue, mkStringValue
, mkAttrStringValue
, typeBool, typeInt, typeFloat, typeString
, typeAttrString
, parseValue
, mbBuiltins
-- re-exports
, typeList, typeError, throwError, getSymbol, Exp (..), nil, liftL
) where
import Text.ParserCombinators.Parsec
import Mudblood.Contrib.Lisp.Core
import Mudblood.Text
import Data.Monoid
import Control.Monad
import qualified Data.Map as M
data Value = BoolValue Bool
| IntValue Int
| FloatValue Double
| StringValue String
| AttrStringValue AttrString
instance Show Value where
show (BoolValue True) = "true"
show (BoolValue False) = "false"
show (IntValue x) = show x
show (FloatValue x) = show x
show (StringValue x) = x
show (AttrStringValue v) = show v
mkBoolValue = Value . BoolValue
mkIntValue = Value . IntValue
mkFloatValue = Value . FloatValue
mkStringValue = Value . StringValue
mkAttrStringValue = Value . AttrStringValue
typeBool x = case x of
Value (BoolValue v) -> return v
_ -> typeError "bool"
typeInt x = case x of
Value (IntValue v) -> return v
_ -> typeError "int"
typeFloat x = case x of
Value (FloatValue v) -> return v
_ -> typeError "float"
typeString x = case x of
Value (StringValue v) -> return v
_ -> typeError "string"
typeAttrString x = case x of
Value (AttrStringValue v) -> return v
_ -> typeError "attrstring"
class ValueClass v where
valueEq :: v -> v -> Maybe v
valueOrd :: v -> v -> Maybe v
valuePlus :: v -> v -> Maybe v
valueMinus :: v -> v -> Maybe v
valueMult :: v -> v -> Maybe v
valueDiv :: v -> v -> Maybe v
valueNeg :: v -> Maybe v
valueEq _ _ = Nothing
valueOrd _ _ = Nothing
valuePlus _ _ = Nothing
valueMinus _ _ = Nothing
valueMult _ _ = Nothing
valueDiv _ _ = Nothing
valueNeg _ = Nothing
instance ValueClass (Exp m Value) where
valueEq (Value a) (Value b) = fmap Value $ valueEq a b
valueEq (List a) (List b) =
let zipper a b = case (valueEq a b) of
Just (Value (BoolValue True)) -> True
_ -> False
in if (length a == length b) && (and (zipWith zipper a b))
then Just (Value $ BoolValue True)
else Just (Value $ BoolValue False)
valueEq _ _ = Nothing
valueOrd (Value a) (Value b) = fmap Value $ valueOrd a b
valueOrd _ _ = Nothing
valuePlus (Value a) (Value b) = fmap Value $ valuePlus a b
valuePlus (List a) (List b) = Just $ List $ a ++ b
valuePlus _ _ = Nothing
valueMinus (Value a) (Value b) = fmap Value $ valueMinus a b
valueMinus _ _ = Nothing
valueMult (Value a) (Value b) = fmap Value $ valueMult a b
valueMult _ _ = Nothing
valueDiv (Value a) (Value b) = fmap Value $ valueDiv a b
valueDiv _ _ = Nothing
valueNeg (Value a) = fmap Value $ valueNeg a
valueNeg _ = Nothing
instance ValueClass Value where
valueEq (IntValue a) (IntValue b) = Just $ BoolValue $ a == b
valueEq (StringValue a) (StringValue b) = Just $ BoolValue $ a == b
valueEq (AttrStringValue a) (AttrStringValue b) = Just $ BoolValue $ a == b
valueEq (AttrStringValue a) (AttrStringValue b) = Just $ AttrStringValue $ a `mappend` b
valueEq (AttrStringValue a) (StringValue b) = Just $ BoolValue $ (fromAS a) == b
valueEq (StringValue a) (AttrStringValue b) = Just $ BoolValue $ a == (fromAS b)
valueEq _ _ = Nothing
valueOrd (IntValue a) (IntValue b) = Just $ BoolValue $ a >= b
valueOrd _ _ = Nothing
valuePlus (IntValue a) (IntValue b) = Just $ IntValue $ a + b
valuePlus (StringValue a) (StringValue b) = Just $ StringValue $ a ++ b
valuePlus _ _ = Nothing
valueMinus (IntValue a) (IntValue b) = Just $ IntValue $ a - b
valueMinus _ _ = Nothing
valueMult (IntValue a) (IntValue b) = Just $ IntValue $ a * b
valueMult _ _ = Nothing
valueDiv (IntValue a) (IntValue b) = Just $ IntValue $ a `div` b
valueDiv _ _ = Nothing
valueNeg (BoolValue a) = Just $ BoolValue $ not a
valueNeg _ = Nothing
mbBuiltins :: (Monad m) => Context m Value
mbBuiltins = mkContext $
[ ("if", dlispIf)
, ("=", dlispStdBinary valueEq)
, ("+", dlispStdBinary valuePlus)
, ("-", dlispStdBinary valueMinus)
, ("*", dlispStdBinary valueMult)
, ("/", dlispStdBinary valueDiv)
, ("ord", dlispStdBinary valueOrd)
, ("not", dlispStdUnary valueNeg)
, ("set-fg", dlispAttrStringColor setFg)
, ("set-bg", dlispAttrStringColor setBg)
, ("repeat", dlispRepeat)
]
dlispIf :: (Monad m) => Exp m Value
dlispIf = Function ["condition", "iftrue", "iffalse"] $ do
arg1 <- getSymbol "condition" >>= typeBool
arg2 <- getSymbol "iftrue"
arg3 <- getSymbol "iffalse"
if arg1 then eval arg2 else eval arg3
dlispStdBinary :: (Monad m) => (Exp m Value -> Exp m Value -> Maybe (Exp m Value)) -> Exp m Value
dlispStdBinary f = Function ["a", "b"] $ do
a <- getSymbol "a"
b <- getSymbol "b"
case f a b of
Nothing -> throwError "Undefined binary relation"
Just v -> return v
dlispStdUnary :: (Monad m) => (Exp m Value -> Maybe (Exp m Value)) -> Exp m Value
dlispStdUnary f = Function ["a"] $ do
a <- getSymbol "a"
case f a of
Nothing -> throwError "Undefined unary relation"
Just v -> return v
dlispAttrStringColor :: (Monad m) => (Color -> AttrString -> AttrString) -> Exp m Value
dlispAttrStringColor f = Function ["color", "string"] $ do
arg1 <- getSymbol "color" >>= typeString
arg2 <- getSymbol "string" >>= typeAttrString
case nameToColor arg1 of
Nothing -> throwError "Invalid color"
Just c -> return $ mkAttrStringValue $ f c arg2
dlispRepeat :: (Monad m) => Exp m Value
dlispRepeat = Special ["count", "arg"] $ do
count <- getSymbol "count" >>= typeInt
action <- getSymbol "arg"
forM_ [1..count] $ \_ -> eval action
return nil
parseValue = do
v <- parseStdValue
return v
parseStdValue =
(try (parseBool >>= return . BoolValue))
<|>
(try (parseInteger >>= return . IntValue))
<|>
(try (parseString >>= return . StringValue))
parseBool = try (string "true" >> return True)
<|>
try (string "false" >> return False)
parseInteger = many1 digit >>= return . read
parseString = (try $ between (char '"') (char '"') (many $ noneOf "\""))
<|>
(try $ between (char '{') (char '}') (many $ noneOf "}"))
| talanis85/mudblood | src/Mudblood/Contrib/Lisp/MB.hs | gpl-3.0 | 6,828 | 0 | 17 | 1,954 | 2,599 | 1,307 | 1,292 | 168 | 2 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UnicodeSyntax #-}
{-# OPTIONS_GHC -fno-warn-unused-local-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module Main where
import Codec.BMP (BMP, packRGBA32ToBMP24, writeBMP)
import Control.Monad (forM, forM_, when)
import Control.Monad.IO.Class (liftIO)
import Data.Array.MArray (getBounds)
import Data.Array.MArray (readArray)
import Data.Bifunctor (bimap)
import Data.Bool (bool)
import qualified Data.ByteString as B
import Data.Foldable (foldrM)
import Data.IORef (newIORef, readIORef, writeIORef)
import Data.List (foldl1', intercalate, maximumBy)
import qualified Data.Matrix as M
import Data.Maybe (isJust)
import Data.Ord (comparing)
import Data.Random.Normal ()
import Data.Random.Normal (normalsIO')
import qualified Data.Vector as V
import Data.Vector.Generic ((!))
import qualified Data.Vector.Mutable as MV
import Data.Word (Word8)
import Graphics.UI.Gtk hiding (Label, Layout, Object)
import Graphics.UI.Gtk.Gdk.GC (GCValues (..), gcGetValues, gcNewWithValues,
gcSetValues, newGCValues)
import Linear.Vector (Additive (..))
import Numeric (showFFloat)
import System.Environment (getArgs)
import System.Random (mkStdGen, setStdGen)
import System.Random.Shuffle (shuffleM)
(//) :: (Integral a, Fractional b) => a -> a -> b
n // m = fromIntegral n / fromIntegral m
type Object = V.Vector Double -- 28*28 picture, each pixel 0 to 1
type Label = Int -- 0 to 9
type Dataset = [(Object, Label)]
picSize :: Int
picSize = 28*28
readObjects :: B.ByteString -> [Object]
readObjects b = read' (B.drop headerSize b)
where
headerSize = 16
read' bs = let (p,ps) = B.splitAt picSize bs
in V.generate picSize ((//255) . B.index p) : read' ps
readLabels :: B.ByteString -> [Label]
readLabels b = read' (B.drop headerSize b)
where
headerSize = 8
read' bs = map (fromIntegral . toInteger) $ B.unpack bs
toBMP :: Object → BMP
toBMP dat = packRGBA32ToBMP24 28 28 bytestring
where
bytestring = fst $ B.unfoldrN (4*picSize) step (0,0,0)
next (i, 27, 3) = (i+1, 0, 0)
next (i, j, 3) = (i, j+1, 0)
next (i, j, ch) = (i, j, ch+1)
step :: (Int,Int,Int) → Maybe (Word8, (Int,Int,Int))
step (i,j,ch) = Just $ (toRGBA val !! ch, next (i,j,ch))
where
val = dat ! ((27-i)*28+j)
toRGBA c = [round $ 255*(1-c), round $ 255*(1-c), 0, 0]
showt :: Object → IO ()
showt dat = putStrLn lns
where
lns =
intercalate "\n" $
map (map (bool '·' '∗' . (> 0))) $
flip map [0..27] $ \i →
V.toList $ V.slice (28*i) 28 dat
newtype Pars' a = Pars' [(M.Matrix a, V.Vector a)] deriving (Show, Functor)
type Pars = Pars' Double
addPars :: Pars -> Pars -> Pars
addPars (Pars' a) (Pars' b) = Pars' $ zipWith foo a b
where foo (m1,v1) (m2,v2) = (m1 + m2, v1 ^+^ v2)
sumPars :: [Pars] -> Pars
sumPars = foldl1' addPars
sigma :: Double -> Double
sigma t = 1 / (1 + exp (-t))
sigma' :: Double -> Double
sigma' t = sigma t * (1 - sigma t)
-- multiply matrix by vector
mul :: M.Matrix Double -> V.Vector Double -> V.Vector Double
mul m v = M.getMatrixAsVector $ m * M.colVector v
-- apply the network
predicts :: Pars -> V.Vector Double -> V.Vector Double
predicts (Pars' []) x = x
predicts (Pars' ((w,b):ls)) x = predicts (Pars' ls) (V.map sigma (mul w x ^+^ b))
-- digit with maximum value of `predicts`
predict :: Pars -> V.Vector Double -> Int
predict pars obj =
fst $ maximumBy (comparing snd) $
zip [0..] $ V.toList $ predicts pars obj
grad1 :: Pars -> (Object, Label) -> IO Pars
grad1 (Pars' ps) (x,y) =
let zs = unf (\(w,b) z -> mul w z ^+^ b) ps x
as = map (V.map sigma) zs
grads = snd $ unf'
(\(z,(a,(w,_))) r ->
let delta = V.zipWith (*) r (V.map sigma' z)
in (mul (M.transpose w) delta
, ( M.rowVector a * M.colVector delta
, delta
)
)
)
(zs `zip` (init as `zip` ps))
(labelToVector y ^-^ last as)
in do
print zs
pure $ Pars' grads
where
unf :: (b -> a -> a) -> ([b] -> a -> [a])
unf _ [] _ = []
unf f (b:bs) a = let a' = f b a in a' : unf f bs a'
unf' :: (b -> t -> (t, a)) -> ([b] -> t -> (t, [a]))
unf' _ [] t = (t, [])
unf' f (b:bs) t =
let (t', as) = unf' f bs t
(t'', a) = f b t'
in (t'', a:as)
trainBatch :: Dataset -> Pars -> IO Pars
trainBatch batch pars = addPars pars <$> fmap ((-eta)*) <$> grad
where
eta = 0.1
grad =
fmap (/ fromIntegral (length batch)) <$>
sumPars <$> mapM (grad1 pars) batch
train1 :: (Object,Label) -> Pars -> IO Pars
train1 d pars = trainBatch [d] pars
randn :: Double -> Int -> IO (V.Vector Double)
randn s n = V.fromListN n <$> normalsIO' (0,s)
initialPars :: [Int] -> IO Pars
initialPars sizes =
fmap Pars' $
forM (sizes `zip` tail sizes) $ \(lprev, l) -> do
matvec <- randn (1//(2*lprev)) (l*lprev)
b <- randn (1//(2*l)) l
pure (M.matrix l lprev (\(i,j) -> matvec ! (i*l+j)), b)
labelToVector :: Label -> V.Vector Double
labelToVector i = V.generate 10 (\j -> bool 0 1 (i == j))
train :: Dataset -> Dataset -> IO Pars
train trainset testset = train' epochs trainset =<< initialPars sizes
where
--epochs = 50
epochs = 3
--sizes = [28*28, 40, 40, 10]
sizes = [28*28, 10]
batchSize = 1
train' :: Int -> Dataset -> Pars -> IO Pars
train' 0 _ pars = pure pars
train' k [] pars = do
shd <- shuffleM trainset
train' (k-1) shd pars
train' k dat pars = do
let (batch,rest) = splitAt batchSize dat
pars' <- trainBatch batch pars
--pars'' <- train' k rest pars'
pars'' <- train' (k-1) rest pars'
print $ accuracy pars'' testset
pure pars''
accuracy :: Pars -> Dataset -> Int
accuracy pars testset =
sum $ flip map testset $ \(x,y) -> bool 0 1 (predict pars x == y)
exec :: IO ()
exec = do
setStdGen (mkStdGen 11111)
[datadir] <- getArgs
trainData <- readObjects <$> B.readFile (datadir ++ "/train-images-idx3-ubyte")
trainLabels <- readLabels <$> B.readFile (datadir ++ "/train-labels-idx1-ubyte")
testData <- readObjects <$> B.readFile (datadir ++ "/t10k-images-idx3-ubyte")
testLabels <- readLabels <$> B.readFile (datadir ++ "/t10k-labels-idx1-ubyte")
let trainSet = zip trainData trainLabels
let testSet = zip testData testLabels
-- _ <- train trainSet testSet
writeBMP "some.bmp" $ toBMP $ testData !! 6
showt $ testData !! 6
-- pixBufToVector :: Pixbuf -> IO (mutable vector)
-- | Takes a pixbuf, returns vector of size 28x28
pixBufToVector pixBuf = do
(pbData :: PixbufData Int Word8) <- pixbufGetPixels pixBuf
(_,total) <- getBounds pbData
pbHeight <- pixbufGetHeight pixBuf
pbWidth <- pixbufGetWidth pixBuf
print (pbHeight, pbWidth)
print total
npix <- pixbufGetNChannels pixBuf
print npix
stride <- pixbufGetRowstride pixBuf
print stride
v <- MV.new $ 28*28
MV.set v (0 :: Double)
let elemsPerCell = stride `div` 28
elemsPerRow = pbHeight `div` 28
rowsN = min (stride `div` 3) pbHeight
print elemsPerRow
print rowsN
forM_ [0..rowsN-1] $ \rowI -> do
forM_ [0..27] $ \cellI -> do
let rStart = rowI * stride + elemsPerCell * cellI
foldFoo index aggr = do
r <- readArray pbData index
g <- readArray pbData $ index+1
b <- readArray pbData $ index+2
pure $ aggr + 255 * 3 - fromIntegral r - fromIntegral g - fromIntegral b
(res :: Int) <-
foldrM foldFoo (0 :: Int) [rStart,rStart+3..rStart+elemsPerCell-1]
MV.modify v ((+) (fromInteger $ fromIntegral res))
(min 783 (28 * (rowI `div` elemsPerRow) + cellI))
maxValue <- foldrM (\i curMax -> max curMax <$> MV.read v i) 0 [0..28*28-1]
forM_ [0..27] $ \i -> do
forM_ [0..27] $ \j -> do
MV.modify v (\x -> x / maxValue) $ i * 28 + j
pure v
-- For the vector return some output to show user
processVector :: V.Vector Double -> IO String
processVector v = do
forM_ [0..27] $ \i -> do
forM_ [0..27] $ \j -> do
let value = v V.! (i * 28 + j)
putStr $ showFFloat (Just 2) value "" ++ " "
putStrLn ""
pure $ "KEK, vector of length: " ++ show (V.length v)
main :: IO ()
main = do
initGUI
window <- windowNew
set window [ windowResizable := False
, windowDefaultHeight := 200
, windowDefaultWidth := 300
-- , windowAllowGrow := False
-- , windowAllowShrink := False
]
onDestroy window mainQuit
gcVar <- newIORef undefined -- lol
canDraw <- newIORef False
initialized <- newIORef False
drawArea <- drawingAreaNew
predictButton <- buttonNewWithLabel ("Make prediction" :: String)
outputLabel <- labelNew $ Just ("TODO Put something" :: String)
learnNumberEntry <- entryNew
learnButton <- buttonNewWithLabel ("Make prediction" :: String)
widgetSetSizeRequest drawArea 280 280
hbox <- hBoxNew False 5
vbox <- vBoxNew False 5
hboxLearn <- hBoxNew False 5
boxPackStart hboxLearn learnNumberEntry PackNatural 10
boxPackStart hboxLearn learnButton PackNatural 10
boxPackStart vbox hboxLearn PackNatural 10
boxPackStart vbox predictButton PackNatural 10
boxPackStart vbox outputLabel PackGrow 10
boxPackStart hbox drawArea PackGrow 10
boxPackStart hbox vbox PackNatural 10
let initialize :: IO ()
initialize = do
drawWindow <- widgetGetDrawWindow drawArea
gc <- readIORef gcVar
gcv <- gcGetValues gc
w <- drawWindowGetWidth drawWindow
h <- drawWindowGetHeight drawWindow
gcSetValues gc $ gcv { foreground = Color 0xffff 0xffff 0xffff }
drawRectangle drawWindow gc True 0 0 w h
gcSetValues gc $ gcv { foreground = Color 0 0 0 }
learnButton `on` buttonPressEvent $ do
drawWindow <- liftIO $ widgetGetDrawWindow drawArea
(number :: Int) <- read <$> liftIO (entryGetText learnNumberEntry)
when (number < 0 || number > 9) $ error "number should be in 0..9"
(sizeX, sizeY) <- liftIO $ widgetGetSize drawArea
pixBufM <- liftIO $
pixbufGetFromDrawable drawWindow (Rectangle 0 0 sizeX sizeY)
(flip (maybe (pure ())) pixBufM) $ \pixBuf -> liftIO $ do
vec <- pixBufToVector pixBuf
vecFrozen <- V.freeze vec
processVector vecFrozen
labelSetText outputLabel ("Successfully learned" :: String)
liftIO $ entrySetText learnNumberEntry ("" :: String)
liftIO initialize
liftIO $ writeIORef initialized False
return False
window `on` configureEvent $ do
(w, h) <- eventSize
liftIO initialize
liftIO $ writeIORef initialized False
liftIO . putStrLn $ "Resizing: " ++ show w ++ " " ++ show h
return False
predictButton `on` buttonPressEvent $ do
drawWindow <- liftIO $ widgetGetDrawWindow drawArea
(sizeX, sizeY) <- liftIO $ widgetGetSize drawArea
pixBufM <- liftIO $
pixbufGetFromDrawable drawWindow (Rectangle 0 0 sizeX sizeY)
liftIO $ putStrLn $
"Successfully retrieved pixBuf: " ++ show (isJust pixBufM)
(flip (maybe (pure ())) pixBufM) $ \pixBuf -> liftIO $ do
vec <- pixBufToVector pixBuf
vecFrozen <- V.freeze vec
resText <- processVector vecFrozen
labelSetText outputLabel resText
liftIO initialize
liftIO $ writeIORef initialized False
return False
widgetAddEvents drawArea [ ExposureMask
, LeaveNotifyMask
, ButtonPressMask
, PointerMotionMask
-- , PointerMotionHintMask
]
drawArea `on` realize $ do
drawWindow <- widgetGetDrawWindow drawArea
gc <- gcNewWithValues drawWindow $
newGCValues { background = Color 0xffff 0xffff 0xffff
, foreground = Color 0 0 0 }
writeIORef gcVar gc
drawArea `on` buttonPressEvent $ do
inited <- liftIO $ readIORef initialized
when (not inited) $ liftIO $ do
initialize
writeIORef initialized True
liftIO $ writeIORef canDraw True
return False
drawArea `on` buttonReleaseEvent $ do
liftIO $ writeIORef canDraw False
return False
drawArea `on` motionNotifyEvent $ do
gc <- liftIO $ readIORef gcVar
drawWindow <- liftIO $ widgetGetDrawWindow drawArea
let ps = 10
ps' = ps `div` 2
(x,y) <- bimap round round <$> eventCoordinates
toDraw <- liftIO $ readIORef canDraw
when (toDraw) $
liftIO $ drawRectangle drawWindow gc True (x-ps') (y-ps') ps ps
pure False
set window
[ containerChild := hbox
, containerBorderWidth := 10
, windowTitle := ("fdm" :: String)
]
widgetShowAll window
mainGUI
| zhenyavinogradov/ml-labs | src/Lab7/Main.hs | gpl-3.0 | 13,902 | 0 | 25 | 4,371 | 4,979 | 2,529 | 2,450 | -1 | -1 |
-- Converts .lhs (literary Haskell files) to .hs (plain Haskell files)
-- Keeps only the statements which are normally compiled, plus blank lines.
-- To use:
-- ghc --make lhs2hs.hs
-- to get an executable file lhs2hs.
-- Then
-- lhs2hs filename
-- will open filename.lhs and save the converted file in filename.hs
-- by Scot Drysdale on 7/28/07, based on SOE program on p. 241
module Main where
import System.IO
import System.IO.Error
import System.Environment -- to allow getArgs
-- Opens a file, given name and mode
openGivenFile :: String -> IOMode -> IO Handle
openGivenFile name mode
= catch (do handle <- openFile name mode
return handle)
(\e -> error ("Cannot open " ++ name))
main = do args <- getArgs
fromHandle <- openGivenFile (args !! 0 ++ ".lhs") ReadMode
toHandle <- openGivenFile (args !! 0 ++ ".hs") WriteMode
convertFile fromHandle toHandle
hClose fromHandle
hClose toHandle
-- Converts all the lines in a file
convertFile :: Handle -> Handle -> IO ()
convertFile fromHandle toHandle
= catch (do line <- hGetLine fromHandle
case line of
('>' : ' ' : rest) -> hPutStrLn toHandle rest
('>' : rest) -> hPutStrLn toHandle rest
('\n' : rest) -> hPutStrLn toHandle line
('\r' : rest) -> hPutStrLn toHandle line
_ -> return ()
convertFile fromHandle toHandle)
(\error -> if isEOFError error then return ()
else ioError error)
| passionfruit18/ldl_exposition | util/lhs2hs.hs | gpl-3.0 | 1,655 | 0 | 14 | 543 | 355 | 179 | 176 | 27 | 6 |
{-# 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.CloudResourceManager.Organizations.Search
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Searches Organization resources that are visible to the user and satisfy
-- the specified filter. This method returns Organizations in an
-- unspecified order. New Organizations do not necessarily appear at the
-- end of the results.
--
-- /See:/ <https://cloud.google.com/resource-manager Google Cloud Resource Manager API Reference> for @cloudresourcemanager.organizations.search@.
module Network.Google.Resource.CloudResourceManager.Organizations.Search
(
-- * REST Resource
OrganizationsSearchResource
-- * Creating a Request
, organizationsSearch
, OrganizationsSearch
-- * Request Lenses
, osXgafv
, osUploadProtocol
, osPp
, osAccessToken
, osUploadType
, osPayload
, osBearerToken
, osCallback
) where
import Network.Google.Prelude
import Network.Google.ResourceManager.Types
-- | A resource alias for @cloudresourcemanager.organizations.search@ method which the
-- 'OrganizationsSearch' request conforms to.
type OrganizationsSearchResource =
"v1" :>
"organizations:search" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] SearchOrganizationsRequest :>
Post '[JSON] SearchOrganizationsResponse
-- | Searches Organization resources that are visible to the user and satisfy
-- the specified filter. This method returns Organizations in an
-- unspecified order. New Organizations do not necessarily appear at the
-- end of the results.
--
-- /See:/ 'organizationsSearch' smart constructor.
data OrganizationsSearch = OrganizationsSearch'
{ _osXgafv :: !(Maybe Xgafv)
, _osUploadProtocol :: !(Maybe Text)
, _osPp :: !Bool
, _osAccessToken :: !(Maybe Text)
, _osUploadType :: !(Maybe Text)
, _osPayload :: !SearchOrganizationsRequest
, _osBearerToken :: !(Maybe Text)
, _osCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'OrganizationsSearch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'osXgafv'
--
-- * 'osUploadProtocol'
--
-- * 'osPp'
--
-- * 'osAccessToken'
--
-- * 'osUploadType'
--
-- * 'osPayload'
--
-- * 'osBearerToken'
--
-- * 'osCallback'
organizationsSearch
:: SearchOrganizationsRequest -- ^ 'osPayload'
-> OrganizationsSearch
organizationsSearch pOsPayload_ =
OrganizationsSearch'
{ _osXgafv = Nothing
, _osUploadProtocol = Nothing
, _osPp = True
, _osAccessToken = Nothing
, _osUploadType = Nothing
, _osPayload = pOsPayload_
, _osBearerToken = Nothing
, _osCallback = Nothing
}
-- | V1 error format.
osXgafv :: Lens' OrganizationsSearch (Maybe Xgafv)
osXgafv = lens _osXgafv (\ s a -> s{_osXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
osUploadProtocol :: Lens' OrganizationsSearch (Maybe Text)
osUploadProtocol
= lens _osUploadProtocol
(\ s a -> s{_osUploadProtocol = a})
-- | Pretty-print response.
osPp :: Lens' OrganizationsSearch Bool
osPp = lens _osPp (\ s a -> s{_osPp = a})
-- | OAuth access token.
osAccessToken :: Lens' OrganizationsSearch (Maybe Text)
osAccessToken
= lens _osAccessToken
(\ s a -> s{_osAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
osUploadType :: Lens' OrganizationsSearch (Maybe Text)
osUploadType
= lens _osUploadType (\ s a -> s{_osUploadType = a})
-- | Multipart request metadata.
osPayload :: Lens' OrganizationsSearch SearchOrganizationsRequest
osPayload
= lens _osPayload (\ s a -> s{_osPayload = a})
-- | OAuth bearer token.
osBearerToken :: Lens' OrganizationsSearch (Maybe Text)
osBearerToken
= lens _osBearerToken
(\ s a -> s{_osBearerToken = a})
-- | JSONP
osCallback :: Lens' OrganizationsSearch (Maybe Text)
osCallback
= lens _osCallback (\ s a -> s{_osCallback = a})
instance GoogleRequest OrganizationsSearch where
type Rs OrganizationsSearch =
SearchOrganizationsResponse
type Scopes OrganizationsSearch =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only"]
requestClient OrganizationsSearch'{..}
= go _osXgafv _osUploadProtocol (Just _osPp)
_osAccessToken
_osUploadType
_osBearerToken
_osCallback
(Just AltJSON)
_osPayload
resourceManagerService
where go
= buildClient
(Proxy :: Proxy OrganizationsSearchResource)
mempty
| rueshyna/gogol | gogol-resourcemanager/gen/Network/Google/Resource/CloudResourceManager/Organizations/Search.hs | mpl-2.0 | 5,859 | 0 | 18 | 1,408 | 866 | 505 | 361 | 123 | 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.GamesManagement.Events.ResetAll
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Resets all player progress on all events for the currently authenticated
-- player. This method is only accessible to whitelisted tester accounts
-- for your application. All quests for this player will also be reset.
--
-- /See:/ <https://developers.google.com/games/services Google Play Game Services Management API Reference> for @gamesManagement.events.resetAll@.
module Network.Google.Resource.GamesManagement.Events.ResetAll
(
-- * REST Resource
EventsResetAllResource
-- * Creating a Request
, eventsResetAll
, EventsResetAll
) where
import Network.Google.GamesManagement.Types
import Network.Google.Prelude
-- | A resource alias for @gamesManagement.events.resetAll@ method which the
-- 'EventsResetAll' request conforms to.
type EventsResetAllResource =
"games" :>
"v1management" :>
"events" :>
"reset" :>
QueryParam "alt" AltJSON :> Post '[JSON] ()
-- | Resets all player progress on all events for the currently authenticated
-- player. This method is only accessible to whitelisted tester accounts
-- for your application. All quests for this player will also be reset.
--
-- /See:/ 'eventsResetAll' smart constructor.
data EventsResetAll =
EventsResetAll'
deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'EventsResetAll' with the minimum fields required to make a request.
--
eventsResetAll
:: EventsResetAll
eventsResetAll = EventsResetAll'
instance GoogleRequest EventsResetAll where
type Rs EventsResetAll = ()
type Scopes EventsResetAll =
'["https://www.googleapis.com/auth/games",
"https://www.googleapis.com/auth/plus.login"]
requestClient EventsResetAll'{}
= go (Just AltJSON) gamesManagementService
where go
= buildClient (Proxy :: Proxy EventsResetAllResource)
mempty
| rueshyna/gogol | gogol-games-management/gen/Network/Google/Resource/GamesManagement/Events/ResetAll.hs | mpl-2.0 | 2,713 | 0 | 12 | 575 | 233 | 146 | 87 | 41 | 1 |
{-# LANGUAGE OverloadedStrings, TypeFamilies #-}
module Model.Transcode.Types
( Transcode(..)
, TranscodePID
, TranscodeArgs
, transcodeAsset
, transcodeOrig
, transcodeId
-- TODO: don't re-export from Transcode
, makeTranscodeRow
, makeTranscode
, makeOrigTranscode
) where
import qualified Data.ByteString as BS
import Data.Maybe (fromMaybe)
import Model.Kind
import Model.Id.Types
import Model.Time
import Model.Segment
import Model.Asset.Types
import Model.AssetRevision.Types
import Model.Party.Types
import Model.Permission.Types
import Model.Volume.Types
type TranscodePID = Int32
type TranscodeArgs = [String]
type instance IdType Transcode = Int32
data Transcode = Transcode
{ transcodeRevision :: !AssetRevision
, transcodeOwner :: SiteAuth
, transcodeSegment :: Segment
, transcodeOptions :: TranscodeArgs
, transcodeStart :: Maybe Timestamp
, transcodeProcess :: Maybe TranscodePID
, transcodeLog :: Maybe BS.ByteString
}
transcodeAsset :: Transcode -> Asset
transcodeAsset = revisionAsset . transcodeRevision
transcodeOrig :: Transcode -> Asset
transcodeOrig = revisionOrig . transcodeRevision
transcodeId :: Transcode -> Id Transcode
transcodeId = Id . unId . assetId . assetRow . transcodeAsset
instance Kinded Transcode where
kindOf _ = "transcode"
makeTranscodeRow :: Segment -> [Maybe String] -> Maybe Timestamp -> Maybe Int32 -> Maybe BS.ByteString -> SiteAuth -> AssetRevision -> Transcode
makeTranscodeRow s f t p l u a =
Transcode a u s (map (fromMaybe (error "NULL transcode options")) f) t p l
makeOrigTranscode :: (AssetRevision -> Transcode) -> AssetRow -> Asset -> Transcode
makeOrigTranscode f a o = f $ AssetRevision (Asset a $ assetVolume o) o
makeTranscode :: (Asset -> Transcode) -> AssetRow -> (VolumeRolePolicy -> Volume) -> Transcode
makeTranscode t o vp = t $ Asset o $ vp RoleAdmin
| databrary/databrary | src/Model/Transcode/Types.hs | agpl-3.0 | 1,873 | 0 | 11 | 302 | 504 | 281 | 223 | 50 | 1 |
import Test.Hspec
-- We'll try just strait forward implementation.
-- Bruteforcing based on the conditions
-- There is probably math solution to this or simplification
-- a + b + c = 1000
-- a^2 + b^2 = c^2
-- a < b < c
condition_check :: Int -> (Int, Int, Int) -> Bool
condition_check sum (a, b, c)
-- a<b<c check not required since we filter on the input
-- | a > b = False
-- | b > c = False
-- | a + b + c /= sum = False
| a^2 + b^2 /= c^2 = False
| otherwise = True
pythagorian_triplet_search :: Int -> (Int, Int, Int)
pythagorian_triplet_search sum = head (filter (condition_check sum) [(a, b, c) | a <- [1..(sum-3)], b <- [a..(sum-3)], c <- [(sum - a - b)]])
pythagorian_triplet :: Int -> Int
pythagorian_triplet sum = a * b * c
where (a, b, c) = pythagorian_triplet_search sum
res = pythagorian_triplet 1000
-- Tests + result print
main = hspec $ do
describe "Dummy" $ do
it "dummy test" $ do
True `shouldBe` True
describe "Euler test" $ do
it "sum = 5" $ do
pythagorian_triplet (3+4+5) `shouldBe` (3*4*5)
describe "Euler actual problem" $ do
it "result (a + b + c = 1000)" $ do
putStrLn ("res = " ++ show res)
| orbitgray/ProjectEuler | haskell/009.hs | lgpl-3.0 | 1,247 | 0 | 18 | 351 | 391 | 206 | 185 | 21 | 1 |
{-# LANGUAGE Haskell2010 #-}
module ReaderT where
newtype ReaderT r m a = ReaderT { runReaderT :: r -> m a }
| haskell/haddock | hoogle-test/src/type-sigs/ReaderT.hs | bsd-2-clause | 110 | 0 | 8 | 23 | 28 | 19 | 9 | 3 | 0 |
-- Copyright (c) 2015 Gabriel Gonzalez
data RNA = A | U | C | G
deriving (Read)
data AminoAcid
= Ala | Cys | Asp | Glu | Phe | Gly | His | Ile | Lys | Leu
| Met | Asn | Pro | Gln | Arg | Ser | Thr | Val | Trp | Tyr
| Stop
deriving (Show)
-- | Table of RNA triple mappings to amino acids.
decode :: RNA -> RNA -> RNA -> AminoAcid
decode U U U = Phe
decode U U C = Phe
decode U U A = Leu
decode U U G = Leu
decode U C _ = Ser
decode U A U = Tyr
decode U A C = Tyr
decode U A A = Stop
decode U A G = Stop
decode U G U = Cys
decode U G C = Cys
decode U G A = Stop
decode U G G = Trp
decode C U _ = Leu
decode C C _ = Pro
decode C A U = His
decode C A C = His
decode C A A = Gln
decode C A G = Gln
decode C G _ = Arg
decode A U U = Ile
decode A U C = Ile
decode A U A = Ile
decode A U G = Met
decode A C _ = Thr
decode A A U = Asn
decode A A C = Asn
decode A A A = Lys
decode A A G = Lys
decode A G U = Ser
decode A G C = Ser
decode A G A = Arg
decode A G G = Arg
decode G U _ = Val
decode G C _ = Ala
decode G A U = Asp
decode G A C = Asp
decode G A A = Glu
decode G A G = Glu
decode G G _ = Gly
-- | Decode each RNA triple to an amino acid.
decodeAll :: [RNA] -> [AminoAcid]
decodeAll [] = []
decodeAll (a:b:c:ds) = decode a b c : decodeAll ds
decodeAll _ = error "incomplete sequence"
-- | Run the decoder.
main :: IO ()
main = do
interact (concatMap show . decodeAll . map (read . (: [])))
putStrLn ""
| BartMassey/haskell-basic-examples | rna.hs | bsd-2-clause | 1,431 | 0 | 14 | 413 | 731 | 381 | 350 | 56 | 1 |
{-# OPTIONS -XNoMonomorphismRestriction #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Binary.Generic.Extensions
-- Copyright : Lars Petersen
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Lars Petersen <[email protected]>
-- Stability : experimental
--
-- You can build your own type-specific stacks. For example the default stack
-- looks like this, whereas the ordering determines, which function matches
-- first for a specific type. This especially allows you to override the
-- default choices:
--
-- > getExtDefault :: Typeable a => Get a -> Get a
-- > getExtDefault = getExtInteger
-- > . getExtChar
-- > . getExtWord
-- > . getExtInt
-- > . getExtFloat
-- > . getExtText
-- > . getExtByteString
-- >
-- > putExtDefault :: Typeable a => (a -> Put) -> a -> Put
-- > putExtDefault = putExtInteger
-- > . putExtChar
-- > . putExtWord
-- > . putExtInt
-- > . putExtFloat
-- > . putExtText
-- > . putExtByteString
--
-- Notice that these stacks have to be grounded, ideally with something
-- that handles algebraic types.
-- Have a look at @Data.Binary.Generic@ how this is done for the default
-- stack.
--
-- IMPORTANT: You cannot simply apply an extension to 'getGeneric' or
-- 'putGeneric', since these do a recursive call at the bottom level
-- which points to the top of the stack.
--
--
-----------------------------------------------------------------------------
module Data.Binary.Generic.Extensions (
extGet
, extPut
, getExtDefault
, putExtDefault
, getExtInteger
, putExtInteger
, getExtChar
, putExtChar
, getExtWord
, putExtWord
, getExtInt
, putExtInt
, getExtFloat
, putExtFloat
, getExtText
, putExtText
, getExtByteString
, putExtByteString
) where
import Data.Binary
import Data.Binary.IEEE754 (putFloat32be, getFloat32be, putFloat64be, getFloat64be)
import Data.Data
import Data.Generics
import Data.Word ()
import Data.Int
import Data.List
import Data.Bits
import Data.ByteString.Lazy (ByteString)
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Text.Lazy as LT
import qualified Data.Text.Lazy.Encoding as LTE
import Control.Monad
extGet :: (Monad m, Typeable a, Typeable b) => m b -> m a -> m a
extGet = flip extR
extPut :: (Typeable a, Typeable b) => (b -> q) -> (a -> q) -> a -> q
extPut = flip extQ
getExtDefault :: Typeable a => Get a -> Get a
getExtDefault = getExtInteger
. getExtChar
. getExtWord
. getExtInt
. getExtFloat
. getExtText
. getExtByteString
putExtDefault :: Typeable a => (a -> Put) -> a -> Put
putExtDefault = putExtInteger
. putExtChar
. putExtWord
. putExtInt
. putExtFloat
. putExtText
. putExtByteString
getExtInteger :: Typeable a => Get a -> Get a
getExtInteger = extGet (getInteger :: Get Integer)
putExtInteger :: Typeable a => (a -> Put) -> a -> Put
putExtInteger = extPut (putInteger :: Integer -> Put)
getExtChar :: Typeable a => Get a -> Get a
getExtChar = extGet (get :: Get Char)
putExtChar :: Typeable a => (a -> Put) -> a -> Put
putExtChar = extPut (put :: Char -> Put)
getExtWord :: Typeable a => Get a -> Get a
getExtWord = extGet (get :: Get Word )
. extGet (get :: Get Word8 )
. extGet (get :: Get Word16)
. extGet (get :: Get Word32)
. extGet (get :: Get Word64)
putExtWord :: Typeable a => (a -> Put) -> a -> Put
putExtWord = extPut (put :: Word -> Put)
. extPut (put :: Word8 -> Put)
. extPut (put :: Word16 -> Put)
. extPut (put :: Word32 -> Put)
. extPut (put :: Word64 -> Put)
getExtInt :: Typeable a => Get a -> Get a
getExtInt = extGet (get :: Get Int )
. extGet (get :: Get Int8 )
. extGet (get :: Get Int16)
. extGet (get :: Get Int32)
. extGet (get :: Get Int64)
putExtInt :: Typeable a => (a -> Put) -> a -> Put
putExtInt = extPut (put :: Int -> Put)
. extPut (put :: Int8 -> Put)
. extPut (put :: Int16 -> Put)
. extPut (put :: Int32 -> Put)
. extPut (put :: Int64 -> Put)
getExtFloat :: Typeable a => Get a -> Get a
getExtFloat = extGet (getFloat32be :: Get Float)
. extGet (getFloat64be :: Get Double)
putExtFloat :: Typeable a => (a -> Put) -> a -> Put
putExtFloat = extPut (putFloat32be :: Float -> Put)
. extPut (putFloat64be :: Double -> Put)
getExtText :: Typeable a => Get a -> Get a
getExtText = extGet (getText :: Get T.Text)
. extGet (getTextL :: Get LT.Text)
putExtText :: Typeable a => (a -> Put) -> a -> Put
putExtText = extPut (putText :: T.Text -> Put)
. extPut (putTextL :: LT.Text -> Put)
getExtByteString :: Typeable a => Get a -> Get a
getExtByteString = extGet (get :: Get ByteString)
putExtByteString :: Typeable a => (a -> Put) -> a -> Put
putExtByteString = extPut (put :: ByteString -> Put)
-------------------------------------------------------------------
-- serialisation for Data.Text
-------------------------------------------------------------------
getText :: Get T.Text
getText = get >>= (return . TE.decodeUtf8)
getTextL :: Get LT.Text
getTextL = get >>= (return . LTE.decodeUtf8)
putText :: T.Text -> Put
putText = put . TE.encodeUtf8
putTextL :: LT.Text -> Put
putTextL = put . LTE.encodeUtf8
-------------------------------------------------------------------
-- integer serialisation with consistent big-endian byteorder
-------------------------------------------------------------------
{-# INLINE putInteger #-}
putInteger :: Integer -> Put
putInteger n | n >= lo && n <= hi = do
putWord8 0
put (fromIntegral n :: Int32) -- fast path
where
lo = fromIntegral (minBound :: Int32) :: Integer
hi = fromIntegral (maxBound :: Int32) :: Integer
putInteger n = do
putWord8 1
put sign
put $ reverse (unroll (abs n)) -- unroll the bytes
where
sign = fromIntegral (signum n) :: Word8
{-# INLINE getInteger #-}
getInteger :: Get Integer
getInteger = do
tag <- get :: Get Word8
case tag of
0 -> liftM fromIntegral (get :: Get Int32)
_ -> do sign <- get
bytes <- get
let v = roll (reverse bytes)
return $! if sign == (1 :: Word8) then v else - v
--
-- Fold and unfold an Integer to and from a list of its bytes
--
unroll :: Integer -> [Word8]
unroll = unfoldr step
where
step 0 = Nothing
step i = Just (fromIntegral i, i `shiftR` 8)
roll :: [Word8] -> Integer
roll = foldr unstep 0
where
unstep b a = a `shiftL` 8 .|. fromIntegral b
| lpeterse/binary-generic | src/Data/Binary/Generic/Extensions.hs | bsd-3-clause | 8,270 | 0 | 17 | 3,158 | 1,843 | 999 | 844 | 139 | 3 |
module Main (main) where
-- stdlib
import Control.Exception
import Control.Monad
import Control.Monad.Trans
import Data.List
import Network.Browser
import System.Directory
import System.Environment
import System.Exit (exitWith, ExitCode(..))
import System.FilePath
import System.IO
import System.IO.Error
import System.Process (callCommand)
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Compression.GZip as GZ
import qualified Data.ByteString.Lazy as BS
import qualified Data.Set as Set
-- Cabal
import Distribution.Package
import Distribution.Simple.Utils hiding (warn)
import Distribution.Text
import Distribution.Verbosity
import Distribution.Version
-- hackage
import Distribution.Client (PkgIndexInfo(..))
import Distribution.Client.Cron (cron, rethrowSignalsAsExceptions, Signal(..))
import Distribution.Client.Mirror.CmdLine
import Distribution.Client.Mirror.Config
import Distribution.Client.Mirror.Repo
import Distribution.Client.Mirror.Session
import Distribution.Client.Mirror.State
import Distribution.Server.Util.Merge
import Paths_hackage_server (version)
import qualified Distribution.Server.Util.GZip as GZip
-- hackage-security
import qualified Hackage.Security.Client.Repository.HttpLib as Sec
{-------------------------------------------------------------------------------
Application entry point
-------------------------------------------------------------------------------}
main :: IO ()
main = toplevelHandler $ do
rethrowSignalsAsExceptions [SIGABRT, SIGINT, SIGQUIT, SIGTERM]
hSetBuffering stdout LineBuffering
args <- getArgs
(verbosity, opts) <- validateOpts args
(env, st) <- mirrorInit verbosity opts
case continuous opts of
Nothing -> mirrorOneShot verbosity opts env st
Just interval -> cron verbosity interval
(mirrorIteration verbosity opts env) st
toplevelHandler :: IO a -> IO a
toplevelHandler =
handle $ \ioe -> do
hFlush stdout
pname <- getProgName
hPutStrLn stderr (pname ++ ": " ++ formatIOError ioe)
exitWith (ExitFailure 1)
{-------------------------------------------------------------------------------
One-shot versus continuous mirroring
-------------------------------------------------------------------------------}
mirrorOneShot :: Verbosity -> MirrorOpts -> MirrorEnv -> MirrorState -> IO ()
mirrorOneShot verbosity opts env st = do
(merr, _) <- mirrorOnce verbosity opts env st
case merr of
Nothing -> return ()
Just theError -> fail (formatMirrorError theError)
mirrorIteration :: Verbosity -> MirrorOpts -> MirrorEnv
-> MirrorState -> IO MirrorState
mirrorIteration verbosity opts env st = do
(merr, st') <- mirrorOnce verbosity opts { mo_keepGoing = True } env st
when (st' /= st) $
savePackagesState env st'
case merr of
Nothing -> return ()
Just Interrupted -> throw UserInterrupt
Just theError -> do
warn verbosity (formatMirrorError theError)
notice verbosity "Abandoning this mirroring attempt."
return st'
{-------------------------------------------------------------------------------
Main mirroring logic
-------------------------------------------------------------------------------}
mirrorOnce :: Verbosity -> MirrorOpts -> MirrorEnv
-> MirrorState -> IO (Maybe MirrorError, MirrorState)
mirrorOnce verbosity opts
(MirrorEnv srcCacheDir dstCacheDir missingPkgsFile unmirrorablePkgsFile)
st@(MirrorState missingPkgs unmirrorablePkgs) =
mirrorSession (mo_keepGoing opts) $ do
httpLib <- mirrorAskHttpLib
liftCont (initRepos httpLib) $ \(sourceRepo, targetRepo) -> do
srcIndex <- downloadSourceIndex sourceRepo
dstIndex <- readCachedTargetIndex verbosity targetRepo
let pkgsMissingFromDest = diffIndex srcIndex dstIndex
pkgsToMirror
| null (selectedPkgs opts) = pkgsMissingFromDest
| otherwise = subsetIndex (selectedPkgs opts)
pkgsMissingFromDest
pkgsToMirror' = filter (\(PkgIndexInfo pkg _ _ _) ->
pkg `Set.notMember` missingPkgs
&& pkg `Set.notMember` unmirrorablePkgs )
pkgsToMirror
mirrorCount = length pkgsToMirror'
ignoreCount = length pkgsToMirror - mirrorCount
if mirrorCount == 0
then liftIO $ notice verbosity $ "No packages to mirror"
else do
liftIO $ notice verbosity $
show mirrorCount ++ " packages to mirror."
++ if ignoreCount == 0 then ""
else " Ignoring " ++ show ignoreCount
++ " package(s) that cannot be mirrored\n(for details see "
++ missingPkgsFile ++ " and " ++ unmirrorablePkgsFile ++ ")"
mirrorPackages verbosity opts sourceRepo targetRepo pkgsToMirror'
finalizeMirror sourceRepo targetRepo
cacheTargetIndex sourceRepo targetRepo
case mirrorPostHook (mirrorConfig opts) of
Nothing -> return ()
Just postHook -> liftIO $ callCommand postHook
where
mirrorSession :: Bool
-> MirrorSession a -> IO (Maybe MirrorError, MirrorState)
mirrorSession keepGoing action =
liftM (\(eerr, st') -> (either Just (const Nothing) eerr,
fromErrorState st')) $
runMirrorSession verbosity keepGoing (toErrorState st) $ do
browserAction $ do
setUserAgent ("hackage-mirror/" ++ display version)
setErrHandler (warn verbosity)
setOutHandler (debug verbosity)
setAllowBasicAuth True
setCheckForProxy True
action
initRepos :: Sec.HttpLib -> ((SourceRepo, TargetRepo) -> IO a) -> IO a
initRepos httpLib callback =
withSourceRepo verbosity
httpLib
srcCacheDir
(mirrorSource (mirrorConfig opts))
$ \sourceRepo ->
withTargetRepo dstCacheDir
(mirrorTarget (mirrorConfig opts) )
$ \targetRepo ->
callback (sourceRepo, targetRepo)
mirrorPackages :: Verbosity
-> MirrorOpts
-> SourceRepo
-> TargetRepo
-> [PkgIndexInfo]
-> MirrorSession ()
mirrorPackages verbosity opts sourceRepo targetRepo pkgsToMirror = do
authenticate targetRepo
mapM_ (mirrorPackage verbosity opts sourceRepo targetRepo) pkgsToMirror
mirrorPackage :: Verbosity
-> MirrorOpts
-> SourceRepo
-> TargetRepo
-> PkgIndexInfo
-> MirrorSession ()
mirrorPackage verbosity opts sourceRepo targetRepo pkginfo = do
liftIO $ notice verbosity $ "mirroring " ++ display pkgid
go `mirrorFinally` removeTempFiles
where
go :: MirrorSession ()
go = do
rsp <- downloadPackage sourceRepo pkgid locCab locTgz
case rsp of
Just theError ->
notifyResponse (GetPackageFailed theError pkgid)
Nothing -> do
notifyResponse GetPackageOk
liftIO $ sanitiseTarball verbosity (stateDir opts) locTgz
uploadPackage targetRepo (mirrorUploaders opts) pkginfo locCab locTgz
removeTempFiles :: MirrorSession ()
removeTempFiles = liftIO $ handle ignoreDoesNotExist $ do
removeFile locTgz
removeFile locCab
ignoreDoesNotExist :: IOException -> IO ()
ignoreDoesNotExist ex = if isDoesNotExistError ex then return ()
else throwIO ex
PkgIndexInfo pkgid _ _ _ = pkginfo
locTgz = stateDir opts </> display pkgid <.> "tar.gz"
locCab = stateDir opts </> display pkgid <.> "cabal"
{-------------------------------------------------------------------------------
Operations on the the index
-------------------------------------------------------------------------------}
diffIndex :: [PkgIndexInfo] -> [PkgIndexInfo] -> [PkgIndexInfo]
diffIndex as bs =
[ pkg | OnlyInLeft pkg <- mergeBy (comparing mirrorPkgId)
(sortBy (comparing mirrorPkgId) as)
(sortBy (comparing mirrorPkgId) bs) ]
where
mirrorPkgId (PkgIndexInfo pkgid _ _ _) = pkgid
subsetIndex :: [PackageId] -> [PkgIndexInfo] -> [PkgIndexInfo]
subsetIndex pkgids =
filter (\(PkgIndexInfo pkgid' _ _ _) -> anyMatchPackage pkgid')
where
anyMatchPackage :: PackageId -> Bool
anyMatchPackage pkgid' =
any (\pkgid -> matchPackage pkgid pkgid') pkgids
matchPackage :: PackageId -> PackageId -> Bool
matchPackage (PackageIdentifier name v)
(PackageIdentifier name' _)
| nullVersion == v = name == name'
matchPackage pkgid pkgid' = pkgid == pkgid'
{-------------------------------------------------------------------------------
Auxiliary: dealing with tarballs
-------------------------------------------------------------------------------}
-- Some package tarballs have extraneous stuff in them that causes
-- them to fail the "tarbomb" test in the server. This cleans them
-- up before uploading.
sanitiseTarball :: Verbosity -> FilePath -> FilePath -> IO ()
sanitiseTarball verbosity tmpdir tgzpath = do
tgz <- BS.readFile tgzpath
let add _ (Left e) = Left e
add entry (Right entries) = Right (entry:entries)
eallentries = Tar.foldEntries add (Right []) (Left . show) $
Tar.read (GZip.decompressNamed tgzpath tgz)
case eallentries of
Left e -> warn verbosity e
Right allentries -> do
let okentries = filter dirOK allentries
newtgz = GZ.compress $ Tar.write $ reverse okentries
when (length allentries /= length okentries) $
warn verbosity $ "sanitising tarball for " ++ tgzpath
(tmpfp, tmph) <- openBinaryTempFileWithDefaultPermissions tmpdir "tmp.tgz"
hClose tmph
BS.writeFile tmpfp newtgz
renameFile tmpfp tgzpath
where
basedir = dropExtension $ takeBaseName tgzpath
dirOK entry = case splitDirectories (Tar.entryPath entry) of
(d:_) -> d == basedir
_ -> False
| edsko/hackage-server | exes/MirrorClient.hs | bsd-3-clause | 10,501 | 0 | 23 | 2,816 | 2,447 | 1,233 | 1,214 | 207 | 4 |
{-# LANGUAGE TemplateHaskell #-}
module Client.EntityT where
import Control.Lens (makeLenses)
import Linear (V3(..))
import Types
makeLenses ''EntityT
newEntityT :: EntityT
newEntityT = EntityT
{ _eModel = Nothing
, _eAngles = V3 0 0 0
, _eOrigin = V3 0 0 0
, _eFrame = 0
, _eOldOrigin = V3 0 0 0
, _eOldFrame = 0
, _eBackLerp = 0
, _eSkinNum = 0
, _eLightStyle = 0
, _eAlpha = 0
, _eSkin = Nothing
, _enFlags = 0
}
| ksaveljev/hake-2 | src/Client/EntityT.hs | bsd-3-clause | 549 | 0 | 7 | 214 | 145 | 88 | 57 | 20 | 1 |
module Calc.Base
( thenP
, returnP
, happyError
, Parser
, Token(..)
, tokenToPosN
, TokenClass(..)
, AlexPosn
, AlexState(..)
, lexer
, runAlex
)
where
----------------------------------------------------------------------------
import Calc.Lexer
----------------------------------------------------------------------------
-- For readablity - these are the interfaces Happy expects:
type Parser a = Alex a
thenP :: Parser a -> (a -> Parser b) -> Parser b
thenP = (>>=)
returnP :: a -> Parser a
returnP = return
alexShowError :: (Show t, Show t1) => (t, t1, Maybe String) -> Alex a
alexShowError (line, column, e) = alexError $ "show-error: " ++ (show (line, column, e))
alexGetPosition :: Alex (AlexPosn)
alexGetPosition = Alex $ \s@AlexState{alex_pos=pos} -> Right (s, pos)
happyError :: Parser a
happyError = do
(AlexPn _ line col) <- alexGetPosition
alexShowError (line, col, Nothing)
-- Link the lexer and the parser:
lexer :: (Token -> Parser a) -> Parser a
lexer f = alexMonadScan >>= f
| da-x/happy-alex-example | src/Calc/Base.hs | bsd-3-clause | 1,035 | 0 | 10 | 190 | 329 | 187 | 142 | 28 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
module Topic.Api (TopicApi, TopicEntity) where
import Servant
import Topic.Domain
import Data.Aeson.WithField
type TopicEntity = WithId TopicId Topic
type GetTopics =
"topics" :> Get '[JSON] [TopicEntity]
type CreateTopic =
"topics"
:> ReqBody '[JSON] Topic
:> Post '[JSON] TopicEntity
type DeleteTopic =
"topics" :> Capture "topic-id" TopicId
:> DeleteNoContent '[JSON] NoContent
type GetTopic =
"topics" :> Capture "topic-id" TopicId
:> Get '[JSON] TopicEntity
type UpsertTopic =
"topics" :> Capture "topic-id" TopicId
:> ReqBody '[JSON] Topic
:> Put '[JSON] TopicEntity
type TopicApi =
GetTopics
:<|> GetTopic
:<|> CreateTopic
:<|> DeleteTopic
:<|> UpsertTopic
| Unisay/dancher | src/Topic/Api.hs | bsd-3-clause | 766 | 0 | 10 | 141 | 221 | 121 | 100 | 29 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module DBHelper
( runDB
, strToKey
, int64ToKey
) where
import Data.Text (pack, unpack)
import Data.Int (Int64)
import Control.Monad.Trans (liftIO, MonadIO)
import qualified Database.Persist as P
import qualified Database.Persist.Store as PS
import qualified Database.Persist.GenericSql as PG
import Database.Persist.TH
runDB :: MonadIO m => PG.ConnectionPool -> PG.SqlPersist IO a -> m a
runDB p action = liftIO $ PG.runSqlPool action p
strToKey :: String -> PG.Key backend entity
strToKey x = PG.Key $ P.toPersistValue $ pack x
int64ToKey :: Int64 -> PG.Key backend entity
int64ToKey x = PG.Key $ P.toPersistValue x
| takei-shg/Magpie | DBHelper.hs | bsd-3-clause | 710 | 0 | 9 | 151 | 212 | 119 | 93 | 18 | 1 |
{-# LANGUAGE BangPatterns #-}
module ManualBang where
doesntEval :: Bool -> Int
doesntEval b = 1
manualSeq :: Bool -> Int
manualSeq b = b `seq` 1
banging :: Bool -> Int
banging !b = 1
data Foo = Foo Int !Int
first (Foo x _) = x
second (Foo _ y) = y | nicklawls/haskellbook | src/ManualBang.hs | bsd-3-clause | 255 | 0 | 7 | 60 | 107 | 57 | 50 | 13 | 1 |
module Network.MtGoxAPI.DepthStore.StressTest
( stressTest
) where
import Control.Monad
import Data.Time.Clock
import System.Random
import Network.MtGoxAPI.DepthStore
addRandomEntry :: DepthStoreHandle -> IO ()
addRandomEntry handle = do
t <- randomIO >>= \x -> if x
then return DepthStoreAsk
else return DepthStoreBid
amount <- randomRIO (1 * 10^(8::Integer), 10 * 10^(8::Integer))
price <- randomRIO (1 * 10^(5::Integer), 8 * 10^(5::Integer))
updateDepthStore handle t amount price
stressTest :: IO ()
stressTest = do
handle <- initDepthStore
getCurrentTime >>= print
forever $ do
replicateM_ 25000 $ addRandomEntry handle
_ <- simulateBTCSell handle 0
getCurrentTime >>= print
| javgh/mtgoxapi | Network/MtGoxAPI/DepthStore/StressTest.hs | bsd-3-clause | 808 | 0 | 11 | 218 | 255 | 132 | 123 | 22 | 2 |
{-# OPTIONS_GHC -Wall #-}
module Main where
import Eel
main :: IO ()
main = mainM "main.ll" $ \argc _argv -> add (lit 42) argc
| stevezhee/eel | app/Main.hs | bsd-3-clause | 129 | 0 | 9 | 27 | 48 | 26 | 22 | 5 | 1 |
import Control.Concurrent (forkIO)
import qualified Control.Exception as E
import Control.Pipe
import Control.Pipe.Binary
import Network (connectTo, PortID (..))
import System.Environment (getArgs, getProgName)
import System.IO
main :: IO ()
main = do
args <- getArgs
case args of
[host, port] -> telnet host (read port :: Int)
_ -> usageExit
where
usageExit = do
name <- getProgName
putStrLn $ "Usage : " ++ name ++ " host port"
hConnect :: Handle -> Handle -> IO ()
hConnect h1 h2 = runPipe $ handleReader h1 >+> handleWriter h2
telnet :: String -> Int -> IO ()
telnet host port = E.bracket
(connectTo host (PortNumber (fromIntegral port)))
hClose
(\hsock -> do
mapM_ (`hSetBuffering` LineBuffering) [ stdin, stdout, hsock ]
_ <- forkIO $ hConnect stdin hsock
hConnect hsock stdout)
| pcapriotti/pipes-extra | examples/telnet.hs | bsd-3-clause | 865 | 0 | 12 | 205 | 307 | 162 | 145 | 26 | 2 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, FlexibleContexts #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.AutoMaster
-- Description : Change size of the stack area depending on the number of its windows.
-- Copyright : (c) 2009 Ilya Portnov
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Ilya Portnov <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- Provides layout modifier AutoMaster. It separates screen in two parts -
-- master and slave. Size of slave area automatically changes depending on
-- number of slave windows.
--
-----------------------------------------------------------------------------
module XMonad.Layout.AutoMaster (
-- * Usage
-- $usage
autoMaster, AutoMaster
) where
import XMonad
import XMonad.Layout.LayoutModifier
import XMonad.Prelude
import qualified XMonad.StackSet as W
import Control.Arrow (first)
-- $usage
-- This module defines layout modifier named autoMaster. It separates
-- screen in two parts - master and slave. Master windows are arranged
-- in one row, in slave area underlying layout is run. Size of slave area
-- automatically increases when number of slave windows is increasing.
--
-- You can use this module by adding folowing in your @xmonad.hs@:
--
-- > import XMonad.Layout.AutoMaster
--
-- Then add layouts to your layoutHook:
--
-- > myLayoutHook = autoMaster 1 (1/100) Grid ||| ...
--
-- In this example, master area by default contains 1 window (you can
-- change this number in runtime with usual IncMasterN message), changing
-- slave area size with 1/100 on each Shrink/Expand message.
-- | Data type for layout modifier
data AutoMaster a = AutoMaster Int Float Float
deriving (Read,Show)
instance (Eq w) => LayoutModifier AutoMaster w where
modifyLayout (AutoMaster k bias _) = autoLayout k bias
pureMess = autoMess
-- | Handle Shrink/Expand and IncMasterN messages
autoMess :: AutoMaster a -> SomeMessage -> Maybe (AutoMaster a)
autoMess (AutoMaster k bias delta) m = msum [fmap resize (fromMessage m),
fmap incmastern (fromMessage m)]
where incmastern (IncMasterN d) = AutoMaster (max 1 (k+d)) bias delta
resize Expand = AutoMaster k (min 0.4 $ bias+delta) delta
resize Shrink = AutoMaster k (max (-0.4) $ bias-delta) delta
-- | Main layout function
autoLayout :: (Eq w, LayoutClass l w) =>
Int ->
Float ->
W.Workspace WorkspaceId (l w) w
-> Rectangle
-> X ([(w, Rectangle)], Maybe (l w))
autoLayout k bias wksp rect = do
let stack = W.stack wksp
let ws = W.integrate' stack
let n = length ws
if null ws then
runLayout wksp rect
else
if n<=k then
return (divideRow rect ws,Nothing)
else do
let master = take k ws
let filtStack = stack >>= W.filter (`notElem` master)
wrs <- runLayout (wksp {W.stack = filtStack}) (slaveRect rect n bias)
return $ first (divideRow (masterRect rect n bias) master ++)
wrs
-- | Calculates height of master area, depending on number of windows.
masterHeight :: Int -> Float -> Float
masterHeight n bias = calcHeight n + bias
where calcHeight :: Int -> Float
calcHeight 1 = 1.0
calcHeight m = if m<9 then (43/45) - fromIntegral m*(7/90) else 1/3
-- | Rectangle for master area
masterRect :: Rectangle -> Int -> Float -> Rectangle
masterRect (Rectangle sx sy sw sh) n bias = Rectangle sx sy sw h
where h = round $ fromIntegral sh*masterHeight n bias
-- | Rectangle for slave area
slaveRect :: Rectangle -> Int -> Float -> Rectangle
slaveRect (Rectangle sx sy sw sh) n bias = Rectangle sx (sy+mh) sw h
where mh = round $ fromIntegral sh*masterHeight n bias
h = round $ fromIntegral sh*(1-masterHeight n bias)
-- | Divide rectangle between windows
divideRow :: Rectangle -> [a] -> [(a, Rectangle)]
divideRow (Rectangle x y w h) ws = zip ws rects
where n = length ws
oneW = fromIntegral w `div` n
oneRect = Rectangle x y (fromIntegral oneW) h
rects = take n $ iterate (shiftR (fromIntegral oneW)) oneRect
-- | Shift rectangle right
shiftR :: Position -> Rectangle -> Rectangle
shiftR s (Rectangle x y w h) = Rectangle (x+s) y w h
-- | User interface function
autoMaster :: LayoutClass l a =>
Int -> -- Number of master windows
Float -> -- Step for which to increment/decrement master area size with Shrink/Expand
l a ->
ModifiedLayout AutoMaster l a
autoMaster nmaster delta = ModifiedLayout (AutoMaster nmaster 0 delta)
| xmonad/xmonad-contrib | XMonad/Layout/AutoMaster.hs | bsd-3-clause | 4,927 | 0 | 16 | 1,302 | 1,140 | 604 | 536 | 65 | 3 |
{-# LANGUAGE BangPatterns, RankNTypes, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module ECC.Code.LDPC.ElimTanh where
-- Implementation of LDPC, that approximates
-- 2 *tanh−1 ( PRODUCT [ tanh ( |Z(x[n′])| / 2)] )
-- with:
-- min |Z(x[n′])|
-- where n' eltOf N(m)\n (same for each equation)
--
-- See the paper, "Reduced-Complexity Decoding of LDPC Codes"
-- by J. Chen, A. Dholakia, E. Eleftheriou, M. Fossorier, and X.–Y. Hu
import ECC.Types
import ECC.Puncture
import Data.Char (isDigit)
import Data.Matrix
import qualified Data.Vector as V
type M a = Matrix a
type V a = V.Vector a
code :: Code
code = Code ["ldpc/elimTanh/<matrix-name>/<max-rounds>[/<truncation-size>]"]
(pure ())
(const (pure ()))
$ \ vars xs -> return []
{-
Code ["ldpc/elimTanh/<matrix-name>/<max-rounds>[/<truncation-size>]"]
$ \ xs -> case xs of
["ldpc","elimTanh",m,n]
| all isDigit n -> fmap (: []) $ mkLDPC m (read n)
["ldpc","elimTanh",m,n,t]
| all isDigit n
&& all isDigit t -> fmap (: []) $ fmap (punctureTail (read t)) $ mkLDPC m (read n)
_ -> return []
mkLDPC :: String -> Int -> IO ECC
mkLDPC codeName maxI = do
g :: G <- readAlist ("codes/" ++ codeName ++ ".G") -- with G, we prepend the identity
let full_g = identity (nrows g) <|> g
h :: H <- readAlist ("codes/" ++ codeName ++ ".H")
return $ ECC
{ name = "ldpc/elimTanh/" ++ codeName ++ "/" ++ show maxI
, encode = return . V.toList . encoder full_g . V.fromList
, decode = return . (,True) . take (nrows full_g) . V.toList . ldpc maxI h . V.fromList
, message_length = nrows full_g
, codeword_length = ncols full_g
}
type G = M Bit
type H = M Bit
encoder :: G -> V Bit -> V Bit
encoder g v = getRow 1 (multStd (rowVector v) g)
---------------------------------------------------------------------
ldpc :: Int -> M Bit -> V Double -> V Bit
ldpc maxIterations a orig_lam = fmap hard $ loop 0 orig_ne orig_lam
where
orig_ne :: M Double
orig_ne = fmap (const 0) a
loop :: Int -> M Double -> V Double -> V Double
loop !n ne lam
| V.all (== 0) ans = lam
| n >= maxIterations = orig_lam
| otherwise = loop (n+1) ne' lam'
where
c_hat :: V Bit
c_hat = fmap hard lam
ans :: V Bit
ans = getCol 1 (a `multStd` colVector c_hat)
ne' :: M Double
ne' = matrix (nrows orig_ne) (ncols orig_ne) $ \ (m,n) ->
if a ! (m,n) == 1
then
let bigVal = 100.0
(signProduct, absval) =
foldl ( \ (signProduct, curmin) x -> (signProduct /= ((signum x) == (-1)), min curmin (abs x)))
(False, bigVal)
[ lam V.! (j-1) - ne ! (m,j) | j <- [1 .. V.length orig_lam]
, j /= n
, a ! (m,j) == 1]
in if signProduct then negate absval else absval
else 0
lam' :: V Double
lam' = V.fromList [ V.foldr (+) (orig_lam V.! (j - 1)) (getCol j ne')
| j <- [1 .. V.length lam]
]
-}
| ku-fpg/ecc-ldpc | src/ECC/Code/LDPC/ElimTanh.hs | bsd-3-clause | 3,476 | 0 | 11 | 1,257 | 132 | 81 | 51 | 15 | 1 |
-- | Tokenization breaks a 'String' into pieces of whitespace,
-- constants, symbols, and identifiers.
module Hpp.Tokens where
import Data.Char (isAlphaNum, isDigit, isSpace)
-- | Tokenization is 'words' except the white space is tagged rather
-- than discarded.
data Token = Important String
-- ^ Identifiers, symbols, and constants
| Other String
-- ^ White space, etc.
deriving (Eq,Ord,Show)
-- | Extract the contents of a 'Token'.
detok :: Token -> String
detok (Important s) = s
detok (Other s) = s
-- | 'True' if the given 'Token' is 'Important'; 'False' otherwise.
isImportant :: Token -> Bool
isImportant (Important _) = True
isImportant _ = False
-- | Return the contents of only 'Important' (non-space) tokens.
importants :: [Token] -> [String]
importants = map detok . filter isImportant
-- | Break a 'String' into space and non-whitespace runs.
tokWords :: String -> [Token]
tokWords [] = []
tokWords (c:cs)
| isSpace c = let (spaces,rst) = break (not . isSpace) cs
in Other (c : spaces) : tokWords rst
| c == '\'' && isCharLit = goCharLit
| c == '"' = flip skipLiteral cs $ \str rst ->
Important (str []) : tokWords rst
| otherwise = let (chars,rst) = break (not . validIdentifierChar) cs
in Important (c:chars) : tokWords rst
where (isCharLit, goCharLit) =
case cs of
(c':'\'':cs') -> (True, Important ['\'',c','\''] : tokWords cs')
_ -> (False, [])
-- | If you encounter a string literal, call this helper with a
-- double-barreled continuation and the rest of your input. The
-- continuation will be called with the remainder of the string
-- literal as the first argument, and the remaining input as the
-- second argument.
skipLiteral :: ((String -> String) -> String -> r) -> String -> r
skipLiteral k = go ('"':)
where go acc ('\\':'\\':cs) = go (acc . ("\\\\"++)) cs
go acc ('\\':'"':cs) = go (acc . ("\\\""++)) cs
-- go acc (c:'"':cs) = k (acc . ([c,'"']++)) cs
go acc ('"':cs) = k (acc . ('"':)) cs
go acc (c:cs) = go (acc . (c :)) cs
go acc [] = k acc []
-- | @splits isDelimiter str@ tokenizes @str@ using @isDelimiter@ as a
-- delimiter predicate. Leading whitespace is also stripped from
-- tokens.
splits :: (Char -> Bool) -> String -> [String]
splits isDelim = filter (not . null) . go . dropWhile isSpace
where go s = case break isDelim s of
(h,[]) -> [dropWhile isSpace h]
(h,d:t) -> dropWhile isSpace h : [d] : go t
-- | Predicate on space characters based on something approximating
-- valid identifier syntax. This is used to break apart non-space
-- characters.
validIdentifierChar :: Char -> Bool
validIdentifierChar c = isAlphaNum c || c == '_' || c == '\''
-- | Something like @12E+FOO@ is a single pre-processor token, so
-- @FOO@ should not be macro expanded.
fixExponents :: [Token] -> [Token]
fixExponents [] = []
fixExponents (Important (t1@(d1:_)):Important [c]:Important (d2:t2):ts)
| elem c "-+" && isDigit d1 && elem (last t1) "eE" && isAlphaNum d2 =
Important (t1++c:d2:t2) : fixExponents ts
fixExponents (t:ts) = t : fixExponents ts
-- | Break an input 'String' into a sequence of 'Tokens'. Warning:
-- This may not exactly correspond to your target language's
-- definition of a valid identifier!
tokenize :: String -> [Token]
tokenize = fixExponents . concatMap seps . tokWords
where seps t@(Other _) = [t]
seps t@(Important ('"':_)) = [t]
seps t@(Important ('\'':_)) = [t]
seps (Important s) = map Important $
splits (not . validIdentifierChar) s
-- | Collapse a sequence of 'Tokens' back into a 'String'. @detokenize
-- . tokenize == id@.
detokenize :: [Token] -> String
detokenize = concatMap detok
| bitemyapp/hpp | src/Hpp/Tokens.hs | bsd-3-clause | 3,852 | 0 | 13 | 916 | 1,146 | 608 | 538 | 56 | 5 |
{-# language CPP #-}
-- | = Name
--
-- XR_EXT_eye_gaze_interaction - instance extension
--
-- = Specification
--
-- See
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XR_EXT_eye_gaze_interaction XR_EXT_eye_gaze_interaction>
-- in the main specification for complete information.
--
-- = Registered Extension Number
--
-- 31
--
-- = Revision
--
-- 1
--
-- = Extension and Version Dependencies
--
-- - Requires OpenXR 1.0
--
-- = See Also
--
-- 'EyeGazeSampleTimeEXT', 'SystemEyeGazeInteractionPropertiesEXT'
--
-- = Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XR_EXT_eye_gaze_interaction OpenXR Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module OpenXR.Extensions.XR_EXT_eye_gaze_interaction ( SystemEyeGazeInteractionPropertiesEXT(..)
, EyeGazeSampleTimeEXT(..)
, EXT_eye_gaze_interaction_SPEC_VERSION
, pattern EXT_eye_gaze_interaction_SPEC_VERSION
, EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME
, pattern EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME
) where
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import OpenXR.CStruct (FromCStruct)
import OpenXR.CStruct (FromCStruct(..))
import OpenXR.CStruct (ToCStruct)
import OpenXR.CStruct (ToCStruct(..))
import OpenXR.Zero (Zero(..))
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import Foreign.Ptr (Ptr)
import Data.Kind (Type)
import OpenXR.Core10.FundamentalTypes (bool32ToBool)
import OpenXR.Core10.FundamentalTypes (boolToBool32)
import OpenXR.Core10.FundamentalTypes (Bool32)
import OpenXR.Core10.Enums.StructureType (StructureType)
import OpenXR.Core10.FundamentalTypes (Time)
import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_EYE_GAZE_SAMPLE_TIME_EXT))
import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_SYSTEM_EYE_GAZE_INTERACTION_PROPERTIES_EXT))
-- | XrSystemEyeGazeInteractionPropertiesEXT - Eye gaze interaction system
-- properties
--
-- == Valid Usage (Implicit)
--
-- - #VUID-XrSystemEyeGazeInteractionPropertiesEXT-extension-notenabled#
-- The @XR_EXT_eye_gaze_interaction@ extension /must/ be enabled prior
-- to using 'SystemEyeGazeInteractionPropertiesEXT'
--
-- - #VUID-XrSystemEyeGazeInteractionPropertiesEXT-type-type# @type@
-- /must/ be
-- 'OpenXR.Core10.Enums.StructureType.TYPE_SYSTEM_EYE_GAZE_INTERACTION_PROPERTIES_EXT'
--
-- - #VUID-XrSystemEyeGazeInteractionPropertiesEXT-next-next# @next@
-- /must/ be @NULL@ or a valid pointer to the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#valid-usage-for-structure-pointer-chains next structure in a structure chain>
--
-- = See Also
--
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrBool32 >,
-- 'OpenXR.Core10.Enums.StructureType.StructureType'
data SystemEyeGazeInteractionPropertiesEXT = SystemEyeGazeInteractionPropertiesEXT
{ -- | @supportsEyeGazeInteraction@ the runtime /must/ set this value to
-- 'OpenXR.Core10.FundamentalTypes.TRUE' when eye gaze sufficient for use
-- cases such as aiming or targeting is supported by the current device,
-- otherwise the runtime /must/ set this to
-- 'OpenXR.Core10.FundamentalTypes.FALSE'.
supportsEyeGazeInteraction :: Bool }
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (SystemEyeGazeInteractionPropertiesEXT)
#endif
deriving instance Show SystemEyeGazeInteractionPropertiesEXT
instance ToCStruct SystemEyeGazeInteractionPropertiesEXT where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p SystemEyeGazeInteractionPropertiesEXT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SYSTEM_EYE_GAZE_INTERACTION_PROPERTIES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (supportsEyeGazeInteraction))
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SYSTEM_EYE_GAZE_INTERACTION_PROPERTIES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero))
f
instance FromCStruct SystemEyeGazeInteractionPropertiesEXT where
peekCStruct p = do
supportsEyeGazeInteraction <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32))
pure $ SystemEyeGazeInteractionPropertiesEXT
(bool32ToBool supportsEyeGazeInteraction)
instance Storable SystemEyeGazeInteractionPropertiesEXT where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero SystemEyeGazeInteractionPropertiesEXT where
zero = SystemEyeGazeInteractionPropertiesEXT
zero
-- | XrEyeGazeSampleTimeEXT - Eye gaze sample time structure
--
-- == Valid Usage (Implicit)
--
-- - #VUID-XrEyeGazeSampleTimeEXT-extension-notenabled# The
-- @XR_EXT_eye_gaze_interaction@ extension /must/ be enabled prior to
-- using 'EyeGazeSampleTimeEXT'
--
-- - #VUID-XrEyeGazeSampleTimeEXT-type-type# @type@ /must/ be
-- 'OpenXR.Core10.Enums.StructureType.TYPE_EYE_GAZE_SAMPLE_TIME_EXT'
--
-- - #VUID-XrEyeGazeSampleTimeEXT-next-next# @next@ /must/ be @NULL@ or a
-- valid pointer to the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#valid-usage-for-structure-pointer-chains next structure in a structure chain>
--
-- = See Also
--
-- 'OpenXR.Core10.Enums.StructureType.StructureType',
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrTime >
data EyeGazeSampleTimeEXT = EyeGazeSampleTimeEXT
{ -- | @time@ is when in time the eye gaze pose is expressed.
time :: Time }
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (EyeGazeSampleTimeEXT)
#endif
deriving instance Show EyeGazeSampleTimeEXT
instance ToCStruct EyeGazeSampleTimeEXT where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p EyeGazeSampleTimeEXT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_EYE_GAZE_SAMPLE_TIME_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Time)) (time)
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_EYE_GAZE_SAMPLE_TIME_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Time)) (zero)
f
instance FromCStruct EyeGazeSampleTimeEXT where
peekCStruct p = do
time <- peek @Time ((p `plusPtr` 16 :: Ptr Time))
pure $ EyeGazeSampleTimeEXT
time
instance Storable EyeGazeSampleTimeEXT where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero EyeGazeSampleTimeEXT where
zero = EyeGazeSampleTimeEXT
zero
type EXT_eye_gaze_interaction_SPEC_VERSION = 1
-- No documentation found for TopLevel "XR_EXT_eye_gaze_interaction_SPEC_VERSION"
pattern EXT_eye_gaze_interaction_SPEC_VERSION :: forall a . Integral a => a
pattern EXT_eye_gaze_interaction_SPEC_VERSION = 1
type EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME = "XR_EXT_eye_gaze_interaction"
-- No documentation found for TopLevel "XR_EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME"
pattern EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME = "XR_EXT_eye_gaze_interaction"
| expipiplus1/vulkan | openxr/src/OpenXR/Extensions/XR_EXT_eye_gaze_interaction.hs | bsd-3-clause | 8,099 | 0 | 14 | 1,391 | 1,405 | 814 | 591 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.