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 FlexibleInstances #-}
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
module Thrift.Transport.HttpClient
( module Thrift.Transport
, HttpClient (..)
, openHttpClient
) where
import Thrift.Transport
import Thrift.Transport.IOBuffer
import Network.URI
import Network.HTTP hiding (port, host)
import Data.Maybe (fromJust)
import Data.Monoid (mempty)
import Control.Exception (throw)
import qualified Data.ByteString.Lazy as LBS
-- | 'HttpClient', or THttpClient implements the Thrift Transport
-- | Layer over http or https.
data HttpClient =
HttpClient {
hstream :: HandleStream LBS.ByteString,
uri :: URI,
writeBuffer :: WriteBuffer,
readBuffer :: ReadBuffer
}
uriAuth :: URI -> URIAuth
uriAuth = fromJust . uriAuthority
host :: URI -> String
host = uriRegName . uriAuth
port :: URI -> Int
port uri_ =
if portStr == mempty then
httpPort
else
read portStr
where
portStr = dropWhile (== ':') $ uriPort $ uriAuth uri_
httpPort = 80
-- | Use 'openHttpClient' to create an HttpClient connected to @uri@
openHttpClient :: URI -> IO HttpClient
openHttpClient uri_ = do
stream <- openTCPConnection (host uri_) (port uri_)
wbuf <- newWriteBuffer
rbuf <- newReadBuffer
return $ HttpClient stream uri_ wbuf rbuf
instance Transport HttpClient where
tClose = close . hstream
tPeek = peekBuf . readBuffer
tRead = readBuf . readBuffer
tWrite = writeBuf . writeBuffer
tFlush hclient = do
body <- flushBuf $ writeBuffer hclient
let request = Request {
rqURI = uri hclient,
rqHeaders = [
mkHeader HdrContentType "application/x-thrift",
mkHeader HdrContentLength $ show $ LBS.length body],
rqMethod = POST,
rqBody = body
}
res <- sendHTTP (hstream hclient) request
case res of
Right response ->
fillBuf (readBuffer hclient) (rspBody response)
Left _ ->
throw $ TransportExn "THttpConnection: HTTP failure from server" TE_UNKNOWN
return ()
tIsOpen _ = return True
| jcgruenhage/dendrite | vendor/src/github.com/apache/thrift/lib/hs/src/Thrift/Transport/HttpClient.hs | apache-2.0 | 2,967 | 0 | 16 | 755 | 545 | 301 | 244 | 58 | 2 |
-- -------------------------------------------------------------------------------------
-- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
-- For email, run on linux (perl v5.8.5):
-- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
-- -------------------------------------------------------------------------------------
import Data.List
main :: IO ()
main = do
ip <- getContents
let ts = map read . words . last . lines $ ip
ans = snd . foldl' (\a@(freeTill, spent) wt ->
if wt <= freeTill then (freeTill, spent) else (wt + 4, spent + 1) )
(-1, 0) $ sort ts
putStrLn $ show ans
| cbrghostrider/Hacking | HackerRank/Algorithms/Greedy/priyankaAndToys.hs | mit | 739 | 0 | 17 | 187 | 151 | 82 | 69 | 9 | 2 |
-- | Helper functions for template Haskell, to avoid stage restrictions.
module Strive.Internal.TH
( options
, makeLenses
) where
import Data.Aeson.TH (Options, defaultOptions, fieldLabelModifier)
import Data.Char (isUpper, toLower, toUpper)
import Data.Maybe (isJust)
import qualified Language.Haskell.TH as TH
import qualified Language.Haskell.TH.Syntax as TH
-- | Default FromJSON options.
options :: Options
options = defaultOptions
{ fieldLabelModifier = underscore . dropPrefix
}
underscore :: String -> String
underscore = concatMap go
where
go c = if isUpper c
then ['_', toLower c]
else [c]
dropPrefix :: String -> String
dropPrefix = drop 1 . dropWhile (/= '_')
-- | Generate lens classes and instances for a type.
makeLenses :: String -> TH.Q [TH.Dec]
makeLenses string = do
maybeName <- TH.lookupTypeName string
case maybeName of
Just name -> do
info <- TH.reify name
case info of
TH.TyConI (TH.DataD _ _ _ _ [TH.RecC _ triples] _) -> do
classes <- makeLensClasses triples
instances <- makeLensInstances name triples
return (classes ++ instances)
_ -> fail "reify failed"
_ -> fail "lookupTypeName failed"
makeLensClasses :: [TH.VarStrictType] -> TH.Q [TH.Dec]
makeLensClasses [] = return []
makeLensClasses (triple : triples) = do
exists <- lensExists triple
if exists
then makeLensClasses triples
else do
klass <- makeLensClass triple
classes <- makeLensClasses triples
return (klass : classes)
makeLensClass :: TH.VarStrictType -> TH.Q TH.Dec
makeLensClass triple = do
exists <- lensExists triple
if exists
then fail "lens already exists"
else do
a <- TH.newName "a"
b <- TH.newName "b"
let klass = TH.ClassD [] name types dependencies declarations
name = TH.mkName (getLensName triple)
types = [TH.PlainTV a, TH.PlainTV b]
dependencies = [TH.FunDep [a] [b]]
declarations = [TH.SigD field typ]
field = TH.mkName (getFieldName triple)
typ = TH.AppT (TH.AppT (TH.ConT (TH.mkName "Lens")) (TH.VarT a)) (TH.VarT b)
return klass
lensExists :: TH.VarStrictType -> TH.Q Bool
lensExists triple = do
let name = getLensName triple
maybeName <- TH.lookupTypeName name
return (isJust maybeName)
getLensName :: TH.VarStrictType -> String
getLensName triple = capitalize (getFieldName triple) ++ "Lens"
capitalize :: String -> String
capitalize "" = ""
capitalize (c : cs) = toUpper c : cs
getFieldName :: TH.VarStrictType -> String
getFieldName (var, _, _) = (lensName . show) var
lensName :: String -> String
lensName x = if y `elem` keywords then y ++ "_" else y
where
y = dropPrefix x
keywords = ["data", "type"]
makeLensInstances :: TH.Name -> [TH.VarStrictType] -> TH.Q [TH.Dec]
makeLensInstances name triples = mapM (makeLensInstance name) triples
makeLensInstance :: TH.Name -> TH.VarStrictType -> TH.Q TH.Dec
makeLensInstance name triple@(var, _, typ) = do
f <- TH.newName "f"
x <- TH.newName "x"
a <- TH.newName "a"
Just fmap' <- TH.lookupValueName "fmap"
let field = TH.mkName (getFieldName triple)
return $ TH.InstanceD
Nothing
[]
(TH.AppT (TH.AppT (TH.ConT (TH.mkName (getLensName triple))) (TH.ConT name)) typ)
[TH.FunD field [TH.Clause [TH.VarP f, TH.VarP x] (TH.NormalB (TH.AppE (TH.AppE (TH.VarE fmap') (TH.LamE [TH.VarP a] (TH.RecUpdE (TH.VarE x) [(var, TH.VarE a)]))) (TH.AppE (TH.VarE f) (TH.AppE (TH.VarE var) (TH.VarE x))))) []]]
| liskin/strive | library/Strive/Internal/TH.hs | mit | 3,523 | 0 | 26 | 749 | 1,337 | 677 | 660 | 87 | 3 |
{-# htermination foldM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a #-}
import Monad
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Monad_foldM_2.hs | mit | 90 | 0 | 3 | 24 | 5 | 3 | 2 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module with consumer properties types and functions.
-----------------------------------------------------------------------------
module Kafka.Consumer.ConsumerProperties
( ConsumerProperties(..)
, CallbackPollMode(..)
, brokersList
, autoCommit
, noAutoCommit
, noAutoOffsetStore
, groupId
, clientId
, setCallback
, logLevel
, compression
, suppressDisconnectLogs
, statisticsInterval
, extraProps
, extraProp
, debugOptions
, queuedMaxMessagesKBytes
, callbackPollMode
, module X
)
where
import Control.Monad (MonadPlus (mplus))
import Data.Map (Map)
import qualified Data.Map as M
import Data.Semigroup as Sem
import Data.Text (Text)
import qualified Data.Text as Text
import Kafka.Consumer.Types (ConsumerGroupId (..))
import Kafka.Internal.Setup (KafkaConf (..), Callback(..))
import Kafka.Types (BrokerAddress (..), ClientId (..), KafkaCompressionCodec (..), KafkaDebug (..), KafkaLogLevel (..), Millis (..), kafkaCompressionCodecToText, kafkaDebugToText)
import Kafka.Consumer.Callbacks as X
-- | Whether the callback polling should be done synchronously or not.
data CallbackPollMode =
-- | You have to poll the consumer frequently to handle new messages
-- as well as rebalance and keep alive events.
-- This enables lowering the footprint and having full control over when polling
-- happens, at the cost of manually managing those events.
CallbackPollModeSync
-- | Handle polling rebalance and keep alive events for you in a background thread.
| CallbackPollModeAsync deriving (Show, Eq)
-- | Properties to create 'Kafka.Consumer.Types.KafkaConsumer'.
data ConsumerProperties = ConsumerProperties
{ cpProps :: Map Text Text
, cpLogLevel :: Maybe KafkaLogLevel
, cpCallbacks :: [Callback]
, cpCallbackPollMode :: CallbackPollMode
}
instance Sem.Semigroup ConsumerProperties where
(ConsumerProperties m1 ll1 cb1 _) <> (ConsumerProperties m2 ll2 cb2 cup2) =
ConsumerProperties (M.union m2 m1) (ll2 `mplus` ll1) (cb1 `mplus` cb2) cup2
{-# INLINE (<>) #-}
-- | /Right biased/ so we prefer newer properties over older ones.
instance Monoid ConsumerProperties where
mempty = ConsumerProperties
{ cpProps = M.empty
, cpLogLevel = Nothing
, cpCallbacks = []
, cpCallbackPollMode = CallbackPollModeAsync
}
{-# INLINE mempty #-}
mappend = (Sem.<>)
{-# INLINE mappend #-}
-- | Set the <https://kafka.apache.org/documentation/#bootstrap.servers list of brokers> to contact to connect to the Kafka cluster.
brokersList :: [BrokerAddress] -> ConsumerProperties
brokersList bs =
let bs' = Text.intercalate "," (unBrokerAddress <$> bs)
in extraProps $ M.fromList [("bootstrap.servers", bs')]
-- | Set the <https://kafka.apache.org/documentation/#auto.commit.interval.ms auto commit interval> and enables <https://kafka.apache.org/documentation/#enable.auto.commit auto commit>.
autoCommit :: Millis -> ConsumerProperties
autoCommit (Millis ms) = extraProps $
M.fromList
[ ("enable.auto.commit", "true")
, ("auto.commit.interval.ms", Text.pack $ show ms)
]
-- | Disable <https://kafka.apache.org/documentation/#enable.auto.commit auto commit> for the consumer.
noAutoCommit :: ConsumerProperties
noAutoCommit =
extraProps $ M.fromList [("enable.auto.commit", "false")]
-- | Disable auto offset store for the consumer.
--
-- See <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md enable.auto.offset.store> for more information.
noAutoOffsetStore :: ConsumerProperties
noAutoOffsetStore =
extraProps $ M.fromList [("enable.auto.offset.store", "false")]
-- | Set the consumer <https://kafka.apache.org/documentation/#group.id group id>.
groupId :: ConsumerGroupId -> ConsumerProperties
groupId (ConsumerGroupId cid) =
extraProps $ M.fromList [("group.id", cid)]
-- | Set the <https://kafka.apache.org/documentation/#client.id consumer identifier>.
clientId :: ClientId -> ConsumerProperties
clientId (ClientId cid) =
extraProps $ M.fromList [("client.id", cid)]
-- | Set the consumer callback.
--
-- For examples of use, see:
--
-- * 'errorCallback'
-- * 'logCallback'
-- * 'statsCallback'
setCallback :: Callback -> ConsumerProperties
setCallback cb = mempty { cpCallbacks = [cb] }
-- | Set the logging level.
-- Usually is used with 'debugOptions' to configure which logs are needed.
logLevel :: KafkaLogLevel -> ConsumerProperties
logLevel ll = mempty { cpLogLevel = Just ll }
-- | Set the <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md compression.codec> for the consumer.
compression :: KafkaCompressionCodec -> ConsumerProperties
compression c =
extraProps $ M.singleton "compression.codec" (kafkaCompressionCodecToText c)
-- | Suppresses consumer <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md log.connection.close>.
--
-- It might be useful to turn this off when interacting with brokers
-- with an aggressive @connection.max.idle.ms@ value.
suppressDisconnectLogs :: ConsumerProperties
suppressDisconnectLogs =
extraProps $ M.fromList [("log.connection.close", "false")]
-- | Set the <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md statistics.interval.ms> for the producer.
statisticsInterval :: Millis -> ConsumerProperties
statisticsInterval (Millis t) =
extraProps $ M.singleton "statistics.interval.ms" (Text.pack $ show t)
-- | Set any configuration options that are supported by /librdkafka/.
-- The full list can be found <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md here>
extraProps :: Map Text Text -> ConsumerProperties
extraProps m = mempty { cpProps = m }
{-# INLINE extraProps #-}
-- | Set any configuration option that is supported by /librdkafka/.
-- The full list can be found <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md here>
extraProp :: Text -> Text -> ConsumerProperties
extraProp k v = mempty { cpProps = M.singleton k v }
{-# INLINE extraProp #-}
-- | Set <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md debug> features for the consumer.
-- Usually is used with 'logLevel'.
debugOptions :: [KafkaDebug] -> ConsumerProperties
debugOptions [] = extraProps M.empty
debugOptions d =
let points = Text.intercalate "," (kafkaDebugToText <$> d)
in extraProps $ M.fromList [("debug", points)]
-- | Set <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md queued.max.messages.kbytes>
queuedMaxMessagesKBytes :: Int -> ConsumerProperties
queuedMaxMessagesKBytes kBytes =
extraProp "queued.max.messages.kbytes" (Text.pack $ show kBytes)
{-# INLINE queuedMaxMessagesKBytes #-}
-- | Set the callback poll mode. Default value is 'CallbackPollModeAsync'.
callbackPollMode :: CallbackPollMode -> ConsumerProperties
callbackPollMode mode = mempty { cpCallbackPollMode = mode }
| haskell-works/kafka-client | src/Kafka/Consumer/ConsumerProperties.hs | mit | 7,103 | 0 | 11 | 1,121 | 1,110 | 656 | 454 | 103 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeFamilies #-}
--------------------------------------------------------------------
-- |
-- Copyright : © Oleg Grenrus 2014
-- License : MIT
-- Maintainer: Oleg Grenrus <[email protected]>
-- Stability : experimental
-- Portability: non-portable
--
--------------------------------------------------------------------
module Data.Algebra.Boolean.NormalForm (
NormalForm(..),
module Data.Algebra.Boolean.CoBoolean
) where
import Data.Algebra.Boolean.CoBoolean
import Data.Algebra.Boolean.FreeBoolean
import GHC.Exts (Constraint)
-- | Class unifying different boolean normal forms.
class CoBoolean1 nf => NormalForm nf where
-- | 'NormalForm' could be constrained, so the 'Set' based implementations could be included.
type NFConstraint nf a :: Constraint
type NFConstraint nf a = ()
-- | Lift a value into normal form.
toNormalForm :: a -> nf a
-- | Simplify the formula, if some terms are ⊥ or ⊤.
simplify :: (NFConstraint nf a) => (a -> Maybe Bool) -> nf a -> nf a
-- | transform from free boolean form
fromFreeBoolean :: (NFConstraint nf a) => FreeBoolean a -> nf a
instance NormalForm FreeBoolean where
toNormalForm = FBValue
simplify _ = id
fromFreeBoolean = id
| phadej/boolean-normal-forms | src/Data/Algebra/Boolean/NormalForm.hs | mit | 1,275 | 0 | 11 | 220 | 206 | 123 | 83 | 18 | 0 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE BangPatterns #-}
-- | This module provides the ability to create reapers: dedicated cleanup
-- threads. These threads will automatically spawn and die based on the
-- presence of a workload to process on. Example uses include:
--
-- * Killing long-running jobs
-- * Closing unused connections in a connection pool
-- * Pruning a cache of old items (see example below)
--
-- For real-world usage, search the <https://github.com/yesodweb/wai WAI family of packages>
-- for imports of "Control.Reaper".
module Control.Reaper (
-- * Example: Regularly cleaning a cache
-- $example1
-- * Settings
ReaperSettings
, defaultReaperSettings
-- * Accessors
, reaperAction
, reaperDelay
, reaperCons
, reaperNull
, reaperEmpty
-- * Type
, Reaper(..)
-- * Creation
, mkReaper
-- * Helper
, mkListAction
) where
import Control.AutoUpdate.Util (atomicModifyIORef')
import Control.Concurrent (forkIO, threadDelay, killThread, ThreadId)
import Control.Exception (mask_)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
-- | Settings for creating a reaper. This type has two parameters:
-- @workload@ gives the entire workload, whereas @item@ gives an
-- individual piece of the queue. A common approach is to have @workload@
-- be a list of @item@s. This is encouraged by 'defaultReaperSettings' and
-- 'mkListAction'.
--
-- @since 0.1.1
data ReaperSettings workload item = ReaperSettings
{ reaperAction :: workload -> IO (workload -> workload)
-- ^ The action to perform on a workload. The result of this is a
-- \"workload modifying\" function. In the common case of using lists,
-- the result should be a difference list that prepends the remaining
-- workload to the temporary workload. For help with setting up such
-- an action, see 'mkListAction'.
--
-- Default: do nothing with the workload, and then prepend it to the
-- temporary workload. This is incredibly useless; you should
-- definitely override this default.
--
-- @since 0.1.1
, reaperDelay :: {-# UNPACK #-} !Int
-- ^ Number of microseconds to delay between calls of 'reaperAction'.
--
-- Default: 30 seconds.
--
-- @since 0.1.1
, reaperCons :: item -> workload -> workload
-- ^ Add an item onto a workload.
--
-- Default: list consing.
--
-- @since 0.1.1
, reaperNull :: workload -> Bool
-- ^ Check if a workload is empty, in which case the worker thread
-- will shut down.
--
-- Default: 'null'.
--
-- @since 0.1.1
, reaperEmpty :: workload
-- ^ An empty workload.
--
-- Default: empty list.
--
-- @since 0.1.1
}
-- | Default @ReaperSettings@ value, biased towards having a list of work
-- items.
--
-- @since 0.1.1
defaultReaperSettings :: ReaperSettings [item] item
defaultReaperSettings = ReaperSettings
{ reaperAction = \wl -> return (wl ++)
, reaperDelay = 30000000
, reaperCons = (:)
, reaperNull = null
, reaperEmpty = []
}
-- | A data structure to hold reaper APIs.
data Reaper workload item = Reaper {
-- | Adding an item to the workload
reaperAdd :: item -> IO ()
-- | Reading workload.
, reaperRead :: IO workload
-- | Stopping the reaper thread if exists.
-- The current workload is returned.
, reaperStop :: IO workload
-- | Killing the reaper thread immediately if exists.
, reaperKill :: IO ()
}
-- | State of reaper.
data State workload = NoReaper -- ^ No reaper thread
| Workload workload -- ^ The current jobs
-- | Create a reaper addition function. This function can be used to add
-- new items to the workload. Spawning of reaper threads will be handled
-- for you automatically.
--
-- @since 0.1.1
mkReaper :: ReaperSettings workload item -> IO (Reaper workload item)
mkReaper settings@ReaperSettings{..} = do
stateRef <- newIORef NoReaper
tidRef <- newIORef Nothing
return Reaper {
reaperAdd = add settings stateRef tidRef
, reaperRead = readRef stateRef
, reaperStop = stop stateRef
, reaperKill = kill tidRef
}
where
readRef stateRef = do
mx <- readIORef stateRef
case mx of
NoReaper -> return reaperEmpty
Workload wl -> return wl
stop stateRef = atomicModifyIORef' stateRef $ \mx ->
case mx of
NoReaper -> (NoReaper, reaperEmpty)
Workload x -> (Workload reaperEmpty, x)
kill tidRef = do
mtid <- readIORef tidRef
case mtid of
Nothing -> return ()
Just tid -> killThread tid
add :: ReaperSettings workload item
-> IORef (State workload) -> IORef (Maybe ThreadId)
-> item -> IO ()
add settings@ReaperSettings{..} stateRef tidRef item =
mask_ $ do
next <- atomicModifyIORef' stateRef cons
next
where
cons NoReaper = let !wl = reaperCons item reaperEmpty
in (Workload wl, spawn settings stateRef tidRef)
cons (Workload wl) = let wl' = reaperCons item wl
in (Workload wl', return ())
spawn :: ReaperSettings workload item
-> IORef (State workload) -> IORef (Maybe ThreadId)
-> IO ()
spawn settings stateRef tidRef = do
tid <- forkIO $ reaper settings stateRef tidRef
writeIORef tidRef $ Just tid
reaper :: ReaperSettings workload item
-> IORef (State workload) -> IORef (Maybe ThreadId)
-> IO ()
reaper settings@ReaperSettings{..} stateRef tidRef = do
threadDelay reaperDelay
-- Getting the current jobs. Push an empty job to the reference.
wl <- atomicModifyIORef' stateRef swapWithEmpty
-- Do the jobs. A function to merge the left jobs and
-- new jobs is returned.
!merge <- reaperAction wl
-- Merging the left jobs and new jobs.
-- If there is no jobs, this thread finishes.
next <- atomicModifyIORef' stateRef (check merge)
next
where
swapWithEmpty NoReaper = error "Control.Reaper.reaper: unexpected NoReaper (1)"
swapWithEmpty (Workload wl) = (Workload reaperEmpty, wl)
check _ NoReaper = error "Control.Reaper.reaper: unexpected NoReaper (2)"
check merge (Workload wl)
-- If there is no job, reaper is terminated.
| reaperNull wl' = (NoReaper, writeIORef tidRef Nothing)
-- If there are jobs, carry them out.
| otherwise = (Workload wl', reaper settings stateRef tidRef)
where
wl' = merge wl
-- | A helper function for creating 'reaperAction' functions. You would
-- provide this function with a function to process a single work item and
-- return either a new work item, or @Nothing@ if the work item is
-- expired.
--
-- @since 0.1.1
mkListAction :: (item -> IO (Maybe item'))
-> [item]
-> IO ([item'] -> [item'])
mkListAction f =
go id
where
go !front [] = return front
go !front (x:xs) = do
my <- f x
let front' =
case my of
Nothing -> front
Just y -> front . (y:)
go front' xs
-- $example1
-- In this example code, we use a 'Data.Map.Strict.Map' to cache fibonacci numbers, and a 'Reaper' to prune the cache.
--
-- The @main@ function first creates a 'Reaper', with fields to initialize the
-- cache ('reaperEmpty'), add items to it ('reaperCons'), and prune it ('reaperAction').
-- The reaper will run every two seconds ('reaperDelay'), but will stop running while
-- 'reaperNull' is true.
--
-- @main@ then loops infinitely ('Control.Monad.forever'). Each second it calculates the fibonacci number
-- for a value between 30 and 34, first trying the cache ('reaperRead' and 'Data.Map.Strict.lookup'),
-- then falling back to manually calculating it (@fib@)
-- and updating the cache with the result ('reaperAdd')
--
-- @clean@ simply removes items cached for more than 10 seconds.
-- This function is where you would perform IO-related cleanup,
-- like killing threads or closing connections, if that was the purpose of your reaper.
--
-- @
-- module Main where
--
-- import "Data.Time" (UTCTime, getCurrentTime, diffUTCTime)
-- import "Control.Reaper"
-- import "Control.Concurrent" (threadDelay)
-- import "Data.Map.Strict" (Map)
-- import qualified "Data.Map.Strict" as Map
-- import "Control.Monad" (forever)
-- import "System.Random" (getStdRandom, randomR)
--
-- fib :: 'Int' -> 'Int'
-- fib 0 = 0
-- fib 1 = 1
-- fib n = fib (n-1) + fib (n-2)
--
-- type Cache = 'Data.Map.Strict.Map' 'Int' ('Int', 'Data.Time.Clock.UTCTime')
--
-- main :: IO ()
-- main = do
-- reaper <- 'mkReaper' 'defaultReaperSettings'
-- { 'reaperEmpty' = Map.'Data.Map.Strict.empty'
-- , 'reaperCons' = \\(k, v, time) workload -> Map.'Data.Map.Strict.insert' k (v, time) workload
-- , 'reaperAction' = clean
-- , 'reaperDelay' = 1000000 * 2 -- Clean every 2 seconds
-- , 'reaperNull' = Map.'Data.Map.Strict.null'
-- }
-- forever $ do
-- fibArg <- 'System.Random.getStdRandom' ('System.Random.randomR' (30,34))
-- cache <- 'reaperRead' reaper
-- let cachedResult = Map.'Data.Map.Strict.lookup' fibArg cache
-- case cachedResult of
-- 'Just' (fibResult, _createdAt) -> 'putStrLn' $ "Found in cache: `fib " ++ 'show' fibArg ++ "` " ++ 'show' fibResult
-- 'Nothing' -> do
-- let fibResult = fib fibArg
-- 'putStrLn' $ "Calculating `fib " ++ 'show' fibArg ++ "` " ++ 'show' fibResult
-- time <- 'Data.Time.Clock.getCurrentTime'
-- ('reaperAdd' reaper) (fibArg, fibResult, time)
-- 'threadDelay' 1000000 -- 1 second
--
-- -- Remove items > 10 seconds old
-- clean :: Cache -> IO (Cache -> Cache)
-- clean oldMap = do
-- currentTime <- 'Data.Time.Clock.getCurrentTime'
-- let pruned = Map.'Data.Map.Strict.filter' (\\(_, createdAt) -> currentTime \`diffUTCTime\` createdAt < 10.0) oldMap
-- return (\\newData -> Map.'Data.Map.Strict.union' pruned newData)
-- @
| tolysz/wai | auto-update/Control/Reaper.hs | mit | 10,059 | 0 | 16 | 2,456 | 1,369 | 770 | 599 | 106 | 4 |
import Control.Applicative
import Text.Parsec
import Text.Parsec.String (Parser)
import Text.Parsec.Language (haskellStyle)
import qualified Text.Parsec.Token as Tok
data Expr = Add String String deriving Show
lexer :: Tok.TokenParser ()
lexer = Tok.makeTokenParser style
where ops = ["->","\\","+","*","-","="]
style = haskellStyle {Tok.reservedOpNames = ops }
identifier :: Parser String
identifier = Tok.identifier lexer
parseM :: Parser Expr
parseM = do
a <- identifier
char '+'
b <- identifier
return $ Add a b
parseA :: Parser Expr
parseA = Add <$> identifier <* char '+' <*> identifier
main :: IO ()
main = do
s0 <- getLine
print $ parse parseM "<stdin>" s0
s1 <- getLine
print $ parse parseA "<stdin>" s1
| riwsky/wiwinwlh | src/parsec_applicative.hs | mit | 747 | 0 | 8 | 143 | 266 | 140 | 126 | 26 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE QuasiQuotes #-}
module Graphics.Urho3D.Resource.Cache(
ResourceCache
, resourceCacheContext
, priorityLast
, cacheAddResourceDir
, cacheGetResource
) where
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Cpp as C
import Graphics.Urho3D.Resource.Internal.Cache
import Graphics.Urho3D.Resource.Resource
import Graphics.Urho3D.Core.Object
import Graphics.Urho3D.Core.Context
import Graphics.Urho3D.Creatable
import Graphics.Urho3D.Math.StringHash
import Graphics.Urho3D.Monad
import Data.Monoid
import Data.Proxy
import Foreign
import Foreign.C.String
C.context (C.cppCtx <> resourceCacheCntx <> contextContext <> resourceContext <> objectContext)
C.include "<Urho3D/Resource/ResourceCache.h>"
C.using "namespace Urho3D"
resourceCacheContext :: C.Context
resourceCacheContext = resourceCacheCntx <> resourceContext <> objectContext
newResourceCache :: Ptr Context -> IO (Ptr ResourceCache)
newResourceCache ptr = [C.exp| ResourceCache* { new ResourceCache( $(Context* ptr) ) } |]
deleteResourceCache :: Ptr ResourceCache -> IO ()
deleteResourceCache ptr = [C.exp| void { delete $(ResourceCache* ptr) } |]
instance Creatable (Ptr ResourceCache) where
type CreationOptions (Ptr ResourceCache) = Ptr Context
newObject = liftIO . newResourceCache
deleteObject = liftIO . deleteResourceCache
instance Subsystem ResourceCache where
getSubsystemImpl ptr = [C.exp| ResourceCache* { $(Object* ptr)->GetSubsystem<ResourceCache>() } |]
-- | Default periority for resource cache
priorityLast :: Word
priorityLast = fromIntegral [C.pure| unsigned int { PRIORITY_LAST } |]
-- | Add a resource load directory. Optional priority parameter which will control search order.
cacheAddResourceDir :: forall a m ptr . (Parent ResourceCache a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to ResourceCache or acenstor
-> FilePath -- ^ Path to directory
-> Word -- ^ Priority (default is priorityLast)
-> m Bool
cacheAddResourceDir ptr pathName priority = liftIO $ withCString pathName $ \pathName' -> do
let ptr' = parentPointer ptr
priority' = fromIntegral priority
toBool <$> [C.exp| int { (int)$(ResourceCache* ptr')->AddResourceDir(String($(const char* pathName')), $(unsigned int priority')) } |]
-- | Loading a resource by name
cacheGetResource :: forall a b m ptr . (Parent ResourceCache a, Pointer ptr a, ResourceType b, MonadIO m)
=> ptr -- ^ Pointer to ResourceCache or acenstor
-> String -- ^ Resource name
-> Bool -- ^ send event on failure?
-> m (Maybe (Ptr b)) -- ^ pointer to resource
cacheGetResource ptr name sendEvent = liftIO $ withCString name $ \name' -> do
let ptr' = parentPointer ptr
rest = fromIntegral . stringHashValue $ resourceType (Proxy :: Proxy b)
sendEvent' = if sendEvent then 1 else 0
resPtr <- [C.exp| Resource* { $(ResourceCache* ptr')->GetResource(StringHash($(unsigned int rest)), String($(const char* name')), $(int sendEvent') != 0) } |]
checkNullPtr' resPtr (return.castPtr)
| Teaspot-Studio/Urho3D-Haskell | src/Graphics/Urho3D/Resource/Cache.hs | mit | 3,048 | 0 | 15 | 460 | 633 | 359 | 274 | -1 | -1 |
module Server.Swagger where
import API
import Servant.Swagger
import Data.Swagger
import Servant
swaggerServer :: Handler Swagger
swaggerServer = return (toSwagger basicApi)
| lierdakil/markco | server/src/Server/Swagger.hs | mit | 176 | 0 | 7 | 22 | 44 | 25 | 19 | 7 | 1 |
{-#LANGUAGE FlexibleContexts #-}
{-#LANGUAGE FlexibleInstances #-}
{-#LANGUAGE OverloadedStrings #-}
{-#LANGUAGE TupleSections #-}
{-#LANGUAGE TypeSynonymInstances #-}
{-#LANGUAGE MultiParamTypeClasses #-}
{-#LANGUAGE ScopedTypeVariables #-}
module Text.Ginger.Run.FuncUtils
where
import Prelude ( (.), ($), (==), (/=)
, (>), (<), (>=), (<=)
, (+), (-), (*), (/), div, (**), (^)
, (||), (&&)
, (++)
, Show, show
, undefined, otherwise
, Maybe (..)
, Bool (..)
, Int, Integer, String
, fromIntegral, floor, round
, not
, show
, uncurry
, seq
, fst, snd
, maybe
, Either (..)
, id
)
import qualified Prelude
import Data.Maybe (fromMaybe, isJust)
import qualified Data.List as List
import Text.Ginger.AST
import Text.Ginger.Html
import Text.Ginger.GVal
import Text.Ginger.Run.Type
import Text.Printf
import Text.PrintfA
import Data.Scientific (formatScientific)
import Data.Text (Text)
import Data.String (fromString)
import qualified Data.Text as Text
import qualified Data.ByteString.UTF8 as UTF8
import Control.Monad
import Control.Monad.Identity
import Control.Monad.Writer
import Control.Monad.Reader
import Control.Monad.State
import Control.Applicative
import qualified Data.HashMap.Strict as HashMap
import Data.HashMap.Strict (HashMap)
import Data.Scientific (Scientific)
import Data.Scientific as Scientific
import Data.Default (def)
import Safe (readMay, lastDef, headMay)
import Network.HTTP.Types (urlEncode)
import Debug.Trace (trace)
import Data.Maybe (isNothing)
import Data.List (lookup, zipWith, unzip)
unaryFunc :: forall m h p. (Monad m) => (GVal (Run p m h) -> GVal (Run p m h)) -> Function (Run p m h)
unaryFunc f [] = do
warn $ ArgumentsError Nothing "expected exactly one argument (zero given)"
return def
unaryFunc f ((_, x):[]) =
return (f x)
unaryFunc f ((_, x):_) = do
warn $ ArgumentsError Nothing "expected exactly one argument (more given)"
return (f x)
binaryFunc :: forall m h p. (Monad m) => (GVal (Run p m h) -> GVal (Run p m h) -> GVal (Run p m h)) -> Function (Run p m h)
binaryFunc f [] = do
warn $ ArgumentsError Nothing "expected exactly two arguments (zero given)"
return def
binaryFunc f (_:[]) = do
warn $ ArgumentsError Nothing "expected exactly two arguments (one given)"
return def
binaryFunc f ((_, x):(_, y):[]) =
return (f x y)
binaryFunc f ((_, x):(_, y):_) = do
warn $ ArgumentsError Nothing "expected exactly two arguments (more given)"
return (f x y)
ignoreArgNames :: ([a] -> b) -> ([(c, a)] -> b)
ignoreArgNames f args = f (Prelude.map snd args)
variadicNumericFunc :: Monad m => Scientific -> ([Scientific] -> Scientific) -> [(Maybe Text, GVal (Run p m h))] -> Run p m h (GVal (Run p m h))
variadicNumericFunc zero f args =
return . toGVal . f $ args'
where
args' :: [Scientific]
args' = Prelude.map (fromMaybe zero . asNumber . snd) args
unaryNumericFunc :: Monad m => Scientific -> (Scientific -> Scientific) -> [(Maybe Text, GVal (Run p m h))] -> Run p m h (GVal (Run p m h))
unaryNumericFunc zero f args =
return . toGVal . f $ args'
where
args' :: Scientific
args' = case args of
[] -> 0
(arg:_) -> fromMaybe zero . asNumber . snd $ arg
variadicStringFunc :: Monad m => ([Text] -> Text) -> [(Maybe Text, GVal (Run p m h))] -> Run p m h (GVal (Run p m h))
variadicStringFunc f args =
return . toGVal . f $ args'
where
args' :: [Text]
args' = Prelude.map (asText . snd) args
-- | Match args according to a given arg spec, Python style.
-- The return value is a triple of @(matched, args, kwargs, unmatchedNames)@,
-- where @matches@ is a hash map of named captured arguments, args is a list of
-- remaining unmatched positional arguments, kwargs is a list of remaining
-- unmatched named arguments, and @unmatchedNames@ contains the argument names
-- that haven't been matched.
extractArgs :: [Text] -> [(Maybe Text, a)] -> (HashMap Text a, [a], HashMap Text a, [Text])
extractArgs argNames args =
let (matchedPositional, argNames', args') = matchPositionalArgs argNames args
(matchedKeyword, argNames'', args'') = matchKeywordArgs argNames' args'
unmatchedPositional = [ a | (Nothing, a) <- args'' ]
unmatchedKeyword = HashMap.fromList [ (k, v) | (Just k, v) <- args'' ]
in ( HashMap.fromList (matchedPositional ++ matchedKeyword)
, unmatchedPositional
, unmatchedKeyword
, argNames''
)
where
matchPositionalArgs :: [Text] -> [(Maybe Text, a)] -> ([(Text, a)], [Text], [(Maybe Text, a)])
matchPositionalArgs [] args = ([], [], args)
matchPositionalArgs names [] = ([], names, [])
matchPositionalArgs names@(n:ns) allArgs@((anm, arg):args)
| Just n == anm || isNothing anm =
let (matched, ns', args') = matchPositionalArgs ns args
in ((n, arg):matched, ns', args')
| otherwise = ([], names, allArgs)
matchKeywordArgs :: [Text] -> [(Maybe Text, a)] -> ([(Text, a)], [Text], [(Maybe Text, a)])
matchKeywordArgs [] args = ([], [], args)
matchKeywordArgs names allArgs@((Nothing, arg):args) =
let (matched, ns', args') = matchKeywordArgs names args
in (matched, ns', (Nothing, arg):args')
matchKeywordArgs names@(n:ns) args =
case (lookup (Just n) args) of
Nothing ->
let (matched, ns', args') = matchKeywordArgs ns args
in (matched, n:ns', args')
Just v ->
let args' = [ (k,v) | (k,v) <- args, k /= Just n ]
(matched, ns', args'') = matchKeywordArgs ns args'
in ((n,v):matched, ns', args'')
-- | Parse argument list into type-safe argument structure.
extractArgsT :: ([Maybe a] -> b) -> [Text] -> [(Maybe Text, a)] -> Either ([a], HashMap Text a, [Text]) b
extractArgsT f argNames args =
let (matchedMap, freeArgs, freeKwargs, unmatched) = extractArgs argNames args
in if List.null freeArgs && HashMap.null freeKwargs
then Right (f $ fmap (\name -> HashMap.lookup name matchedMap) argNames)
else Left (freeArgs, freeKwargs, unmatched)
-- | Parse argument list into flat list of matched arguments.
extractArgsL :: [Text] -> [(Maybe Text, a)] -> Either ([a], HashMap Text a, [Text]) [Maybe a]
extractArgsL = extractArgsT id
extractArgsDefL :: [(Text, a)] -> [(Maybe Text, a)] -> Either ([a], HashMap Text a, [Text]) [a]
extractArgsDefL argSpec args =
let (names, defs) = unzip argSpec
in injectDefaults defs <$> extractArgsL names args
injectDefaults :: [a] -> [Maybe a] -> [a]
injectDefaults = zipWith fromMaybe
| tdammers/ginger | src/Text/Ginger/Run/FuncUtils.hs | mit | 7,011 | 2 | 17 | 1,807 | 2,513 | 1,411 | 1,102 | 143 | 6 |
module Day3Spec (main, spec) where
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
import Test.QuickCheck.Property
import Test.QuickCheck.Modifiers
import Test.Hspec
import Day3
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "When Santa is alone" $ do
it "visits only one house for one instruction" $ do
santaHouses ">" `shouldBe` 2
it "visits houses from a file" $ do
contents <- readFile "test/input-day3.txt"
santaHouses contents `shouldBe` 2081
describe "When the Robot and Santa are working together" $ do
it "visits one house each for two diff instructions" $ do
combinedHouses "><" `shouldBe` 3
it "they visit their same houses but counts it once" $ do
combinedHouses "^vv^" `shouldBe` 3
it "they both visit the same house but counts it only once" $ do
combinedHouses "^>>^" `shouldBe` 4
it "visits 5 houses each" $ do
combinedHouses "^v^v^v^v^v" `shouldBe` 11
it "visits naughty houses" $ do
combinedHouses ">>v^" `shouldBe` 4
it "Visits houses form a file" $ do
contents <- readFile "test/input-day3.txt"
combinedHouses contents `shouldBe` 2341
| AndrewSinclair/aoc-haskell | test/Day3Spec.hs | mit | 1,203 | 0 | 14 | 277 | 292 | 142 | 150 | 32 | 1 |
module Optimization where
import Numeric.LinearAlgebra
class Optimize a where
--optimizeInit :: a -> Double -> Double -> (Int, Int) -> a
paramUpdate :: a -> a
data SGD = SGD {
sgdLearningRate :: Double,
sgdDecay :: Double,
sgdMomentum :: Double,
sgdParams :: [Matrix R],
sgdGparams :: [Matrix R],
sgdDeltaPre :: [Matrix R],
sgdBatchSize :: Double
}
instance Optimize SGD where
paramUpdate sgd =
let learningRate = sgdLearningRate sgd in
let decay = sgdDecay sgd in
let momentum = sgdMomentum sgd in
let params = sgdParams sgd in
let gparams = sgdGparams sgd in
let deltaPre = sgdDeltaPre sgd in
let batchSize = sgdBatchSize sgd in
let _sgd (px:pxs) (gx: gxs) (dx:dxs) paUpdate deUpdate gaZeros =
let r = rows gx in
let c = cols gx in
let lrMat = (r >< c) [learningRate..]:: (Matrix R) in
let batchSizeMat = (r >< c) [batchSize..] :: (Matrix R) in
let momMat = (r >< c) [momentum..] :: (Matrix R) in
let gUp = gx * lrMat / batchSizeMat in
let ugd = momMat * dx - gx in
let pu = px + ugd in _sgd pxs gxs dxs (paUpdate++[pu]) (deUpdate++[ugd]) (gaZeros++[(r >< c) [0..]])
_sgd [] [] [] paUpdate deUpdate gaZeros = SGD {
sgdLearningRate=learningRate,
sgdDecay=decay,
sgdMomentum=momentum,
sgdParams=paUpdate,
sgdGparams=gaZeros,
sgdDeltaPre=deUpdate,
sgdBatchSize=0
} in
_sgd params gparams deltaPre [] [] []
data Adadelta = Adadelta {
adaDecay :: Double,
adaEpsilon :: Double,
adaBatchSize :: Double,
adaParams :: [Matrix R],
adaGparams :: [Matrix R],
adaAccGrad :: [Matrix R],
adaAccDelta :: [Matrix R]
}
instance Optimize Adadelta where
paramUpdate ada =
let decay = adaDecay ada in
let epsilon = adaEpsilon ada in
let batchSize = adaBatchSize ada in
let params = adaParams ada in
let gparams = adaGparams ada in
let accGrad = adaAccGrad ada in
let accDelta = adaAccDelta ada in
let _ada (px:pxs) (gx:gxs) (accgx:accgxs) (accdx:accdxs) paUpdate gradUpdate deltaUpdate gaZeros =
let r = rows px in
let c = cols px in
let decayMat = (r >< c) [decay ..] :: (Matrix R) in
let epsilonMat = (r >< c) [epsilon ..] :: (Matrix R) in
let batchSizeMat = (r >< c) [batchSize ..] :: (Matrix R) in
let oneMat = (r >< c) [1.0 ..]:: (Matrix R) in
let gUp = accgx / batchSizeMat in
let gradUp = decayMat * accgx + (oneMat - decayMat) * gUp * gUp in
let ugd = (cmap (\x -> -(sqrt x)) (accdx + epsilonMat)) / (cmap (\x -> sqrt x) (accgx + epsilonMat)) * gUp in
let deltaUp = decayMat * accdx + (oneMat - decayMat) * ugd * ugd in
let pu = px + ugd in
_ada pxs gxs accgxs accdxs (pu:paUpdate) (gradUp:gradUpdate) (deltaUp:deltaUpdate) (((r >< c)[0.0 ..]):gaZeros)
_ada [] [] [] [] paUpdate gradUpdate deltaUpdate gaZeros = Adadelta {
adaDecay=decay,
adaEpsilon=epsilon,
adaBatchSize=batchSize,
adaParams=(reverse paUpdate),
adaGparams=(reverse gaZeros),
adaAccGrad=(reverse gradUpdate),
adaAccDelta=(reverse deltaUpdate)
}
in _ada params gparams accGrad accDelta [] [] [] []
| neutronest/vortex | vortex/Optimization.hs | mit | 3,455 | 0 | 52 | 1,085 | 1,347 | 698 | 649 | 78 | 0 |
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
{- |
Module : ./Isabelle/Logic_Isabelle.hs
Description : Isabelle instance of class Logic
Copyright : (c) Till Mossakowski, Uni Bremen 2002-2004
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable (imports Logic)
Instance of class Logic for Isabelle (including Pure, HOL etc.).
-}
module Isabelle.Logic_Isabelle where
import Common.DefaultMorphism
import Common.Id
import Logic.Logic
import Isabelle.ATC_Isabelle ()
import Isabelle.IsaSign
import Isabelle.IsaPrint
import Isabelle.IsaProve
type IsabelleMorphism = DefaultMorphism Sign
{- a dummy datatype for the LogicGraph and for identifying the right
instances -}
data Isabelle = Isabelle deriving Show
instance Language Isabelle where
description _ =
"Isabelle - a generic theorem prover\n" ++
"This logic corresponds to the logic of Isabelle,\n" ++
"a weak intuitionistic type theory\n" ++
"Also, the logics encoded in Isabelle, like FOL, HOL, HOLCF, ZF " ++
"are made available\n" ++
"See http://www.cl.cam.ac.uk/Research/HVG/Isabelle/"
instance Logic.Logic.Syntax Isabelle () () () ()
-- default implementation is fine!
instance GetRange Sentence
instance Sentences Isabelle Sentence Sign IsabelleMorphism () where
map_sen Isabelle _ = return
print_named Isabelle = printNamedSen
-- other default implementations are fine
instance StaticAnalysis Isabelle () Sentence
() ()
Sign
IsabelleMorphism () () where
empty_signature Isabelle = emptySign
is_subsig Isabelle = isSubSign
subsig_inclusion Isabelle = defaultInclusion
instance Logic Isabelle () () Sentence () ()
Sign
IsabelleMorphism () () () where
stability _ = Testing
-- again default implementations are fine
empty_proof_tree _ = ()
provers Isabelle =
[isabelleProver Emacs, isabelleProver JEdit, isabelleBatchProver]
cons_checkers Isabelle = [isabelleConsChecker]
instance LogicalFramework Isabelle () () Sentence () () Sign IsabelleMorphism
() () ()
| gnn/Hets | Isabelle/Logic_Isabelle.hs | gpl-2.0 | 2,250 | 0 | 10 | 485 | 367 | 193 | 174 | 41 | 0 |
module Zepto.Primitives.HashPrimitives where
import Control.Monad.Except
import Data.Map (keys, elems, member, delete, fromList, toList)
import Zepto.Types
hashKVDoc :: String -> String
hashKVDoc name = "get " ++ name ++ " from hashmap <par>hash</par>.\n\
\n\
params:\n\
- hash: the hashmap from which to get the " ++ name ++ "\n\
complexity: O(1)\n\
returns: a list of " ++ name
hashKeys :: [LispVal] -> ThrowsError LispVal
hashKeys [HashMap x] = return $ List $ map SimpleVal (keys x)
hashKeys [x] = throwError $ TypeMismatch "hashmap" x
hashKeys badArgList = throwError $ NumArgs 1 badArgList
hashVals :: [LispVal] -> ThrowsError LispVal
hashVals [HashMap x] = return $ List $ elems x
hashVals [x] = throwError $ TypeMismatch "hashmap" x
hashVals badArgList = throwError $ NumArgs 1 badArgList
inHashDoc :: String
inHashDoc = "check whether an element under the key <par>el</par> is in a\n\
hashmap <par>hash</par>.\n\
\n\
params:\n\
- hash: the hashmap to check\n\
- el: the element to find\n\
complexity: O(1)\n\
returns: boolean"
inHash :: [LispVal] -> ThrowsError LispVal
inHash [HashMap x, SimpleVal e] = return $ fromSimple $ Bool $ member e x
inHash [x, SimpleVal _] = throwError $ TypeMismatch "hashmap" x
inHash [HashMap _, e] = throwError $ TypeMismatch "simple value" e
inHash [x, _] = throwError $ TypeMismatch "hashmap and simple value" x
inHash badArgList = throwError $ NumArgs 2 badArgList
makeHashDoc :: String
makeHashDoc = "create a hashmap from a variety of inputs, from other\n\
hashmaps to pairs of keys and values.\n\
\n\
Example:\n\
<zepto>\n\
(make-hash #{1 2} 3 4 [5 6]) ; => #{1 2, 3 4, 5 6}\n\
(make-hash) ; => #{}\n\
</zepto>\n\
\n\
params:\n\
- args: the arguments to create a hashmap from (varargs)\n\
complexity: O(n)\n\
returns: a hashmap"
makeHash :: [LispVal] -> ThrowsError LispVal
makeHash [List x] = makeHash x
makeHash l = case keyVal l [] of
Right x -> return $ HashMap $ fromList x
Left x -> throwError $ TypeMismatch "simple value/hashmap/list" x
where keyVal [] acc = Right acc
keyVal (List [x, y] : r) acc = keyVal (x : y : r) acc
keyVal (SimpleVal x : y : r) acc = keyVal r $ (x, y) : acc
keyVal (HashMap x : r) acc = keyVal r $ acc ++ toList x
keyVal (x : _) _ = Left x
hashRemoveDoc :: String
hashRemoveDoc = "remove an element under the key <par>el</par> from a hashmap\n\
<par>hash</par>.\n\
\n\
params:\n\
- hash: the hashmap from which to delete <par>el</par>\n\
- el: the element to delete\n\
complexity: O(1)\n\
returns: the hashmap without <par>el</par>"
hashRemove :: [LispVal] -> ThrowsError LispVal
hashRemove [HashMap x, SimpleVal e] = return $ HashMap $ delete e x
hashRemove [x, SimpleVal _] = throwError $ TypeMismatch "hashmap" x
hashRemove [HashMap _, e] = throwError $ TypeMismatch "simple value" e
hashRemove [x, _] = throwError $ TypeMismatch "hashmap and simple value" x
hashRemove badArgList = throwError $ NumArgs 2 badArgList
| zepto-lang/zepto | src/Zepto/Primitives/HashPrimitives.hs | gpl-2.0 | 3,055 | 146 | 15 | 637 | 1,268 | 664 | 604 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings #-}
module Text.Pandoc2.Shared where
import Text.Pandoc2.Definition
import Data.Data
import Data.Bits
import Data.Char
import Data.Monoid
import qualified Data.Text.Encoding as E
import qualified Data.ByteString.Char8 as B8
import Text.Parsec (SourcePos, sourceLine, sourceColumn)
import Data.String
import Data.Text (Text)
import Network.URI ( escapeURIString, isAllowedInURI )
import qualified Data.Text as T
import Data.Generics.Uniplate.Data
data LogLevel = INFO | WARNING | ERROR
deriving (Ord, Eq, Show, Read, Data, Typeable)
data Message = Message LogLevel (Maybe SourcePos) Text
instance Show Message where
show (Message level pos t) = show level ++ " " ++ T.unpack t ++
showSourcePos pos
where showSourcePos Nothing = ""
showSourcePos (Just p) = " (line " ++
show (sourceLine p) ++ " col " ++
show (sourceColumn p) ++ ")"
data PExtension = Footnotes
| TeX_math
| Delimited_code_blocks
| Markdown_in_HTML_blocks
| Fancy_lists
| Definition_lists
| Header_identifiers
| All_symbols_escapable
| Intraword_underscores
| Blank_before_blockquote
| Blank_before_header
| Significant_bullets
deriving (Show, Read, Data, Typeable, Enum, Eq)
newtype PExtensions = PExtensions { unPExtensions :: Integer }
noExtensions :: PExtensions
noExtensions = PExtensions 0
allExtensions :: PExtensions
allExtensions = PExtensions $ complement 0
setExtensions :: [PExtension] -> PExtensions
setExtensions =
foldl (\(PExtensions x) e -> PExtensions (setBit x $ fromEnum e))
noExtensions
isEnabled :: PExtension -> PExtensions -> Bool
isEnabled ext opts =
testBit (unPExtensions opts) (fromEnum ext)
isDisabled :: PExtension -> PExtensions -> Bool
isDisabled ext opts = not (isEnabled ext opts)
data HTMLMathMethod = PlainMath
| MathML
| TeXMath
deriving (Show, Read, Eq, Data, Typeable)
data POptions =
POptions { optLogLevel :: LogLevel
, optTabStop :: Int
, optExtensions :: PExtensions
, optSmart :: Bool -- ^ Enable smart typography
, optMathMethod :: HTMLMathMethod
, optCompact :: Bool -- ^ Avoid insignificant whitespace
}
-- | Default parser options.
poptions :: POptions
poptions = POptions { optLogLevel = WARNING
, optTabStop = 4
, optExtensions = noExtensions
, optSmart = False
, optMathMethod = TeXMath
, optCompact = False
}
-- | Concatenate and trim inlines.
toInlines :: [Inlines] -> Inlines
toInlines = trimInlines . mconcat
-- | Remove links from 'Inlines'.
delink :: Inlines -> Inlines
delink = mapItems go
where go (Link (Label lab) _) = lab
go x = single x
-- | Escape a URI, converting to UTF-8 octets, then URI encoding them.
escapeURI :: Text -> Text
escapeURI = T.pack . escapeURIString isAllowedInURI .
B8.unpack . E.encodeUtf8
-- | Version of 'show' that works for any 'IsString' instance.
show' :: (Show a, IsString b) => a -> b
show' = fromString . show
-- | Convert inlines to plain text.
textify :: Inlines -> Text
textify = T.concat . map extractText . universeBi
where extractText :: Inline -> Text
extractText (Txt t) = t
extractText (Verbatim _ t) = t
extractText (Math _ t) = t
extractText (Quoted DoubleQuoted ils) = "\"" <> textify ils <> "\""
extractText (Quoted SingleQuoted ils) = "'" <> textify ils <> "'"
extractText Sp = T.singleton ' '
extractText LineBreak = T.singleton ' '
extractText _ = mempty
inlinesToIdentifier :: Inlines -> Text
inlinesToIdentifier = T.dropWhile (not . isAlpha)
. T.intercalate "-"
. T.words
. T.map (nbspToSp . toLower)
. T.filter (\c -> isLetter c || isDigit c || c `elem` "_-. ")
. textify
where nbspToSp '\160' = ' '
nbspToSp x = x
fromRoman :: Text -> Maybe (Int, ListNumberStyle)
fromRoman t =
case go "M" (map toUpper t') of
Nothing -> Nothing
Just n -> Just (n, sty)
where t' = T.unpack t
sty = case t' of
(c:_) | isLower c -> LowerRoman
_ -> UpperRoman
go :: Text -> String -> Maybe Int
go "M" ('M':xs) = fmap (+ 1000) $ go "M" xs
go "M" xs = go "CM" xs
go "CM" ('C':'M':xs) = fmap (+ 900) $ go "C" xs
go "CM" xs = go "D" xs
go "D" ('D':xs) = fmap (+ 500) $ go "D" xs
go "D" xs = go "CD" xs
go "CD" ('C':'D':xs) = fmap (+ 400) $ go "XC" xs
go "CD" xs = go "C" xs
go "C" ('C':xs) = fmap (+ 100) $ go "C" xs
go "C" xs = go "XC" xs
go "XC" ('X':'C':xs) = fmap (+ 90) $ go "X" xs
go "XC" xs = go "L" xs
go "L" ('L':xs) = fmap (+ 50) $ go "L" xs
go "L" xs = go "XL" xs
go "XL" ('X':'L':xs) = fmap (+ 40) $ go "V" xs
go "XL" xs = go "X" xs
go "X" ('X':xs) = fmap (+ 10) $ go "X" xs
go "X" xs = go "IX" xs
go "IX" ('I':'X':xs) = fmap (+ 9) $ go "V" xs
go "IX" xs = go "V" xs
go "V" ('V':xs) = fmap (+ 5) $ go "V" xs
go "V" xs = go "IV" xs
go "IV" ('I':'V':_) = Just 4
go "IV" xs = go "I" xs
go "I" ('I':xs) = fmap (+ 1) $ go "I" xs
go "I" [] = Just 0
go _ _ = Nothing
| jgm/pandoc2 | Text/Pandoc2/Shared.hs | gpl-2.0 | 5,933 | 0 | 14 | 2,085 | 1,858 | 981 | 877 | 138 | 29 |
module HEP.Automation.MadGraph.Dataset.Set20110516set4 where
import HEP.Storage.WebDAV
import HEP.Automation.MadGraph.Model
import HEP.Automation.MadGraph.Machine
import HEP.Automation.MadGraph.UserCut
import HEP.Automation.MadGraph.SetupType
import HEP.Automation.MadGraph.Model.ZpHFull
import HEP.Automation.MadGraph.Dataset.Common
import HEP.Automation.MadGraph.Dataset.Processes
import qualified Data.ByteString as B
psetup_zphfull_TZpLep :: ProcessSetup ZpHFull
psetup_zphfull_TZpLep = PS {
mversion = MadGraph4
, model = ZpHFull
, process = preDefProcess TZpLep
, processBrief = "TZpLep"
, workname = "428ZpH_TZpLep"
}
zpHFullParamSet :: [ModelParam ZpHFull]
zpHFullParamSet = [ ZpHFullParam m g (0.28)
| m <-[150.0]
, g <- [1.00] ]
psetuplist :: [ProcessSetup ZpHFull]
psetuplist = [ psetup_zphfull_TZpLep ]
sets :: [Int]
sets = [1,2..20]
zptasklist :: ScriptSetup -> ClusterSetup ZpHFull -> [WorkSetup ZpHFull]
zptasklist ssetup csetup =
[ WS ssetup (psetup_zphfull_TZpLep)
(RS { param = p
, numevent = 10000
, machine = TeVatron
, rgrun = Fixed
, rgscale = 200.0
, match = NoMatch
, cut = DefCut
, pythia = RunPYTHIA
, usercut = NoUserCutDef
, pgs = RunPGSNoTau
, setnum = num
})
csetup
(WebDAVRemoteDir "mc/TeVatronFor3/ZpHFull0516Big")
| p <- zpHFullParamSet , num <- sets ]
totaltasklistEvery :: Int -> Int -> ScriptSetup -> ClusterSetup ZpHFull -> [WorkSetup ZpHFull]
totaltasklistEvery n r ssetup csetup =
let lst = zip [1..] (zptasklist ssetup csetup)
in map snd . filter (\(x,_)-> x `mod` n == r) $ lst
| wavewave/madgraph-auto-dataset | src/HEP/Automation/MadGraph/Dataset/Set20110516set4.hs | gpl-3.0 | 1,785 | 0 | 13 | 468 | 465 | 275 | 190 | 46 | 1 |
{-# LANGUAGE RecordWildCards #-}
module Sara.Parser.PrettyPrinter (
Pretty
, pretty
, prettyRender) where
import qualified Sara.Parser.Keywords as K
import Text.PrettyPrint
import Sara.Ast.Types
import Sara.Ast.Operators
import Sara.Ast.Syntax as S
prettyRender :: Pretty a => a -> String
prettyRender = render . pretty
class Pretty a where
pretty :: a -> Doc
instance Pretty (Program a b c d) where
pretty = prettyProgram
instance Pretty (Signature a b c d) where
pretty = prettySignature
instance Pretty (TypedVariable b d) where
pretty = prettyTypedVariable
instance Pretty Type where
pretty = prettyType
instance Pretty (Expression a b c d) where
pretty = prettyExpression
prettyProgram :: Program a b c d -> Doc
prettyProgram = vsep . punctuate semi . map prettyDeclaration . program
indentation :: Int
indentation = 2
vsep :: [Doc] -> Doc
vsep = foldl ($+$) empty
prettyDeclaration :: Declaration a b c d -> Doc
prettyDeclaration (Function sig body _) = prettyFunction sig body
prettyDeclaration (Extern sig _) = keyword K.Extern <+> prettySignature sig
prettyFunction :: Signature a b c d -> Expression a b c d -> Doc
prettyFunction sig body = prettySignature sig $+$ inBlock (prettyExpression body)
prettySignature :: Signature a b c d -> Doc
prettySignature Signature{..} = prettyTyped sig retType
$+$ conditions K.Requires preconditions
$+$ conditions K.Ensures postconditions
where sig = keyword word <+> text sigName
<> (parens . hsep . punctuate comma . map prettyTypedVariable) args
word = if isPure then K.Function else K.Method
conditions :: K.Keyword -> [Expression a b c d] -> Doc
conditions word conds = nest (2 * indentation) $ vsep $ punctuate semi $ map toCond $ conds
where toCond cond = keyword word <+> prettyExpression cond
prettyTyped :: Doc -> Type -> Doc
prettyTyped doc typ = doc
<> colon
<+> prettyType typ
prettyTypedVariable :: TypedVariable b d -> Doc
prettyTypedVariable TypedVariable{..} = prettyTyped (text varName) varType
prettyType :: Type -> Doc
prettyType = text . show
-- TODO types
prettyExpression :: Expression a b c d -> Doc
prettyExpression exp = prettyUntypedExpression exp
prettyBinaryTerm :: Expression a b c d -> Doc
prettyBinaryTerm exp = prettyUntypedBinaryTerm exp
prettyTerm :: Expression a b c d -> Doc
prettyTerm exp = prettyUntypedTerm exp
prettyUntypedBinaryTerm :: Expression a b c d -> Doc
prettyUntypedBinaryTerm exp = case exp of
BinaryOperation{} -> parens $ prettyUntypedExpression exp
Conditional{} -> parens $ prettyUntypedExpression exp
_ -> prettyUntypedExpression exp
prettyUntypedTerm :: Expression a b c d -> Doc
prettyUntypedTerm exp = case exp of
UnaryOperation{} -> parens $ prettyExpression exp
_ -> prettyBinaryTerm exp
prettyUntypedExpression :: Expression a b c d -> Doc
prettyUntypedExpression S.Unit{} = text "()"
prettyUntypedExpression (S.Boolean True _ _) = keyword K.True
prettyUntypedExpression (S.Boolean False _ _) = keyword K.False
prettyUntypedExpression (S.Integer n _ _) = integer n
prettyUntypedExpression (S.Double d _ _) = double d
prettyUntypedExpression (UnaryOperation op exp _ _) = (text . unarySymbol $ op)
<> prettyTerm exp
prettyUntypedExpression (BinaryOperation op left right _ _) = prettyBinaryTerm left
<+> (text . binarySymbol $ op)
<+> prettyBinaryTerm right
prettyUntypedExpression (Variable var _ _ _) = text var
prettyUntypedExpression (Call name args _ _ _) = text name
<> (parens . hsep . punctuate comma . map prettyExpression) args
prettyUntypedExpression (Conditional cond ifExp elseExp _ _) = keyword K.If
<+> prettyExpression cond
<+> keyword K.Then
<+> prettyExpression ifExp
<+> keyword K.Else
<+> prettyExpression elseExp
prettyUntypedExpression (Block [] S.Unit{} _ _) = text "{}" -- This special case is necessary to make the pretty printer the inverse of the parser.
prettyUntypedExpression (Block stmts exp _ _) = inBlock (vsep . punctuate semi . map prettyExpression $ stmts ++ [exp])
prettyUntypedExpression (While invs cond body _ _) = keyword K.While <+> parens (prettyExpression cond)
$+$ conditions K.Invariant invs
$+$ inBlock (prettyExpression body)
prettyUntypedExpression (Assertion kind exp _ _) = assertKeyword kind <+> prettyExpression exp
prettyUntypedExpression (VarDef tVar isVal exp _ _) = keyword word <+> prettyTypedVariable tVar <+> equals <+> prettyExpression exp
where word = if isVal then K.Val else K.Var
assertKeyword :: AssertionKind -> Doc
assertKeyword Assert = keyword K.Assert
assertKeyword Assume = keyword K.Assume
assertKeyword AssertAndCollapse = keyword K.AssertAndCollapse
inBlock :: Doc -> Doc
inBlock doc = text "{" $+$ nest indentation doc $+$ text "}"
keyword :: K.Keyword -> Doc
keyword = text . K.keyword
| Lykos/Sara | src/lib/Sara/Parser/PrettyPrinter.hs | gpl-3.0 | 5,810 | 0 | 12 | 1,842 | 1,627 | 808 | 819 | 104 | 3 |
{-# LANGUAGE
FlexibleInstances
#-}
-- | parse profile file generated by @+RTS -p@
module GHC.ProfileAnalyzer.ParseProfile
( -- * function
readProfile
)
where
import Control.Applicative ((<*), (*>))
import Control.Monad
import Data.Char
import Data.List (sortBy)
import Data.Monoid
import Data.Ord
import Text.Parsec
import Text.Parsec.String
import Text.Parsec.Token
import Text.Parsec.Language (haskellDef)
import Text.Printf
import System.Environment (getArgs)
import GHC.ProfileAnalyzer.Types
-- | Token require laguage-driven token generator
lexer = makeTokenParser haskellDef
main = do
args <- getArgs
res <- parseFromFile header $ if null args then "sih4-prof.prof" else head args
case res of
Left err -> print err
Right (title, cmd, totalTime, totalAlloc, ls) -> print (title, cmd, totalTime, ls)
readProfile :: String -> IO (Maybe RunProfile)
readProfile file = do
res <- parseFromFile header file
case res of
Left err -> return Nothing
Right (_, cmd, tTime, tHeap, ls) -> return $ Just (RunProfile (mempty { elapsedTime = tTime, usedHeap = tHeap }) (canonizeCostCenterStats ls))
header = do
title <- readLine <* skipLine
cmd <- readLine <* skipLine
tTime <- pTotalTime
tHeap <- liftM fromIntegral pTotalAlloc
count 3 skipLine
l <- statLine `manyTill` (try (string "individual inherited\n"))
return (title, cmd, tTime, tHeap, map (\(CostCenterStat n t h) -> CostCenterStat n (0.01 * t * tTime) (0.01 * h * tHeap)) l)
skipLine = optional (many1 (noneOf "\n")) >> newline
readLine = optional spaces *> many1 (noneOf "\n") <* newline
pTotalTime = do
optional spaces
string "total time" >> spaces >> string "=" >> spaces
float lexer <* readLine
pTotalAlloc = do
optional spaces
string "total alloc" >> spaces >> string "=" >> spaces
num <- many1 (char ',' <|> digit)
readLine
return ((read . filter isDigit $ num) :: Int)
statLine = do
optional $ many1 (oneOf " \t")
id <- many1 (noneOf " \t\n") <* many1 (oneOf " \t")
pac <- many1 (noneOf " \t\n") <* many1 (oneOf " \t")
time <- float lexer
mem <- float lexer
return $ CostCenterStat (id, pac) time mem
| shnarazk/profileAnalyzer | GHC/ProfileAnalyzer/ParseProfile.hs | gpl-3.0 | 2,211 | 0 | 16 | 473 | 780 | 397 | 383 | 58 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.RegionInstanceGroups.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves the list of instance group resources contained within the
-- specified region.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionInstanceGroups.list@.
module Network.Google.Resource.Compute.RegionInstanceGroups.List
(
-- * REST Resource
RegionInstanceGroupsListResource
-- * Creating a Request
, regionInstanceGroupsList
, RegionInstanceGroupsList
-- * Request Lenses
, riglReturnPartialSuccess
, riglOrderBy
, riglProject
, riglFilter
, riglRegion
, riglPageToken
, riglMaxResults
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.regionInstanceGroups.list@ method which the
-- 'RegionInstanceGroupsList' request conforms to.
type RegionInstanceGroupsListResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"regions" :>
Capture "region" Text :>
"instanceGroups" :>
QueryParam "returnPartialSuccess" Bool :>
QueryParam "orderBy" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] RegionInstanceGroupList
-- | Retrieves the list of instance group resources contained within the
-- specified region.
--
-- /See:/ 'regionInstanceGroupsList' smart constructor.
data RegionInstanceGroupsList =
RegionInstanceGroupsList'
{ _riglReturnPartialSuccess :: !(Maybe Bool)
, _riglOrderBy :: !(Maybe Text)
, _riglProject :: !Text
, _riglFilter :: !(Maybe Text)
, _riglRegion :: !Text
, _riglPageToken :: !(Maybe Text)
, _riglMaxResults :: !(Textual Word32)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RegionInstanceGroupsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'riglReturnPartialSuccess'
--
-- * 'riglOrderBy'
--
-- * 'riglProject'
--
-- * 'riglFilter'
--
-- * 'riglRegion'
--
-- * 'riglPageToken'
--
-- * 'riglMaxResults'
regionInstanceGroupsList
:: Text -- ^ 'riglProject'
-> Text -- ^ 'riglRegion'
-> RegionInstanceGroupsList
regionInstanceGroupsList pRiglProject_ pRiglRegion_ =
RegionInstanceGroupsList'
{ _riglReturnPartialSuccess = Nothing
, _riglOrderBy = Nothing
, _riglProject = pRiglProject_
, _riglFilter = Nothing
, _riglRegion = pRiglRegion_
, _riglPageToken = Nothing
, _riglMaxResults = 500
}
-- | Opt-in for partial success behavior which provides partial results in
-- case of failure. The default value is false.
riglReturnPartialSuccess :: Lens' RegionInstanceGroupsList (Maybe Bool)
riglReturnPartialSuccess
= lens _riglReturnPartialSuccess
(\ s a -> s{_riglReturnPartialSuccess = a})
-- | Sorts list results by a certain order. By default, results are returned
-- in alphanumerical order based on the resource name. You can also sort
-- results in descending order based on the creation timestamp using
-- \`orderBy=\"creationTimestamp desc\"\`. This sorts results based on the
-- \`creationTimestamp\` field in reverse chronological order (newest
-- result first). Use this to sort resources like operations so that the
-- newest operation is returned first. Currently, only sorting by \`name\`
-- or \`creationTimestamp desc\` is supported.
riglOrderBy :: Lens' RegionInstanceGroupsList (Maybe Text)
riglOrderBy
= lens _riglOrderBy (\ s a -> s{_riglOrderBy = a})
-- | Project ID for this request.
riglProject :: Lens' RegionInstanceGroupsList Text
riglProject
= lens _riglProject (\ s a -> s{_riglProject = a})
-- | A filter expression that filters resources listed in the response. The
-- expression must specify the field name, a comparison operator, and the
-- value that you want to use for filtering. The value must be a string, a
-- number, or a boolean. The comparison operator must be either \`=\`,
-- \`!=\`, \`>\`, or \`\<\`. For example, if you are filtering Compute
-- Engine instances, you can exclude instances named \`example-instance\`
-- by specifying \`name != example-instance\`. You can also filter nested
-- fields. For example, you could specify \`scheduling.automaticRestart =
-- false\` to include instances only if they are not scheduled for
-- automatic restarts. You can use filtering on nested fields to filter
-- based on resource labels. To filter on multiple expressions, provide
-- each separate expression within parentheses. For example: \`\`\`
-- (scheduling.automaticRestart = true) (cpuPlatform = \"Intel Skylake\")
-- \`\`\` By default, each expression is an \`AND\` expression. However,
-- you can include \`AND\` and \`OR\` expressions explicitly. For example:
-- \`\`\` (cpuPlatform = \"Intel Skylake\") OR (cpuPlatform = \"Intel
-- Broadwell\") AND (scheduling.automaticRestart = true) \`\`\`
riglFilter :: Lens' RegionInstanceGroupsList (Maybe Text)
riglFilter
= lens _riglFilter (\ s a -> s{_riglFilter = a})
-- | Name of the region scoping this request.
riglRegion :: Lens' RegionInstanceGroupsList Text
riglRegion
= lens _riglRegion (\ s a -> s{_riglRegion = a})
-- | Specifies a page token to use. Set \`pageToken\` to the
-- \`nextPageToken\` returned by a previous list request to get the next
-- page of results.
riglPageToken :: Lens' RegionInstanceGroupsList (Maybe Text)
riglPageToken
= lens _riglPageToken
(\ s a -> s{_riglPageToken = a})
-- | The maximum number of results per page that should be returned. If the
-- number of available results is larger than \`maxResults\`, Compute
-- Engine returns a \`nextPageToken\` that can be used to get the next page
-- of results in subsequent list requests. Acceptable values are \`0\` to
-- \`500\`, inclusive. (Default: \`500\`)
riglMaxResults :: Lens' RegionInstanceGroupsList Word32
riglMaxResults
= lens _riglMaxResults
(\ s a -> s{_riglMaxResults = a})
. _Coerce
instance GoogleRequest RegionInstanceGroupsList where
type Rs RegionInstanceGroupsList =
RegionInstanceGroupList
type Scopes RegionInstanceGroupsList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient RegionInstanceGroupsList'{..}
= go _riglProject _riglRegion
_riglReturnPartialSuccess
_riglOrderBy
_riglFilter
_riglPageToken
(Just _riglMaxResults)
(Just AltJSON)
computeService
where go
= buildClient
(Proxy :: Proxy RegionInstanceGroupsListResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/RegionInstanceGroups/List.hs | mpl-2.0 | 7,833 | 0 | 20 | 1,699 | 833 | 497 | 336 | 123 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.Route53.Types.Product
-- 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)
--
module Network.AWS.Route53.Types.Product where
import Network.AWS.Prelude
import Network.AWS.Route53.Internal
import Network.AWS.Route53.Types.Sum
-- | /Alias resource record sets only:/ Information about the domain to which
-- you are redirecting traffic.
--
-- For more information and an example, see
-- <http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingAliasRRSets.html Creating Alias Resource Record Sets>
-- in the /Amazon Route 53 Developer Guide/
--
-- .
--
-- /See:/ 'aliasTarget' smart constructor.
data AliasTarget = AliasTarget'
{ _atHostedZoneId :: !Text
, _atDNSName :: !Text
, _atEvaluateTargetHealth :: !Bool
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'AliasTarget' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'atHostedZoneId'
--
-- * 'atDNSName'
--
-- * 'atEvaluateTargetHealth'
aliasTarget
:: Text -- ^ 'atHostedZoneId'
-> Text -- ^ 'atDNSName'
-> Bool -- ^ 'atEvaluateTargetHealth'
-> AliasTarget
aliasTarget pHostedZoneId_ pDNSName_ pEvaluateTargetHealth_ =
AliasTarget'
{ _atHostedZoneId = pHostedZoneId_
, _atDNSName = pDNSName_
, _atEvaluateTargetHealth = pEvaluateTargetHealth_
}
-- | /Alias resource record sets only:/ The value of the hosted zone ID for
-- the AWS resource.
--
-- For more information and an example, see
-- <http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingAliasRRSets.html Creating Alias Resource Record Sets>
-- in the /Amazon Route 53 Developer Guide/
--
-- .
atHostedZoneId :: Lens' AliasTarget Text
atHostedZoneId = lens _atHostedZoneId (\ s a -> s{_atHostedZoneId = a});
-- | /Alias resource record sets only:/ The external DNS name associated with
-- the AWS Resource.
--
-- For more information and an example, see
-- <http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingAliasRRSets.html Creating Alias Resource Record Sets>
-- in the /Amazon Route 53 Developer Guide/
--
-- .
atDNSName :: Lens' AliasTarget Text
atDNSName = lens _atDNSName (\ s a -> s{_atDNSName = a});
-- | /Alias resource record sets only:/ A boolean value that indicates
-- whether this Resource Record Set should respect the health status of any
-- health checks associated with the ALIAS target record which it is linked
-- to.
--
-- For more information and an example, see
-- <http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingAliasRRSets.html Creating Alias Resource Record Sets>
-- in the /Amazon Route 53 Developer Guide/
--
-- .
atEvaluateTargetHealth :: Lens' AliasTarget Bool
atEvaluateTargetHealth = lens _atEvaluateTargetHealth (\ s a -> s{_atEvaluateTargetHealth = a});
instance FromXML AliasTarget where
parseXML x
= AliasTarget' <$>
(x .@ "HostedZoneId") <*> (x .@ "DNSName") <*>
(x .@ "EvaluateTargetHealth")
instance ToXML AliasTarget where
toXML AliasTarget'{..}
= mconcat
["HostedZoneId" @= _atHostedZoneId,
"DNSName" @= _atDNSName,
"EvaluateTargetHealth" @= _atEvaluateTargetHealth]
-- | A complex type that contains the information for each change in a change
-- batch request.
--
-- /See:/ 'change' smart constructor.
data Change = Change'
{ _cAction :: !ChangeAction
, _cResourceRecordSet :: !ResourceRecordSet
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Change' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cAction'
--
-- * 'cResourceRecordSet'
change
:: ChangeAction -- ^ 'cAction'
-> ResourceRecordSet -- ^ 'cResourceRecordSet'
-> Change
change pAction_ pResourceRecordSet_ =
Change'
{ _cAction = pAction_
, _cResourceRecordSet = pResourceRecordSet_
}
-- | The action to perform.
--
-- Valid values: 'CREATE' | 'DELETE' | 'UPSERT'
cAction :: Lens' Change ChangeAction
cAction = lens _cAction (\ s a -> s{_cAction = a});
-- | Information about the resource record set to create or delete.
cResourceRecordSet :: Lens' Change ResourceRecordSet
cResourceRecordSet = lens _cResourceRecordSet (\ s a -> s{_cResourceRecordSet = a});
instance ToXML Change where
toXML Change'{..}
= mconcat
["Action" @= _cAction,
"ResourceRecordSet" @= _cResourceRecordSet]
-- | A complex type that contains an optional comment and the changes that
-- you want to make with a change batch request.
--
-- /See:/ 'changeBatch' smart constructor.
data ChangeBatch = ChangeBatch'
{ _cbComment :: !(Maybe Text)
, _cbChanges :: !(List1 Change)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ChangeBatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cbComment'
--
-- * 'cbChanges'
changeBatch
:: NonEmpty Change -- ^ 'cbChanges'
-> ChangeBatch
changeBatch pChanges_ =
ChangeBatch'
{ _cbComment = Nothing
, _cbChanges = _List1 # pChanges_
}
-- | /Optional:/ Any comments you want to include about a change batch
-- request.
cbComment :: Lens' ChangeBatch (Maybe Text)
cbComment = lens _cbComment (\ s a -> s{_cbComment = a});
-- | A complex type that contains one 'Change' element for each resource
-- record set that you want to create or delete.
cbChanges :: Lens' ChangeBatch (NonEmpty Change)
cbChanges = lens _cbChanges (\ s a -> s{_cbChanges = a}) . _List1;
instance ToXML ChangeBatch where
toXML ChangeBatch'{..}
= mconcat
["Comment" @= _cbComment,
"Changes" @= toXMLList "Change" _cbChanges]
-- | A complex type that describes change information about changes made to
-- your hosted zone.
--
-- This element contains an ID that you use when performing a GetChange
-- action to get detailed information about the change.
--
-- /See:/ 'changeInfo' smart constructor.
data ChangeInfo = ChangeInfo'
{ _ciComment :: !(Maybe Text)
, _ciId :: !Text
, _ciStatus :: !ChangeStatus
, _ciSubmittedAt :: !ISO8601
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ChangeInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ciComment'
--
-- * 'ciId'
--
-- * 'ciStatus'
--
-- * 'ciSubmittedAt'
changeInfo
:: Text -- ^ 'ciId'
-> ChangeStatus -- ^ 'ciStatus'
-> UTCTime -- ^ 'ciSubmittedAt'
-> ChangeInfo
changeInfo pId_ pStatus_ pSubmittedAt_ =
ChangeInfo'
{ _ciComment = Nothing
, _ciId = pId_
, _ciStatus = pStatus_
, _ciSubmittedAt = _Time # pSubmittedAt_
}
-- | A complex type that describes change information about changes made to
-- your hosted zone.
--
-- This element contains an ID that you use when performing a GetChange
-- action to get detailed information about the change.
ciComment :: Lens' ChangeInfo (Maybe Text)
ciComment = lens _ciComment (\ s a -> s{_ciComment = a});
-- | The ID of the request. Use this ID to track when the change has
-- completed across all Amazon Route 53 DNS servers.
ciId :: Lens' ChangeInfo Text
ciId = lens _ciId (\ s a -> s{_ciId = a});
-- | The current state of the request. 'PENDING' indicates that this request
-- has not yet been applied to all Amazon Route 53 DNS servers.
--
-- Valid Values: 'PENDING' | 'INSYNC'
ciStatus :: Lens' ChangeInfo ChangeStatus
ciStatus = lens _ciStatus (\ s a -> s{_ciStatus = a});
-- | The date and time the change was submitted, in the format
-- 'YYYY-MM-DDThh:mm:ssZ', as specified in the ISO 8601 standard (for
-- example, 2009-11-19T19:37:58Z). The 'Z' after the time indicates that
-- the time is listed in Coordinated Universal Time (UTC), which is
-- synonymous with Greenwich Mean Time in this context.
ciSubmittedAt :: Lens' ChangeInfo UTCTime
ciSubmittedAt = lens _ciSubmittedAt (\ s a -> s{_ciSubmittedAt = a}) . _Time;
instance FromXML ChangeInfo where
parseXML x
= ChangeInfo' <$>
(x .@? "Comment") <*> (x .@ "Id") <*> (x .@ "Status")
<*> (x .@ "SubmittedAt")
-- | A complex type that contains name server information.
--
-- /See:/ 'delegationSet' smart constructor.
data DelegationSet = DelegationSet'
{ _dsId :: !(Maybe Text)
, _dsCallerReference :: !(Maybe Text)
, _dsNameServers :: !(List1 Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DelegationSet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dsId'
--
-- * 'dsCallerReference'
--
-- * 'dsNameServers'
delegationSet
:: NonEmpty Text -- ^ 'dsNameServers'
-> DelegationSet
delegationSet pNameServers_ =
DelegationSet'
{ _dsId = Nothing
, _dsCallerReference = Nothing
, _dsNameServers = _List1 # pNameServers_
}
-- | Undocumented member.
dsId :: Lens' DelegationSet (Maybe Text)
dsId = lens _dsId (\ s a -> s{_dsId = a});
-- | Undocumented member.
dsCallerReference :: Lens' DelegationSet (Maybe Text)
dsCallerReference = lens _dsCallerReference (\ s a -> s{_dsCallerReference = a});
-- | A complex type that contains the authoritative name servers for the
-- hosted zone. Use the method provided by your domain registrar to add an
-- NS record to your domain for each 'NameServer' that is assigned to your
-- hosted zone.
dsNameServers :: Lens' DelegationSet (NonEmpty Text)
dsNameServers = lens _dsNameServers (\ s a -> s{_dsNameServers = a}) . _List1;
instance FromXML DelegationSet where
parseXML x
= DelegationSet' <$>
(x .@? "Id") <*> (x .@? "CallerReference") <*>
(x .@? "NameServers" .!@ mempty >>=
parseXMLList1 "NameServer")
-- | A complex type that contains information about a geo location.
--
-- /See:/ 'geoLocation' smart constructor.
data GeoLocation = GeoLocation'
{ _glSubdivisionCode :: !(Maybe Text)
, _glCountryCode :: !(Maybe Text)
, _glContinentCode :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'GeoLocation' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'glSubdivisionCode'
--
-- * 'glCountryCode'
--
-- * 'glContinentCode'
geoLocation
:: GeoLocation
geoLocation =
GeoLocation'
{ _glSubdivisionCode = Nothing
, _glCountryCode = Nothing
, _glContinentCode = Nothing
}
-- | The code for a country\'s subdivision (e.g., a province of Canada). A
-- subdivision code is only valid with the appropriate country code.
--
-- Constraint: Specifying 'SubdivisionCode' without 'CountryCode' returns
-- an InvalidInput error.
glSubdivisionCode :: Lens' GeoLocation (Maybe Text)
glSubdivisionCode = lens _glSubdivisionCode (\ s a -> s{_glSubdivisionCode = a});
-- | The code for a country geo location. The default location uses \'*\' for
-- the country code and will match all locations that are not matched by a
-- geo location.
--
-- The default geo location uses a '*' for the country code. All other
-- country codes follow the ISO 3166 two-character code.
glCountryCode :: Lens' GeoLocation (Maybe Text)
glCountryCode = lens _glCountryCode (\ s a -> s{_glCountryCode = a});
-- | The code for a continent geo location. Note: only continent locations
-- have a continent code.
--
-- Valid values: 'AF' | 'AN' | 'AS' | 'EU' | 'OC' | 'NA' | 'SA'
--
-- Constraint: Specifying 'ContinentCode' with either 'CountryCode' or
-- 'SubdivisionCode' returns an InvalidInput error.
glContinentCode :: Lens' GeoLocation (Maybe Text)
glContinentCode = lens _glContinentCode (\ s a -> s{_glContinentCode = a});
instance FromXML GeoLocation where
parseXML x
= GeoLocation' <$>
(x .@? "SubdivisionCode") <*> (x .@? "CountryCode")
<*> (x .@? "ContinentCode")
instance ToXML GeoLocation where
toXML GeoLocation'{..}
= mconcat
["SubdivisionCode" @= _glSubdivisionCode,
"CountryCode" @= _glCountryCode,
"ContinentCode" @= _glContinentCode]
-- | A complex type that contains information about a 'GeoLocation'.
--
-- /See:/ 'geoLocationDetails' smart constructor.
data GeoLocationDetails = GeoLocationDetails'
{ _gldSubdivisionName :: !(Maybe Text)
, _gldSubdivisionCode :: !(Maybe Text)
, _gldCountryName :: !(Maybe Text)
, _gldCountryCode :: !(Maybe Text)
, _gldContinentCode :: !(Maybe Text)
, _gldContinentName :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'GeoLocationDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gldSubdivisionName'
--
-- * 'gldSubdivisionCode'
--
-- * 'gldCountryName'
--
-- * 'gldCountryCode'
--
-- * 'gldContinentCode'
--
-- * 'gldContinentName'
geoLocationDetails
:: GeoLocationDetails
geoLocationDetails =
GeoLocationDetails'
{ _gldSubdivisionName = Nothing
, _gldSubdivisionCode = Nothing
, _gldCountryName = Nothing
, _gldCountryCode = Nothing
, _gldContinentCode = Nothing
, _gldContinentName = Nothing
}
-- | The name of the subdivision. This element is only present if
-- 'SubdivisionCode' is also present.
gldSubdivisionName :: Lens' GeoLocationDetails (Maybe Text)
gldSubdivisionName = lens _gldSubdivisionName (\ s a -> s{_gldSubdivisionName = a});
-- | The code for a country\'s subdivision (e.g., a province of Canada). A
-- subdivision code is only valid with the appropriate country code.
gldSubdivisionCode :: Lens' GeoLocationDetails (Maybe Text)
gldSubdivisionCode = lens _gldSubdivisionCode (\ s a -> s{_gldSubdivisionCode = a});
-- | The name of the country. This element is only present if 'CountryCode'
-- is also present.
gldCountryName :: Lens' GeoLocationDetails (Maybe Text)
gldCountryName = lens _gldCountryName (\ s a -> s{_gldCountryName = a});
-- | The code for a country geo location. The default location uses \'*\' for
-- the country code and will match all locations that are not matched by a
-- geo location.
--
-- The default geo location uses a '*' for the country code. All other
-- country codes follow the ISO 3166 two-character code.
gldCountryCode :: Lens' GeoLocationDetails (Maybe Text)
gldCountryCode = lens _gldCountryCode (\ s a -> s{_gldCountryCode = a});
-- | The code for a continent geo location. Note: only continent locations
-- have a continent code.
gldContinentCode :: Lens' GeoLocationDetails (Maybe Text)
gldContinentCode = lens _gldContinentCode (\ s a -> s{_gldContinentCode = a});
-- | The name of the continent. This element is only present if
-- 'ContinentCode' is also present.
gldContinentName :: Lens' GeoLocationDetails (Maybe Text)
gldContinentName = lens _gldContinentName (\ s a -> s{_gldContinentName = a});
instance FromXML GeoLocationDetails where
parseXML x
= GeoLocationDetails' <$>
(x .@? "SubdivisionName") <*>
(x .@? "SubdivisionCode")
<*> (x .@? "CountryName")
<*> (x .@? "CountryCode")
<*> (x .@? "ContinentCode")
<*> (x .@? "ContinentName")
-- | A complex type that contains identifying information about the health
-- check.
--
-- /See:/ 'healthCheck' smart constructor.
data HealthCheck = HealthCheck'
{ _hcId :: !Text
, _hcCallerReference :: !Text
, _hcHealthCheckConfig :: !HealthCheckConfig
, _hcHealthCheckVersion :: !Nat
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'HealthCheck' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'hcId'
--
-- * 'hcCallerReference'
--
-- * 'hcHealthCheckConfig'
--
-- * 'hcHealthCheckVersion'
healthCheck
:: Text -- ^ 'hcId'
-> Text -- ^ 'hcCallerReference'
-> HealthCheckConfig -- ^ 'hcHealthCheckConfig'
-> Natural -- ^ 'hcHealthCheckVersion'
-> HealthCheck
healthCheck pId_ pCallerReference_ pHealthCheckConfig_ pHealthCheckVersion_ =
HealthCheck'
{ _hcId = pId_
, _hcCallerReference = pCallerReference_
, _hcHealthCheckConfig = pHealthCheckConfig_
, _hcHealthCheckVersion = _Nat # pHealthCheckVersion_
}
-- | The ID of the specified health check.
hcId :: Lens' HealthCheck Text
hcId = lens _hcId (\ s a -> s{_hcId = a});
-- | A unique string that identifies the request to create the health check.
hcCallerReference :: Lens' HealthCheck Text
hcCallerReference = lens _hcCallerReference (\ s a -> s{_hcCallerReference = a});
-- | A complex type that contains the health check configuration.
hcHealthCheckConfig :: Lens' HealthCheck HealthCheckConfig
hcHealthCheckConfig = lens _hcHealthCheckConfig (\ s a -> s{_hcHealthCheckConfig = a});
-- | The version of the health check. You can optionally pass this value in a
-- call to 'UpdateHealthCheck' to prevent overwriting another change to the
-- health check.
hcHealthCheckVersion :: Lens' HealthCheck Natural
hcHealthCheckVersion = lens _hcHealthCheckVersion (\ s a -> s{_hcHealthCheckVersion = a}) . _Nat;
instance FromXML HealthCheck where
parseXML x
= HealthCheck' <$>
(x .@ "Id") <*> (x .@ "CallerReference") <*>
(x .@ "HealthCheckConfig")
<*> (x .@ "HealthCheckVersion")
-- | A complex type that contains the health check configuration.
--
-- /See:/ 'healthCheckConfig' smart constructor.
data HealthCheckConfig = HealthCheckConfig'
{ _hccFailureThreshold :: !(Maybe Nat)
, _hccIPAddress :: !(Maybe Text)
, _hccSearchString :: !(Maybe Text)
, _hccHealthThreshold :: !(Maybe Nat)
, _hccResourcePath :: !(Maybe Text)
, _hccMeasureLatency :: !(Maybe Bool)
, _hccInverted :: !(Maybe Bool)
, _hccFullyQualifiedDomainName :: !(Maybe Text)
, _hccChildHealthChecks :: !(Maybe [Text])
, _hccRequestInterval :: !(Maybe Nat)
, _hccPort :: !(Maybe Nat)
, _hccType :: !HealthCheckType
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'HealthCheckConfig' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'hccFailureThreshold'
--
-- * 'hccIPAddress'
--
-- * 'hccSearchString'
--
-- * 'hccHealthThreshold'
--
-- * 'hccResourcePath'
--
-- * 'hccMeasureLatency'
--
-- * 'hccInverted'
--
-- * 'hccFullyQualifiedDomainName'
--
-- * 'hccChildHealthChecks'
--
-- * 'hccRequestInterval'
--
-- * 'hccPort'
--
-- * 'hccType'
healthCheckConfig
:: HealthCheckType -- ^ 'hccType'
-> HealthCheckConfig
healthCheckConfig pType_ =
HealthCheckConfig'
{ _hccFailureThreshold = Nothing
, _hccIPAddress = Nothing
, _hccSearchString = Nothing
, _hccHealthThreshold = Nothing
, _hccResourcePath = Nothing
, _hccMeasureLatency = Nothing
, _hccInverted = Nothing
, _hccFullyQualifiedDomainName = Nothing
, _hccChildHealthChecks = Nothing
, _hccRequestInterval = Nothing
, _hccPort = Nothing
, _hccType = pType_
}
-- | The number of consecutive health checks that an endpoint must pass or
-- fail for Route 53 to change the current status of the endpoint from
-- unhealthy to healthy or vice versa.
--
-- Valid values are integers between 1 and 10. For more information, see
-- \"How Amazon Route 53 Determines Whether an Endpoint Is Healthy\" in the
-- Amazon Route 53 Developer Guide.
hccFailureThreshold :: Lens' HealthCheckConfig (Maybe Natural)
hccFailureThreshold = lens _hccFailureThreshold (\ s a -> s{_hccFailureThreshold = a}) . mapping _Nat;
-- | IP Address of the instance being checked.
hccIPAddress :: Lens' HealthCheckConfig (Maybe Text)
hccIPAddress = lens _hccIPAddress (\ s a -> s{_hccIPAddress = a});
-- | A string to search for in the body of a health check response. Required
-- for HTTP_STR_MATCH and HTTPS_STR_MATCH health checks.
hccSearchString :: Lens' HealthCheckConfig (Maybe Text)
hccSearchString = lens _hccSearchString (\ s a -> s{_hccSearchString = a});
-- | The minimum number of child health checks that must be healthy for Route
-- 53 to consider the parent health check to be healthy. Valid values are
-- integers between 0 and 256, inclusive.
hccHealthThreshold :: Lens' HealthCheckConfig (Maybe Natural)
hccHealthThreshold = lens _hccHealthThreshold (\ s a -> s{_hccHealthThreshold = a}) . mapping _Nat;
-- | Path to ping on the instance to check the health. Required for HTTP,
-- HTTPS, HTTP_STR_MATCH, and HTTPS_STR_MATCH health checks, HTTP request
-- is issued to the instance on the given port and path.
hccResourcePath :: Lens' HealthCheckConfig (Maybe Text)
hccResourcePath = lens _hccResourcePath (\ s a -> s{_hccResourcePath = a});
-- | A Boolean value that indicates whether you want Route 53 to measure the
-- latency between health checkers in multiple AWS regions and your
-- endpoint and to display CloudWatch latency graphs in the Route 53
-- console.
hccMeasureLatency :: Lens' HealthCheckConfig (Maybe Bool)
hccMeasureLatency = lens _hccMeasureLatency (\ s a -> s{_hccMeasureLatency = a});
-- | A boolean value that indicates whether the status of health check should
-- be inverted. For example, if a health check is healthy but 'Inverted' is
-- 'True', then Route 53 considers the health check to be unhealthy.
hccInverted :: Lens' HealthCheckConfig (Maybe Bool)
hccInverted = lens _hccInverted (\ s a -> s{_hccInverted = a});
-- | Fully qualified domain name of the instance to be health checked.
hccFullyQualifiedDomainName :: Lens' HealthCheckConfig (Maybe Text)
hccFullyQualifiedDomainName = lens _hccFullyQualifiedDomainName (\ s a -> s{_hccFullyQualifiedDomainName = a});
-- | For a specified parent health check, a list of 'HealthCheckId' values
-- for the associated child health checks.
hccChildHealthChecks :: Lens' HealthCheckConfig [Text]
hccChildHealthChecks = lens _hccChildHealthChecks (\ s a -> s{_hccChildHealthChecks = a}) . _Default . _Coerce;
-- | The number of seconds between the time that Route 53 gets a response
-- from your endpoint and the time that it sends the next health-check
-- request.
--
-- Each Route 53 health checker makes requests at this interval. Valid
-- values are 10 and 30. The default value is 30.
hccRequestInterval :: Lens' HealthCheckConfig (Maybe Natural)
hccRequestInterval = lens _hccRequestInterval (\ s a -> s{_hccRequestInterval = a}) . mapping _Nat;
-- | Port on which connection will be opened to the instance to health check.
-- For HTTP and HTTP_STR_MATCH this defaults to 80 if the port is not
-- specified. For HTTPS and HTTPS_STR_MATCH this defaults to 443 if the
-- port is not specified.
hccPort :: Lens' HealthCheckConfig (Maybe Natural)
hccPort = lens _hccPort (\ s a -> s{_hccPort = a}) . mapping _Nat;
-- | The type of health check to be performed. Currently supported types are
-- TCP, HTTP, HTTPS, HTTP_STR_MATCH, and HTTPS_STR_MATCH.
hccType :: Lens' HealthCheckConfig HealthCheckType
hccType = lens _hccType (\ s a -> s{_hccType = a});
instance FromXML HealthCheckConfig where
parseXML x
= HealthCheckConfig' <$>
(x .@? "FailureThreshold") <*> (x .@? "IPAddress")
<*> (x .@? "SearchString")
<*> (x .@? "HealthThreshold")
<*> (x .@? "ResourcePath")
<*> (x .@? "MeasureLatency")
<*> (x .@? "Inverted")
<*> (x .@? "FullyQualifiedDomainName")
<*>
(x .@? "ChildHealthChecks" .!@ mempty >>=
may (parseXMLList "ChildHealthCheck"))
<*> (x .@? "RequestInterval")
<*> (x .@? "Port")
<*> (x .@ "Type")
instance ToXML HealthCheckConfig where
toXML HealthCheckConfig'{..}
= mconcat
["FailureThreshold" @= _hccFailureThreshold,
"IPAddress" @= _hccIPAddress,
"SearchString" @= _hccSearchString,
"HealthThreshold" @= _hccHealthThreshold,
"ResourcePath" @= _hccResourcePath,
"MeasureLatency" @= _hccMeasureLatency,
"Inverted" @= _hccInverted,
"FullyQualifiedDomainName" @=
_hccFullyQualifiedDomainName,
"ChildHealthChecks" @=
toXML
(toXMLList "ChildHealthCheck" <$>
_hccChildHealthChecks),
"RequestInterval" @= _hccRequestInterval,
"Port" @= _hccPort, "Type" @= _hccType]
-- | A complex type that contains the IP address of a Route 53 health checker
-- and the reason for the health check status.
--
-- /See:/ 'healthCheckObservation' smart constructor.
data HealthCheckObservation = HealthCheckObservation'
{ _hcoIPAddress :: !(Maybe Text)
, _hcoStatusReport :: !(Maybe StatusReport)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'HealthCheckObservation' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'hcoIPAddress'
--
-- * 'hcoStatusReport'
healthCheckObservation
:: HealthCheckObservation
healthCheckObservation =
HealthCheckObservation'
{ _hcoIPAddress = Nothing
, _hcoStatusReport = Nothing
}
-- | The IP address of the Route 53 health checker that performed the health
-- check.
hcoIPAddress :: Lens' HealthCheckObservation (Maybe Text)
hcoIPAddress = lens _hcoIPAddress (\ s a -> s{_hcoIPAddress = a});
-- | A complex type that contains information about the health check status
-- for the current observation.
hcoStatusReport :: Lens' HealthCheckObservation (Maybe StatusReport)
hcoStatusReport = lens _hcoStatusReport (\ s a -> s{_hcoStatusReport = a});
instance FromXML HealthCheckObservation where
parseXML x
= HealthCheckObservation' <$>
(x .@? "IPAddress") <*> (x .@? "StatusReport")
-- | A complex type that contain information about the specified hosted zone.
--
-- /See:/ 'hostedZone' smart constructor.
data HostedZone = HostedZone'
{ _hzConfig :: !(Maybe HostedZoneConfig)
, _hzResourceRecordSetCount :: !(Maybe Integer)
, _hzId :: !Text
, _hzName :: !Text
, _hzCallerReference :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'HostedZone' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'hzConfig'
--
-- * 'hzResourceRecordSetCount'
--
-- * 'hzId'
--
-- * 'hzName'
--
-- * 'hzCallerReference'
hostedZone
:: Text -- ^ 'hzId'
-> Text -- ^ 'hzName'
-> Text -- ^ 'hzCallerReference'
-> HostedZone
hostedZone pId_ pName_ pCallerReference_ =
HostedZone'
{ _hzConfig = Nothing
, _hzResourceRecordSetCount = Nothing
, _hzId = pId_
, _hzName = pName_
, _hzCallerReference = pCallerReference_
}
-- | A complex type that contains the 'Comment' element.
hzConfig :: Lens' HostedZone (Maybe HostedZoneConfig)
hzConfig = lens _hzConfig (\ s a -> s{_hzConfig = a});
-- | Total number of resource record sets in the hosted zone.
hzResourceRecordSetCount :: Lens' HostedZone (Maybe Integer)
hzResourceRecordSetCount = lens _hzResourceRecordSetCount (\ s a -> s{_hzResourceRecordSetCount = a});
-- | The ID of the specified hosted zone.
hzId :: Lens' HostedZone Text
hzId = lens _hzId (\ s a -> s{_hzId = a});
-- | The name of the domain. This must be a fully-specified domain, for
-- example, www.example.com. The trailing dot is optional; Route 53 assumes
-- that the domain name is fully qualified. This means that Route 53 treats
-- www.example.com (without a trailing dot) and www.example.com. (with a
-- trailing dot) as identical.
--
-- This is the name you have registered with your DNS registrar. You should
-- ask your registrar to change the authoritative name servers for your
-- domain to the set of 'NameServers' elements returned in 'DelegationSet'.
hzName :: Lens' HostedZone Text
hzName = lens _hzName (\ s a -> s{_hzName = a});
-- | A unique string that identifies the request to create the hosted zone.
hzCallerReference :: Lens' HostedZone Text
hzCallerReference = lens _hzCallerReference (\ s a -> s{_hzCallerReference = a});
instance FromXML HostedZone where
parseXML x
= HostedZone' <$>
(x .@? "Config") <*> (x .@? "ResourceRecordSetCount")
<*> (x .@ "Id")
<*> (x .@ "Name")
<*> (x .@ "CallerReference")
-- | A complex type that contains an optional comment about your hosted zone.
-- If you don\'t want to specify a comment, you can omit the
-- 'HostedZoneConfig' and 'Comment' elements from the XML document.
--
-- /See:/ 'hostedZoneConfig' smart constructor.
data HostedZoneConfig = HostedZoneConfig'
{ _hzcPrivateZone :: !(Maybe Bool)
, _hzcComment :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'HostedZoneConfig' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'hzcPrivateZone'
--
-- * 'hzcComment'
hostedZoneConfig
:: HostedZoneConfig
hostedZoneConfig =
HostedZoneConfig'
{ _hzcPrivateZone = Nothing
, _hzcComment = Nothing
}
-- | A value that indicates whether this is a private hosted zone. The value
-- is returned in the response; do not specify it in the request.
hzcPrivateZone :: Lens' HostedZoneConfig (Maybe Bool)
hzcPrivateZone = lens _hzcPrivateZone (\ s a -> s{_hzcPrivateZone = a});
-- | An optional comment about your hosted zone. If you don\'t want to
-- specify a comment, you can omit the 'HostedZoneConfig' and 'Comment'
-- elements from the XML document.
hzcComment :: Lens' HostedZoneConfig (Maybe Text)
hzcComment = lens _hzcComment (\ s a -> s{_hzcComment = a});
instance FromXML HostedZoneConfig where
parseXML x
= HostedZoneConfig' <$>
(x .@? "PrivateZone") <*> (x .@? "Comment")
instance ToXML HostedZoneConfig where
toXML HostedZoneConfig'{..}
= mconcat
["PrivateZone" @= _hzcPrivateZone,
"Comment" @= _hzcComment]
-- | A complex type that contains the value of the 'Value' element for the
-- current resource record set.
--
-- /See:/ 'resourceRecord' smart constructor.
newtype ResourceRecord = ResourceRecord'
{ _rrValue :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ResourceRecord' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rrValue'
resourceRecord
:: Text -- ^ 'rrValue'
-> ResourceRecord
resourceRecord pValue_ =
ResourceRecord'
{ _rrValue = pValue_
}
-- | The value of the 'Value' element for the current resource record set.
rrValue :: Lens' ResourceRecord Text
rrValue = lens _rrValue (\ s a -> s{_rrValue = a});
instance FromXML ResourceRecord where
parseXML x = ResourceRecord' <$> (x .@ "Value")
instance ToXML ResourceRecord where
toXML ResourceRecord'{..}
= mconcat ["Value" @= _rrValue]
-- | A complex type that contains information about the current resource
-- record set.
--
-- /See:/ 'resourceRecordSet' smart constructor.
data ResourceRecordSet = ResourceRecordSet'
{ _rrsTTL :: !(Maybe Nat)
, _rrsResourceRecords :: !(Maybe (List1 ResourceRecord))
, _rrsAliasTarget :: !(Maybe AliasTarget)
, _rrsWeight :: !(Maybe Nat)
, _rrsSetIdentifier :: !(Maybe Text)
, _rrsFailover :: !(Maybe Failover)
, _rrsHealthCheckId :: !(Maybe Text)
, _rrsRegion :: !(Maybe Region)
, _rrsGeoLocation :: !(Maybe GeoLocation)
, _rrsName :: !Text
, _rrsType :: !RecordType
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ResourceRecordSet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rrsTTL'
--
-- * 'rrsResourceRecords'
--
-- * 'rrsAliasTarget'
--
-- * 'rrsWeight'
--
-- * 'rrsSetIdentifier'
--
-- * 'rrsFailover'
--
-- * 'rrsHealthCheckId'
--
-- * 'rrsRegion'
--
-- * 'rrsGeoLocation'
--
-- * 'rrsName'
--
-- * 'rrsType'
resourceRecordSet
:: Text -- ^ 'rrsName'
-> RecordType -- ^ 'rrsType'
-> ResourceRecordSet
resourceRecordSet pName_ pType_ =
ResourceRecordSet'
{ _rrsTTL = Nothing
, _rrsResourceRecords = Nothing
, _rrsAliasTarget = Nothing
, _rrsWeight = Nothing
, _rrsSetIdentifier = Nothing
, _rrsFailover = Nothing
, _rrsHealthCheckId = Nothing
, _rrsRegion = Nothing
, _rrsGeoLocation = Nothing
, _rrsName = pName_
, _rrsType = pType_
}
-- | The cache time to live for the current resource record set.
rrsTTL :: Lens' ResourceRecordSet (Maybe Natural)
rrsTTL = lens _rrsTTL (\ s a -> s{_rrsTTL = a}) . mapping _Nat;
-- | A complex type that contains the resource records for the current
-- resource record set.
rrsResourceRecords :: Lens' ResourceRecordSet (Maybe (NonEmpty ResourceRecord))
rrsResourceRecords = lens _rrsResourceRecords (\ s a -> s{_rrsResourceRecords = a}) . mapping _List1;
-- | /Alias resource record sets only:/ Information about the AWS resource to
-- which you are redirecting traffic.
rrsAliasTarget :: Lens' ResourceRecordSet (Maybe AliasTarget)
rrsAliasTarget = lens _rrsAliasTarget (\ s a -> s{_rrsAliasTarget = a});
-- | /Weighted resource record sets only:/ Among resource record sets that
-- have the same combination of DNS name and type, a value that determines
-- what portion of traffic for the current resource record set is routed to
-- the associated location.
rrsWeight :: Lens' ResourceRecordSet (Maybe Natural)
rrsWeight = lens _rrsWeight (\ s a -> s{_rrsWeight = a}) . mapping _Nat;
-- | /Weighted, Latency, Geo, and Failover resource record sets only:/ An
-- identifier that differentiates among multiple resource record sets that
-- have the same combination of DNS name and type.
rrsSetIdentifier :: Lens' ResourceRecordSet (Maybe Text)
rrsSetIdentifier = lens _rrsSetIdentifier (\ s a -> s{_rrsSetIdentifier = a});
-- | /Failover resource record sets only:/ Among resource record sets that
-- have the same combination of DNS name and type, a value that indicates
-- whether the current resource record set is a primary or secondary
-- resource record set. A failover set may contain at most one resource
-- record set marked as primary and one resource record set marked as
-- secondary. A resource record set marked as primary will be returned if
-- any of the following are true: (1) an associated health check is
-- passing, (2) if the resource record set is an alias with the evaluate
-- target health and at least one target resource record set is healthy,
-- (3) both the primary and secondary resource record set are failing
-- health checks or (4) there is no secondary resource record set. A
-- secondary resource record set will be returned if: (1) the primary is
-- failing a health check and either the secondary is passing a health
-- check or has no associated health check, or (2) there is no primary
-- resource record set.
--
-- Valid values: 'PRIMARY' | 'SECONDARY'
rrsFailover :: Lens' ResourceRecordSet (Maybe Failover)
rrsFailover = lens _rrsFailover (\ s a -> s{_rrsFailover = a});
-- | /Health Check resource record sets only, not required for alias resource
-- record sets:/ An identifier that is used to identify health check
-- associated with the resource record set.
rrsHealthCheckId :: Lens' ResourceRecordSet (Maybe Text)
rrsHealthCheckId = lens _rrsHealthCheckId (\ s a -> s{_rrsHealthCheckId = a});
-- | /Latency-based resource record sets only:/ Among resource record sets
-- that have the same combination of DNS name and type, a value that
-- specifies the AWS region for the current resource record set.
rrsRegion :: Lens' ResourceRecordSet (Maybe Region)
rrsRegion = lens _rrsRegion (\ s a -> s{_rrsRegion = a});
-- | /Geo location resource record sets only:/ Among resource record sets
-- that have the same combination of DNS name and type, a value that
-- specifies the geo location for the current resource record set.
rrsGeoLocation :: Lens' ResourceRecordSet (Maybe GeoLocation)
rrsGeoLocation = lens _rrsGeoLocation (\ s a -> s{_rrsGeoLocation = a});
-- | The domain name of the current resource record set.
rrsName :: Lens' ResourceRecordSet Text
rrsName = lens _rrsName (\ s a -> s{_rrsName = a});
-- | The type of the current resource record set.
rrsType :: Lens' ResourceRecordSet RecordType
rrsType = lens _rrsType (\ s a -> s{_rrsType = a});
instance FromXML ResourceRecordSet where
parseXML x
= ResourceRecordSet' <$>
(x .@? "TTL") <*>
(x .@? "ResourceRecords" .!@ mempty >>=
may (parseXMLList1 "ResourceRecord"))
<*> (x .@? "AliasTarget")
<*> (x .@? "Weight")
<*> (x .@? "SetIdentifier")
<*> (x .@? "Failover")
<*> (x .@? "HealthCheckId")
<*> (x .@? "Region")
<*> (x .@? "GeoLocation")
<*> (x .@ "Name")
<*> (x .@ "Type")
instance ToXML ResourceRecordSet where
toXML ResourceRecordSet'{..}
= mconcat
["TTL" @= _rrsTTL,
"ResourceRecords" @=
toXML
(toXMLList "ResourceRecord" <$> _rrsResourceRecords),
"AliasTarget" @= _rrsAliasTarget,
"Weight" @= _rrsWeight,
"SetIdentifier" @= _rrsSetIdentifier,
"Failover" @= _rrsFailover,
"HealthCheckId" @= _rrsHealthCheckId,
"Region" @= _rrsRegion,
"GeoLocation" @= _rrsGeoLocation, "Name" @= _rrsName,
"Type" @= _rrsType]
-- | A complex type containing a resource and its associated tags.
--
-- /See:/ 'resourceTagSet' smart constructor.
data ResourceTagSet = ResourceTagSet'
{ _rtsResourceId :: !(Maybe Text)
, _rtsResourceType :: !(Maybe TagResourceType)
, _rtsTags :: !(Maybe (List1 Tag))
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ResourceTagSet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rtsResourceId'
--
-- * 'rtsResourceType'
--
-- * 'rtsTags'
resourceTagSet
:: ResourceTagSet
resourceTagSet =
ResourceTagSet'
{ _rtsResourceId = Nothing
, _rtsResourceType = Nothing
, _rtsTags = Nothing
}
-- | The ID for the specified resource.
rtsResourceId :: Lens' ResourceTagSet (Maybe Text)
rtsResourceId = lens _rtsResourceId (\ s a -> s{_rtsResourceId = a});
-- | The type of the resource.
--
-- - The resource type for health checks is 'healthcheck'.
--
-- - The resource type for hosted zones is 'hostedzone'.
rtsResourceType :: Lens' ResourceTagSet (Maybe TagResourceType)
rtsResourceType = lens _rtsResourceType (\ s a -> s{_rtsResourceType = a});
-- | The tags associated with the specified resource.
rtsTags :: Lens' ResourceTagSet (Maybe (NonEmpty Tag))
rtsTags = lens _rtsTags (\ s a -> s{_rtsTags = a}) . mapping _List1;
instance FromXML ResourceTagSet where
parseXML x
= ResourceTagSet' <$>
(x .@? "ResourceId") <*> (x .@? "ResourceType") <*>
(x .@? "Tags" .!@ mempty >>=
may (parseXMLList1 "Tag"))
-- | A complex type that contains information about the health check status
-- for the current observation.
--
-- /See:/ 'statusReport' smart constructor.
data StatusReport = StatusReport'
{ _srStatus :: !(Maybe Text)
, _srCheckedTime :: !(Maybe ISO8601)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'StatusReport' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'srStatus'
--
-- * 'srCheckedTime'
statusReport
:: StatusReport
statusReport =
StatusReport'
{ _srStatus = Nothing
, _srCheckedTime = Nothing
}
-- | The observed health check status.
srStatus :: Lens' StatusReport (Maybe Text)
srStatus = lens _srStatus (\ s a -> s{_srStatus = a});
-- | The date and time the health check status was observed, in the format
-- 'YYYY-MM-DDThh:mm:ssZ', as specified in the ISO 8601 standard (for
-- example, 2009-11-19T19:37:58Z). The 'Z' after the time indicates that
-- the time is listed in Coordinated Universal Time (UTC), which is
-- synonymous with Greenwich Mean Time in this context.
srCheckedTime :: Lens' StatusReport (Maybe UTCTime)
srCheckedTime = lens _srCheckedTime (\ s a -> s{_srCheckedTime = a}) . mapping _Time;
instance FromXML StatusReport where
parseXML x
= StatusReport' <$>
(x .@? "Status") <*> (x .@? "CheckedTime")
-- | A single tag containing a key and value.
--
-- /See:/ 'tag' smart constructor.
data Tag = Tag'
{ _tagValue :: !(Maybe Text)
, _tagKey :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Tag' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tagValue'
--
-- * 'tagKey'
tag
:: Tag
tag =
Tag'
{ _tagValue = Nothing
, _tagKey = Nothing
}
-- | The value for a 'Tag'.
tagValue :: Lens' Tag (Maybe Text)
tagValue = lens _tagValue (\ s a -> s{_tagValue = a});
-- | The key for a 'Tag'.
tagKey :: Lens' Tag (Maybe Text)
tagKey = lens _tagKey (\ s a -> s{_tagKey = a});
instance FromXML Tag where
parseXML x
= Tag' <$> (x .@? "Value") <*> (x .@? "Key")
instance ToXML Tag where
toXML Tag'{..}
= mconcat ["Value" @= _tagValue, "Key" @= _tagKey]
-- | /See:/ 'vpc' smart constructor.
data VPC = VPC'
{ _vpcVPCRegion :: !(Maybe VPCRegion)
, _vpcVPCId :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'VPC' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vpcVPCRegion'
--
-- * 'vpcVPCId'
vpc
:: VPC
vpc =
VPC'
{ _vpcVPCRegion = Nothing
, _vpcVPCId = Nothing
}
-- | Undocumented member.
vpcVPCRegion :: Lens' VPC (Maybe VPCRegion)
vpcVPCRegion = lens _vpcVPCRegion (\ s a -> s{_vpcVPCRegion = a});
-- | Undocumented member.
vpcVPCId :: Lens' VPC (Maybe Text)
vpcVPCId = lens _vpcVPCId (\ s a -> s{_vpcVPCId = a});
instance FromXML VPC where
parseXML x
= VPC' <$> (x .@? "VPCRegion") <*> (x .@? "VPCId")
instance ToXML VPC where
toXML VPC'{..}
= mconcat
["VPCRegion" @= _vpcVPCRegion, "VPCId" @= _vpcVPCId]
| olorin/amazonka | amazonka-route53/gen/Network/AWS/Route53/Types/Product.hs | mpl-2.0 | 44,112 | 0 | 20 | 9,576 | 7,455 | 4,339 | 3,116 | 720 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Experimental.Database where
import Experimental.Data.Card
type Database = [Card]
database :: IO Database
database = readSets "db/cards/sets"
findByName :: String -> Database -> Database
findByName name = filter (\card -> cName card == name)
findBySet :: String -> Database -> Database
findBySet set = filter (\card -> cSet card == set)
| aspidites/vice-by-example | haskell/Experimental/Database.hs | agpl-3.0 | 383 | 0 | 9 | 60 | 116 | 63 | 53 | 10 | 1 |
module HEP.Jet.FastJet.Class.TObject
(
TObject(..)
, ITObject(..)
, upcastTObject
, newTObject
) where
-- import HEP.Jet.FastJet.Class.Interface
-- import HEP.Jet.FastJet.Class.Implementation ()
import HEP.Jet.FastJet.Class.TObject.RawType
import HEP.Jet.FastJet.Class.TObject.Interface
import HEP.Jet.FastJet.Class.TObject.Implementation
| wavewave/HFastJet | oldsrc/HEP/Jet/FastJet/Class/TObject.hs | lgpl-2.1 | 357 | 0 | 5 | 43 | 60 | 45 | 15 | 9 | 0 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-|
Module providing Bitcoin script evaluation. See
<https://github.com/bitcoin/bitcoin/blob/master/src/script.cpp>
EvalScript and <https://en.bitcoin.it/wiki/Script>
-}
module Network.Haskoin.Script.Evaluator
(
-- * Script evaluation
verifySpend
, evalScript
, SigCheck
, Flag
-- * Evaluation data types
, ProgramData
, Stack
-- * Helper functions
, encodeInt
, decodeInt
, decodeFullInt
, cltvEncodeInt
, cltvDecodeInt
, encodeBool
, decodeBool
, runStack
, checkStack
, dumpScript
, dumpStack
, execScript
) where
import Control.Monad.Except
import Control.Monad.Identity
import Control.Monad.Reader
import Control.Monad.State
import Data.Bits (clearBit, setBit, shiftL,
shiftR, testBit, (.&.))
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Either (rights)
import Data.Int (Int64)
import Data.Maybe (isJust, mapMaybe)
import Data.Serialize (decode, encode)
import Data.String.Conversions (cs)
import Data.Word (Word32, Word64, Word8)
import Network.Haskoin.Crypto
import Network.Haskoin.Script.SigHash
import Network.Haskoin.Script.Types
import Network.Haskoin.Transaction.Types
import Network.Haskoin.Util
maxScriptSize :: Int
maxScriptSize = 10000
maxScriptElementSize :: Int
maxScriptElementSize = 520
maxStackSize :: Int
maxStackSize = 1000
maxOpcodes :: Int
maxOpcodes = 200
maxKeysMultisig :: Int
maxKeysMultisig = 20
data Flag = P2SH
| STRICTENC
| DERSIG
| LOW_S
| NULLDUMMY
| SIGPUSHONLY
| MINIMALDATA
| DISCOURAGE_UPGRADABLE_NOPS
deriving ( Show, Read, Eq )
type FlagSet = [ Flag ]
data EvalError =
EvalError String
| ProgramError String ProgramData
| StackError ScriptOp
| DisabledOp ScriptOp
instance Show EvalError where
show (EvalError m) = m
show (ProgramError m prog) = m ++ " - ProgramData: " ++ show prog
show (StackError op) = show op ++ ": Stack Error"
show (DisabledOp op) = show op ++ ": disabled"
type StackValue = [Word8]
type AltStack = [StackValue]
type Stack = [StackValue]
type HashOps = [ScriptOp] -- the code that is verified by OP_CHECKSIG
-- | Defines the type of function required by script evaluating
-- functions to check transaction signatures.
type SigCheck = [ScriptOp] -> TxSignature -> PubKey -> Bool
-- | Data type of the evaluation state.
data ProgramData = ProgramData {
stack :: Stack,
altStack :: AltStack,
hashOps :: HashOps,
sigCheck :: SigCheck,
opCount :: Int
}
dumpOp :: ScriptOp -> ByteString
dumpOp (OP_PUSHDATA payload optype) = mconcat
[ "OP_PUSHDATA(", cs (show optype), ")", " 0x", encodeHex payload ]
dumpOp op = cs $ show op
dumpList :: [ByteString] -> ByteString
dumpList xs = mconcat [ "[", BS.intercalate "," xs, "]" ]
dumpScript :: [ScriptOp] -> ByteString
dumpScript script = dumpList $ map dumpOp script
dumpStack :: Stack -> ByteString
dumpStack s = dumpList $ map (encodeHex . BS.pack) s
-- TODO: Test
instance Show ProgramData where
show p = "stack: " ++ cs (dumpStack $ stack p)
type ProgramState = ExceptT EvalError Identity
type IfStack = [Bool]
-- | Monad of actions independent of conditional statements.
type StackOperation = ReaderT FlagSet ( StateT ProgramData ProgramState )
-- | Monad of actions which taking if statements into account.
-- Separate state type from StackOperation for type safety
type Program a = StateT IfStack StackOperation a
evalStackOperation :: StackOperation a -> ProgramData -> FlagSet -> Either EvalError a
evalStackOperation m s f = runIdentity . runExceptT $ evalStateT ( runReaderT m f ) s
evalProgram :: Program a -- ^ ProgramData monad
-> [ Bool ] -- ^ Initial if state stack
-> ProgramData -- ^ Initial computation data
-> FlagSet -- ^ Evaluation Flags
-> Either EvalError a
evalProgram m s = evalStackOperation ( evalStateT m s )
--------------------------------------------------------------------------------
-- Error utils
programError :: String -> StackOperation a
programError s = get >>= throwError . ProgramError s
disabled :: ScriptOp -> StackOperation ()
disabled = throwError . DisabledOp
--------------------------------------------------------------------------------
-- Type Conversions
-- | Encoding function for the stack value format of integers. Most
-- significant bit defines sign.
-- Note that this function will encode any Int64 into a StackValue,
-- thus producing stack-encoded integers which are not valid numeric
-- opcodes, as they exceed 4 bytes in length.
encodeInt :: Int64 -> StackValue
encodeInt i = prefix $ encod (fromIntegral $ abs i) []
where encod :: Word64 -> StackValue -> StackValue
encod 0 bytes = bytes
encod j bytes = fromIntegral j:encod (j `shiftR` 8) bytes
prefix :: StackValue -> StackValue
prefix [] = []
prefix xs | testBit (last xs) 7 = prefix $ xs ++ [0]
| i < 0 = init xs ++ [setBit (last xs) 7]
| otherwise = xs
-- | Decode an Int64 from the stack value integer format.
-- Inverse of `encodeInt`.
-- Note that only integers decoded by 'decodeInt' are valid
-- numeric opcodes (numeric opcodes can only be up to 4 bytes in size).
-- However, in the case of eg. CHECKLOCKTIMEVERIFY, we need to
-- be able to encode and decode stack integers up to
-- (maxBound :: Word32), which are 5 bytes.
decodeFullInt :: StackValue -> Maybe Int64
decodeFullInt bytes
| length bytes > 8 = Nothing
| otherwise = Just $ sign' (decodeW bytes)
where decodeW [] = 0
decodeW [x] = fromIntegral $ clearBit x 7
decodeW (x:xs) = fromIntegral x + decodeW xs `shiftL` 8
sign' i | null bytes = 0
| testBit (last bytes) 7 = -i
| otherwise = i
-- | Used for decoding numeric opcodes. Will not return
-- an integer that takes up more than
-- 4 bytes on the stack (the size limit for numeric opcodes).
-- The naming is kept for backwards compatibility.
decodeInt :: StackValue -> Maybe Int64
decodeInt bytes | length bytes > 4 = Nothing
| otherwise = decodeFullInt bytes
-- | Decode the integer argument to OP_CHECKLOCKTIMEVERIFY (CLTV)
-- from a stack value.
-- The full uint32 range is needed in order to represent timestamps
-- for use with CLTV. Reference:
-- https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki#Detailed_Specification
cltvDecodeInt :: StackValue -> Maybe Word32
cltvDecodeInt bytes
| length bytes > 5 = Nothing
| otherwise = decodeFullInt bytes >>= uint32Bounds
where
uint32Bounds :: Int64 -> Maybe Word32
uint32Bounds i64
| i64 < 0 || i64 > fromIntegral (maxBound :: Word32) = Nothing
| otherwise = Just $ fromIntegral i64
-- | Helper function for encoding the argument to OP_CHECKLOCKTIMEVERIFY
cltvEncodeInt :: Word32 -> StackValue
cltvEncodeInt = encodeInt . fromIntegral
-- | Conversion of StackValue to Bool (true if non-zero).
decodeBool :: StackValue -> Bool
decodeBool [] = False
decodeBool [0x00] = False
decodeBool [0x80] = False
decodeBool (0x00:vs) = decodeBool vs
decodeBool _ = True
encodeBool :: Bool -> StackValue
encodeBool True = [1]
encodeBool False = []
constValue :: ScriptOp -> Maybe StackValue
constValue op = case op of
OP_0 -> Just $ encodeInt 0
OP_1 -> Just $ encodeInt 1
OP_2 -> Just $ encodeInt 2
OP_3 -> Just $ encodeInt 3
OP_4 -> Just $ encodeInt 4
OP_5 -> Just $ encodeInt 5
OP_6 -> Just $ encodeInt 6
OP_7 -> Just $ encodeInt 7
OP_8 -> Just $ encodeInt 8
OP_9 -> Just $ encodeInt 9
OP_10 -> Just $ encodeInt 10
OP_11 -> Just $ encodeInt 11
OP_12 -> Just $ encodeInt 12
OP_13 -> Just $ encodeInt 13
OP_14 -> Just $ encodeInt 14
OP_15 -> Just $ encodeInt 15
OP_16 -> Just $ encodeInt 16
OP_1NEGATE -> Just $ encodeInt $ -1
(OP_PUSHDATA string _) -> Just $ BS.unpack string
_ -> Nothing
-- | Check if OpCode is constant
isConstant :: ScriptOp -> Bool
isConstant = isJust . constValue
-- | Check if OpCode is disabled
isDisabled :: ScriptOp -> Bool
isDisabled op = op `elem` [ OP_CAT
, OP_SUBSTR
, OP_LEFT
, OP_RIGHT
, OP_INVERT
, OP_AND
, OP_OR
, OP_XOR
, OP_2MUL
, OP_2DIV
, OP_MUL
, OP_DIV
, OP_MOD
, OP_LSHIFT
, OP_RSHIFT
, OP_VER
, OP_VERIF
, OP_VERNOTIF ]
-- | Check if OpCode counts towards opcount limit
countOp :: ScriptOp -> Bool
countOp op | isConstant op = False
| op == OP_RESERVED = False
| otherwise = True
popInt :: StackOperation Int64
popInt = minimalStackValEnforcer >> decodeInt <$> popStack >>= \case
Nothing -> programError "popInt: data > nMaxNumSize"
Just i -> return i
pushInt :: Int64 -> StackOperation ()
pushInt = pushStack . encodeInt
popBool :: StackOperation Bool
popBool = decodeBool <$> popStack
pushBool :: Bool -> StackOperation ()
pushBool = pushStack . encodeBool
opToSv :: StackValue -> ByteString
opToSv = BS.pack
bsToSv :: ByteString -> StackValue
bsToSv = BS.unpack
--------------------------------------------------------------------------------
-- Stack Primitives
getStack :: StackOperation Stack
getStack = stack <$> get
getCond :: Program [Bool]
getCond = get
popCond :: Program Bool
popCond = get >>= \case
[] -> lift $ programError "popCond: empty condStack"
(x:xs) -> put xs >> return x
pushCond :: Bool -> Program ()
pushCond c = get >>= \s ->
put (c:s)
flipCond :: Program ()
flipCond = popCond >>= pushCond . not
withStack :: StackOperation Stack
withStack = getStack >>= \case
[] -> stackError
s -> return s
putStack :: Stack -> StackOperation ()
putStack st = modify $ \p -> p { stack = st }
prependStack :: Stack -> StackOperation ()
prependStack s = getStack >>= \s' -> putStack $ s ++ s'
checkPushData :: ScriptOp -> StackOperation ()
checkPushData (OP_PUSHDATA v _) | BS.length v > fromIntegral maxScriptElementSize
= programError "OP_PUSHDATA > maxScriptElementSize"
| otherwise = return ()
checkPushData _ = return ()
checkStackSize :: StackOperation ()
checkStackSize = do n <- length . stack <$> get
m <- length . altStack <$> get
when ((n + m) > fromIntegral maxStackSize) $
programError "stack > maxStackSize"
pushStack :: StackValue -> StackOperation ()
pushStack v = getStack >>= \s -> putStack (v:s)
popStack :: StackOperation StackValue
popStack = withStack >>= \(s:ss) -> putStack ss >> return s
popStackN :: Integer -> StackOperation [StackValue]
popStackN n | n < 0 = programError "popStackN: negative argument"
| n == 0 = return []
| otherwise = (:) <$> popStack <*> popStackN (n - 1)
pickStack :: Bool -> Int -> StackOperation ()
pickStack remove n = do
st <- getStack
when (n < 0) $
programError "pickStack: n < 0"
when (n > length st - 1) $
programError "pickStack: n > size"
let v = st !! n
when remove $ putStack $ take n st ++ drop (n+1) st
pushStack v
getHashOps :: StackOperation HashOps
getHashOps = hashOps <$> get
-- | Function to track the verified OPs signed by OP_CHECK(MULTI) sig.
-- Dependent on the sequence of `OP_CODESEPARATOR`
dropHashOpsSeparatedCode :: StackOperation ()
dropHashOpsSeparatedCode = modify $ \p ->
let tryDrop = dropWhile ( /= OP_CODESEPARATOR ) $ hashOps p in
case tryDrop of
-- If no OP_CODESEPARATOR, take the whole script. This case is
-- possible when there is no OP_CODESEPARATOR in scriptPubKey but
-- one exists in scriptSig
[] -> p
_ -> p { hashOps = tail tryDrop }
-- | Filters out `OP_CODESEPARATOR` from the output script used by
-- OP_CHECK(MULTI)SIG
preparedHashOps :: StackOperation HashOps
preparedHashOps = filter ( /= OP_CODESEPARATOR ) <$> getHashOps
-- | Removes any PUSHDATA that contains the signatures. Used in
-- CHECK(MULTI)SIG so that signatures can be contained in output
-- scripts. See FindAndDelete() in Bitcoin Core.
findAndDelete :: [ StackValue ] -> [ ScriptOp ] -> [ ScriptOp ]
findAndDelete [] ops = ops
findAndDelete (s:ss) ops = let pushOp = opPushData . opToSv $ s in
findAndDelete ss $ filter ( /= pushOp ) ops
checkMultiSig :: SigCheck -- ^ Signature checking function
-> [ StackValue ] -- ^ PubKeys
-> [ StackValue ] -- ^ Signatures
-> [ ScriptOp ] -- ^ CODESEPARATOR'd hashops
-> Bool
checkMultiSig f encPubKeys encSigs hOps =
let pubKeys = mapMaybe (eitherToMaybe . decode . opToSv) encPubKeys
sigs = rights $ map ( decodeSig . opToSv ) encSigs
cleanHashOps = findAndDelete encSigs hOps
in (length sigs == length encSigs) && -- check for bad signatures
orderedSatisfy (f cleanHashOps) sigs pubKeys
-- | Tests whether a function is satisfied for every a with some b "in
-- order". By "in order" we mean, if a pair satisfies the function,
-- any other satisfying pair must be deeper in each list. Designed to
-- return as soon as the result is known to minimize expensive
-- function calls. Used in checkMultiSig to verify signature/pubKey
-- pairs with a values as signatures and b values as pubkeys
orderedSatisfy :: ( a -> b -> Bool )
-> [ a ]
-> [ b ]
-> Bool
orderedSatisfy _ [] _ = True
orderedSatisfy _ (_:_) [] = False
orderedSatisfy f x@(a:as) y@(b:bs) | length x > length y = False
| f a b = orderedSatisfy f as bs
| otherwise = orderedSatisfy f x bs
tStack1 :: (StackValue -> Stack) -> StackOperation ()
tStack1 f = f <$> popStack >>= prependStack
tStack2 :: (StackValue -> StackValue -> Stack) -> StackOperation ()
tStack2 f = f <$> popStack <*> popStack >>= prependStack
tStack3 :: (StackValue -> StackValue -> StackValue -> Stack) -> StackOperation ()
tStack3 f = f <$> popStack <*> popStack <*> popStack >>= prependStack
tStack4 :: (StackValue -> StackValue -> StackValue -> StackValue -> Stack)
-> StackOperation ()
tStack4 f = f <$> popStack <*> popStack <*> popStack <*> popStack
>>= prependStack
tStack6 :: (StackValue -> StackValue -> StackValue ->
StackValue -> StackValue -> StackValue -> Stack) -> StackOperation ()
tStack6 f = f <$> popStack <*> popStack <*> popStack
<*> popStack <*> popStack <*> popStack >>= prependStack
arith1 :: (Int64 -> Int64) -> StackOperation ()
arith1 f = do
i <- popInt
pushStack $ encodeInt (f i)
arith2 :: (Int64 -> Int64 -> Int64) -> StackOperation ()
arith2 f = do
i <- popInt
j <- popInt
pushStack $ encodeInt (f i j)
stackError :: StackOperation a
stackError = programError "stack error"
-- AltStack Primitives
pushAltStack :: StackValue -> StackOperation ()
pushAltStack op = modify $ \p -> p { altStack = op:altStack p }
popAltStack :: StackOperation StackValue
popAltStack = get >>= \p -> case altStack p of
a:as -> put p { altStack = as } >> return a
[] -> programError "popAltStack: empty stack"
incrementOpCount :: Int -> StackOperation ()
incrementOpCount i | i > maxOpcodes = programError "reached opcode limit"
| otherwise = modify $ \p -> p { opCount = i + 1 }
nopDiscourager :: StackOperation ()
nopDiscourager = do
flgs <- ask
when (DISCOURAGE_UPGRADABLE_NOPS `elem` flgs) $
programError "Discouraged OP used."
-- Instruction Evaluation
eval :: ScriptOp -> StackOperation ()
eval OP_NOP = return ()
eval OP_NOP1 = void nopDiscourager
eval OP_NOP2 = void nopDiscourager
eval OP_NOP3 = void nopDiscourager
eval OP_NOP4 = void nopDiscourager
eval OP_NOP5 = void nopDiscourager
eval OP_NOP6 = void nopDiscourager
eval OP_NOP7 = void nopDiscourager
eval OP_NOP8 = void nopDiscourager
eval OP_NOP9 = void nopDiscourager
eval OP_NOP10 = void nopDiscourager
eval OP_VERIFY = popBool >>= \case
True -> return ()
False -> programError "OP_VERIFY failed"
eval OP_RETURN = programError "explicit OP_RETURN"
-- Stack
eval OP_TOALTSTACK = popStack >>= pushAltStack
eval OP_FROMALTSTACK = popAltStack >>= pushStack
eval OP_IFDUP = tStack1 $ \a -> if decodeBool a then [a, a] else [a]
eval OP_DEPTH = getStack >>= pushStack . encodeInt . fromIntegral . length
eval OP_DROP = void popStack
eval OP_DUP = tStack1 $ \a -> [a, a]
eval OP_NIP = tStack2 $ \a _ -> [a]
eval OP_OVER = tStack2 $ \a b -> [b, a, b]
eval OP_PICK = popInt >>= (pickStack False . fromIntegral)
eval OP_ROLL = popInt >>= (pickStack True . fromIntegral)
eval OP_ROT = tStack3 $ \a b c -> [c, a, b]
eval OP_SWAP = tStack2 $ \a b -> [b, a]
eval OP_TUCK = tStack2 $ \a b -> [a, b, a]
eval OP_2DROP = tStack2 $ \_ _ -> []
eval OP_2DUP = tStack2 $ \a b -> [a, b, a, b]
eval OP_3DUP = tStack3 $ \a b c -> [a, b, c, a, b, c]
eval OP_2OVER = tStack4 $ \a b c d -> [c, d, a, b, c, d]
eval OP_2ROT = tStack6 $ \a b c d e f -> [e, f, a, b, c, d]
eval OP_2SWAP = tStack4 $ \a b c d -> [c, d, a, b]
-- Splice
eval OP_SIZE = (fromIntegral . length . head <$> withStack) >>= pushInt
-- Bitwise Logic
eval OP_EQUAL = tStack2 $ \a b -> [encodeBool (a == b)]
eval OP_EQUALVERIFY = eval OP_EQUAL >> eval OP_VERIFY
-- Arithmetic
eval OP_1ADD = arith1 (+1)
eval OP_1SUB = arith1 (subtract 1)
eval OP_NEGATE = arith1 negate
eval OP_ABS = arith1 abs
eval OP_NOT = arith1 $ \case 0 -> 1; _ -> 0
eval OP_0NOTEQUAL = arith1 $ \case 0 -> 0; _ -> 1
eval OP_ADD = arith2 (+)
eval OP_SUB = arith2 $ flip (-)
eval OP_BOOLAND = (&&) <$> ((0 /=) <$> popInt)
<*> ((0 /=) <$> popInt) >>= pushBool
eval OP_BOOLOR = (||) <$> ((0 /=) <$> popInt)
<*> ((0 /=) <$> popInt) >>= pushBool
eval OP_NUMEQUAL = (==) <$> popInt <*> popInt >>= pushBool
eval OP_NUMEQUALVERIFY = eval OP_NUMEQUAL >> eval OP_VERIFY
eval OP_NUMNOTEQUAL = (/=) <$> popInt <*> popInt >>= pushBool
eval OP_LESSTHAN = (>) <$> popInt <*> popInt >>= pushBool
eval OP_GREATERTHAN = (<) <$> popInt <*> popInt >>= pushBool
eval OP_LESSTHANOREQUAL = (>=) <$> popInt <*> popInt >>= pushBool
eval OP_GREATERTHANOREQUAL = (<=) <$> popInt <*> popInt >>= pushBool
eval OP_MIN = min <$> popInt <*> popInt >>= pushInt
eval OP_MAX = max <$> popInt <*> popInt >>= pushInt
eval OP_WITHIN = within <$> popInt <*> popInt <*> popInt >>= pushBool
where within y x a = (x <= a) && (a < y)
eval OP_RIPEMD160 = tStack1 $ return . bsToSv . encode . hash160 . opToSv
eval OP_SHA1 = tStack1 $ return . bsToSv . encode . hashSHA1 . opToSv
eval OP_SHA256 = tStack1 $ return . bsToSv . encode . hash256 . opToSv
eval OP_HASH160 = tStack1 $
return . bsToSv . encode . addressHash . opToSv
eval OP_HASH256 = tStack1 $
return . bsToSv . encode . doubleHash256 . opToSv
eval OP_CODESEPARATOR = dropHashOpsSeparatedCode
eval OP_CHECKSIG = do
pubKey <- popStack
sig <- popStack
checker <- sigCheck <$> get
hOps <- preparedHashOps
-- Reuse checkMultiSig code
pushBool $ checkMultiSig checker [ pubKey ] [ sig ] hOps
eval OP_CHECKMULTISIG =
do nPubKeys <- fromIntegral <$> popInt
when (nPubKeys < 0 || nPubKeys > maxKeysMultisig)
$ programError $ "nPubKeys outside range: " ++ show nPubKeys
pubKeys <- popStackN $ toInteger nPubKeys
nSigs <- fromIntegral <$> popInt
when (nSigs < 0 || nSigs > nPubKeys)
$ programError $ "nSigs outside range: " ++ show nSigs
sigs <- popStackN $ toInteger nSigs
nullDummyEnforcer
void popStack -- spec bug
checker <- sigCheck <$> get
hOps <- preparedHashOps
pushBool $ checkMultiSig checker pubKeys sigs hOps
modify $ \p -> p { opCount = opCount p + length pubKeys }
eval OP_CHECKSIGVERIFY = eval OP_CHECKSIG >> eval OP_VERIFY
eval OP_CHECKMULTISIGVERIFY = eval OP_CHECKMULTISIG >> eval OP_VERIFY
eval op = case constValue op of
Just sv -> minimalPushEnforcer op >> pushStack sv
Nothing -> programError $ "unexpected op " ++ show op
minimalPushEnforcer :: ScriptOp -> StackOperation ()
minimalPushEnforcer op = do
flgs <- ask
when (MINIMALDATA `elem` flgs) $
unless (checkMinimalPush op) $
programError $ "Non-minimal data: " ++ show op
checkMinimalPush :: ScriptOp -> Bool -- Putting in a maybe monad to avoid elif chain
checkMinimalPush ( OP_PUSHDATA payload optype ) =
let l = BS.length payload
v = head (BS.unpack payload)
in not $
BS.null payload -- Check if could have used OP_0
|| (l == 1 && v <= 16 && v >= 1) -- Could have used OP_{1,..,16}
|| (l == 1 && v == 0x81) -- Could have used OP_1NEGATE
|| (l <= 75 && optype /= OPCODE) -- Could have used direct push
|| (l <= 255 && l > 75 && optype /= OPDATA1)
|| (l > 255 && l <= 65535 && optype /= OPDATA2)
checkMinimalPush _ = True
-- | Checks the top of the stack for a minimal numeric representation
-- if flagged to do so
minimalStackValEnforcer :: StackOperation ()
minimalStackValEnforcer = do
flgs <- ask
s <- getStack
let topStack = if null s then [] else head s
when (MINIMALDATA `elem` flgs || null topStack) $
unless (checkMinimalNumRep topStack) $
programError $ "Non-minimal stack value: " ++ show topStack
-- | Checks if a stack value is the minimal numeric representation of
-- the integer to which it decoes. Based on CScriptNum from Bitcoin
-- Core.
checkMinimalNumRep :: StackValue -> Bool
checkMinimalNumRep [] = True
checkMinimalNumRep s =
let msb = last s
l = length s in
not $
-- If the MSB except sign bit is zero, then nonMinimal
( msb .&. 0x7f == 0 )
-- With the exception of when a new byte is forced by a filled last bit
&& ( l <= 1 || ( s !! (l-2) ) .&. 0x80 == 0 )
nullDummyEnforcer :: StackOperation ()
nullDummyEnforcer = do
flgs <- ask
topStack <- getStack >>= headOrError
when ((NULLDUMMY `elem` flgs) && (not . null $ topStack)) $
programError "Non-null dummy stack in multi-sig"
where
headOrError s =
if null s
then programError "Empty stack where dummy op should be."
else return $ head s
--------------------------------------------------------------------------------
-- | Based on the IfStack, returns whether the script is within an
-- evaluating if-branch.
getExec :: Program Bool
getExec = and <$> getCond
-- | Converts a `ScriptOp` to a ProgramData monad.
conditionalEval :: ScriptOp -> Program ()
conditionalEval scrpOp = do
-- lift $ checkOpEnabled scrpOp
lift $ checkPushData scrpOp
e <- getExec
eval' e scrpOp
when (countOp scrpOp) $ lift $ join $ incrementOpCount . opCount <$> get
lift checkStackSize
where
eval' :: Bool -> ScriptOp -> Program ()
eval' True OP_IF = lift popStack >>= pushCond . decodeBool
eval' True OP_NOTIF = lift popStack >>= pushCond . not . decodeBool
eval' True OP_ELSE = flipCond
eval' True OP_ENDIF = void popCond
eval' True op = lift $ eval op
eval' False OP_IF = pushCond False
eval' False OP_NOTIF = pushCond False
eval' False OP_ELSE = flipCond
eval' False OP_ENDIF = void popCond
eval' False OP_CODESEPARATOR = lift $ eval OP_CODESEPARATOR
eval' False OP_VER = return ()
eval' False op | isDisabled op = lift $ disabled op
| otherwise = return ()
-- | Builds a Script evaluation monad.
evalOps :: [ ScriptOp ] -> Program ()
evalOps ops = do mapM_ conditionalEval ops
cond <- getCond
unless (null cond) (lift $ programError "ifStack not empty")
checkPushOnly :: [ ScriptOp ] -> Program ()
checkPushOnly ops
| not (all checkPushOp ops) = lift $ programError "only push ops allowed"
| otherwise = return ()
where checkPushOp op = case constValue op of
Just _ -> True
Nothing -> False
checkStack :: Stack -> Bool
checkStack (x:_) = decodeBool x
checkStack [] = False
isPayToScriptHash :: [ ScriptOp ] -> [ Flag ] -> Bool
isPayToScriptHash [OP_HASH160, OP_PUSHDATA bytes OPCODE, OP_EQUAL] flgs
= ( P2SH `elem` flgs ) && ( BS.length bytes == 20 )
isPayToScriptHash _ _ = False
stackToScriptOps :: StackValue -> [ ScriptOp ]
stackToScriptOps sv = case decode $ BS.pack sv of
Left _ -> [] -- Maybe should propogate the error some how
Right s -> scriptOps s
-- exported functions
execScript :: Script -- ^ scriptSig ( redeemScript )
-> Script -- ^ scriptPubKey
-> SigCheck -- ^ signature verification Function
-> [ Flag ] -- ^ Evaluation flags
-> Either EvalError ProgramData
execScript scriptSig scriptPubKey sigCheckFcn flags =
let sigOps = scriptOps scriptSig
pubKeyOps = scriptOps scriptPubKey
initData = ProgramData {
stack = [],
altStack = [],
hashOps = pubKeyOps,
sigCheck = sigCheckFcn,
opCount = 0
}
checkSig | isPayToScriptHash pubKeyOps flags = checkPushOnly sigOps
| SIGPUSHONLY `elem` flags = checkPushOnly sigOps
| otherwise = return ()
checkKey
| BS.length (encode scriptPubKey) > fromIntegral maxScriptSize =
lift $ programError "pubKey > maxScriptSize"
| otherwise = return ()
redeemEval = checkSig >> evalOps sigOps >> lift (stack <$> get)
pubKeyEval = checkKey >> evalOps pubKeyOps >> lift get
in do s <- evalProgram redeemEval [] initData flags
p <- evalProgram pubKeyEval [] initData { stack = s } flags
if not (null s)
&& isPayToScriptHash pubKeyOps flags
&& checkStack (runStack p)
then evalProgram (evalP2SH s) [] initData { stack = drop 1 s,
hashOps = stackToScriptOps $ head s } flags
else return p
-- | Evaluates a P2SH style script from its serialization in the stack
evalP2SH :: Stack -> Program ProgramData
evalP2SH [] = lift $ programError "PayToScriptHash: no script on stack"
evalP2SH (sv:_) = evalOps (stackToScriptOps sv) >> lift get
evalScript :: Script -> Script -> SigCheck -> [ Flag ] -> Bool
evalScript scriptSig scriptPubKey sigCheckFcn flags =
case execScript scriptSig scriptPubKey sigCheckFcn flags of
Left _ -> False
Right p -> checkStack . runStack $ p
runStack :: ProgramData -> Stack
runStack = stack
-- | A wrapper around 'verifySig' which handles grabbing the hash type
verifySigWithType :: Tx -> Int -> [ ScriptOp ] -> TxSignature -> PubKey -> Bool
verifySigWithType tx i outOps txSig pubKey =
let outScript = Script outOps
h = txSigHash tx outScript i ( sigHashType txSig ) in
verifySig h ( txSignature txSig ) pubKey
-- | Uses `evalScript` to check that the input script of a spending
-- transaction satisfies the output script.
verifySpend :: Tx -- ^ The spending transaction
-> Int -- ^ The input index
-> Script -- ^ The output script we are spending
-> [Flag] -- ^ Evaluation flags
-> Bool
verifySpend tx i outscript flags =
let scriptSig = either err id . decode . scriptInput $ txIn tx !! i
verifyFcn = verifySigWithType tx i
err e = error $ "Could not decode scriptInput in verifySpend: " ++ e
in evalScript scriptSig outscript verifyFcn flags
| plaprade/haskoin | haskoin-core/src/Network/Haskoin/Script/Evaluator.hs | unlicense | 29,108 | 0 | 17 | 8,251 | 7,845 | 4,040 | 3,805 | 575 | 20 |
module Data.P440.Domain.APZ where
import Data.P440.Domain.SimpleTypes
import Data.P440.Domain.ComplexTypes
import Data.Text (Text)
-- 2.7 Отзыв инкассового поручения
data Файл = Файл {
идЭС :: GUID
,типИнф :: Text
,версПрог :: Text
,телОтпр :: Text
,должнОтпр :: Text
,фамОтпр :: Text
,версФорм :: Text
,решенотзпор :: РЕШЕНОТЗПОР
} deriving (Eq, Show)
data РЕШЕНОТЗПОР = РЕШЕНОТЗПОР {
номРеш :: Text
,датаПодп :: Date
,банкПл :: Text
,бикбПл :: БИК
,инннп :: Text
,кппнп :: Maybe КПП
,сумма :: Maybe Text
,отозвПоруч :: [ОтозвПоруч]
,свНО :: СвНО
,руководитель :: РукНО
} deriving (Eq, Show)
data ОтозвПоруч = ОтозвПоруч {
номПоруч :: Text
,датаПоруч :: Date
,видПоруч :: Text
,номСчПл :: Text
,видСч :: Text
} deriving (Eq, Show)
| Macil-dev/p440 | src/Data/P440/Domain/APZ.hs | unlicense | 1,197 | 50 | 8 | 303 | 500 | 274 | 226 | 33 | 0 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
------------------------------------------------------------------------------
-- | This module defines our application's state type and an alias for its
-- handler monad.
module Application where
------------------------------------------------------------------------------
import Control.Lens
import Snap
import Snap.Snaplet
import Snap.Snaplet.Heist
import Snap.Snaplet.Auth
import Snap.Snaplet.Session
import Snap.Snaplet.SqliteSimple
------------------------------------------------------------------------------
data App = App
{ _heist :: Snaplet (Heist App)
, _sess :: Snaplet SessionManager
, _db :: Snaplet Sqlite
, _auth :: Snaplet (AuthManager App)
}
makeLenses ''App
instance HasHeist App where
heistLens = subSnaplet heist
instance HasSqlite (Handler b App) where
getSqliteState = with db get
------------------------------------------------------------------------------
type AppHandler = Handler App App
| santolucito/Peers | src/Application.hs | apache-2.0 | 1,096 | 0 | 11 | 148 | 169 | 98 | 71 | 23 | 0 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGLWidget.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:32
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Opengl.QGLWidget (
QqGLWidget(..)
,QautoBufferSwap(..)
,colormap
,qGLWidgetConvertToGLFormat, qGLWidgetConvertToGLFormat_nf
,QfontDisplayListBase(..)
,QglDraw(..)
,QglInit(..)
,QgrabFrameBuffer(..), QgrabFrameBuffer_nf(..)
,QinitializeGL(..)
,QinitializeOverlayGL(..)
,makeOverlayCurrent
,overlayContext
,QpaintGL(..)
,QpaintOverlayGL(..)
,qglClearColor
,qglColor
,QrenderPixmap(..), QrenderPixmap_nf(..)
,QrenderText(..)
,QresizeGL(..)
,QresizeOverlayGL(..)
,QsetAutoBufferSwap(..)
,setColormap
,QupdateGL(..)
,QupdateOverlayGL(..)
,qGLWidget_delete
,qGLWidget_deleteLater
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
import Qtc.Classes.Opengl
import Qtc.ClassTypes.Opengl
instance QuserMethod (QGLWidget ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QGLWidget_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QGLWidget_userMethod" qtc_QGLWidget_userMethod :: Ptr (TQGLWidget a) -> CInt -> IO ()
instance QuserMethod (QGLWidgetSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QGLWidget_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QGLWidget ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QGLWidget_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QGLWidget_userMethodVariant" qtc_QGLWidget_userMethodVariant :: Ptr (TQGLWidget a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QGLWidgetSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QGLWidget_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqGLWidget x1 where
qGLWidget :: x1 -> IO (QGLWidget ())
instance QqGLWidget (()) where
qGLWidget ()
= withQGLWidgetResult $
qtc_QGLWidget
foreign import ccall "qtc_QGLWidget" qtc_QGLWidget :: IO (Ptr (TQGLWidget ()))
instance QqGLWidget ((QWidget t1)) where
qGLWidget (x1)
= withQGLWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget1 cobj_x1
foreign import ccall "qtc_QGLWidget1" qtc_QGLWidget1 :: Ptr (TQWidget t1) -> IO (Ptr (TQGLWidget ()))
instance QqGLWidget ((QGLContext t1)) where
qGLWidget (x1)
= withQGLWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget2 cobj_x1
foreign import ccall "qtc_QGLWidget2" qtc_QGLWidget2 :: Ptr (TQGLContext t1) -> IO (Ptr (TQGLWidget ()))
instance QqGLWidget ((QGLFormat t1)) where
qGLWidget (x1)
= withQGLWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget3 cobj_x1
foreign import ccall "qtc_QGLWidget3" qtc_QGLWidget3 :: Ptr (TQGLFormat t1) -> IO (Ptr (TQGLWidget ()))
instance QqGLWidget ((QGLContext t1, QWidget t2)) where
qGLWidget (x1, x2)
= withQGLWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLWidget4 cobj_x1 cobj_x2
foreign import ccall "qtc_QGLWidget4" qtc_QGLWidget4 :: Ptr (TQGLContext t1) -> Ptr (TQWidget t2) -> IO (Ptr (TQGLWidget ()))
instance QqGLWidget ((QGLFormat t1, QWidget t2)) where
qGLWidget (x1, x2)
= withQGLWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLWidget5 cobj_x1 cobj_x2
foreign import ccall "qtc_QGLWidget5" qtc_QGLWidget5 :: Ptr (TQGLFormat t1) -> Ptr (TQWidget t2) -> IO (Ptr (TQGLWidget ()))
instance QqGLWidget ((QWidget t1, QGLWidget t2, WindowFlags)) where
qGLWidget (x1, x2, x3)
= withQGLWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLWidget6 cobj_x1 cobj_x2 (toCLong $ qFlags_toInt x3)
foreign import ccall "qtc_QGLWidget6" qtc_QGLWidget6 :: Ptr (TQWidget t1) -> Ptr (TQGLWidget t2) -> CLong -> IO (Ptr (TQGLWidget ()))
instance QqGLWidget ((QGLContext t1, QWidget t2, QGLWidget t3, WindowFlags)) where
qGLWidget (x1, x2, x3, x4)
= withQGLWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGLWidget7 cobj_x1 cobj_x2 cobj_x3 (toCLong $ qFlags_toInt x4)
foreign import ccall "qtc_QGLWidget7" qtc_QGLWidget7 :: Ptr (TQGLContext t1) -> Ptr (TQWidget t2) -> Ptr (TQGLWidget t3) -> CLong -> IO (Ptr (TQGLWidget ()))
instance QqGLWidget ((QGLFormat t1, QWidget t2, QGLWidget t3, WindowFlags)) where
qGLWidget (x1, x2, x3, x4)
= withQGLWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGLWidget8 cobj_x1 cobj_x2 cobj_x3 (toCLong $ qFlags_toInt x4)
foreign import ccall "qtc_QGLWidget8" qtc_QGLWidget8 :: Ptr (TQGLFormat t1) -> Ptr (TQWidget t2) -> Ptr (TQGLWidget t3) -> CLong -> IO (Ptr (TQGLWidget ()))
class QautoBufferSwap x0 x1 where
autoBufferSwap :: x0 -> x1 -> IO (Bool)
instance QautoBufferSwap (QGLWidget ()) (()) where
autoBufferSwap x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_autoBufferSwap cobj_x0
foreign import ccall "qtc_QGLWidget_autoBufferSwap" qtc_QGLWidget_autoBufferSwap :: Ptr (TQGLWidget a) -> IO CBool
instance QautoBufferSwap (QGLWidgetSc a) (()) where
autoBufferSwap x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_autoBufferSwap cobj_x0
instance QbindTexture (QGLWidget a) ((QImage t1)) where
bindTexture x0 (x1)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_bindTexture2 cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_bindTexture2" qtc_QGLWidget_bindTexture2 :: Ptr (TQGLWidget a) -> Ptr (TQImage t1) -> IO CUInt
instance QbindTexture (QGLWidget a) ((QImage t1, Int)) where
bindTexture x0 (x1, x2)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_bindTexture3 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QGLWidget_bindTexture3" qtc_QGLWidget_bindTexture3 :: Ptr (TQGLWidget a) -> Ptr (TQImage t1) -> CInt -> IO CUInt
instance QbindTexture (QGLWidget a) ((QImage t1, Int, Int)) where
bindTexture x0 (x1, x2, x3)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_bindTexture5 cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QGLWidget_bindTexture5" qtc_QGLWidget_bindTexture5 :: Ptr (TQGLWidget a) -> Ptr (TQImage t1) -> CInt -> CInt -> IO CUInt
instance QbindTexture (QGLWidget a) ((QPixmap t1)) where
bindTexture x0 (x1)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_bindTexture1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_bindTexture1" qtc_QGLWidget_bindTexture1 :: Ptr (TQGLWidget a) -> Ptr (TQPixmap t1) -> IO CUInt
instance QbindTexture (QGLWidget a) ((QPixmap t1, Int)) where
bindTexture x0 (x1, x2)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_bindTexture4 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QGLWidget_bindTexture4" qtc_QGLWidget_bindTexture4 :: Ptr (TQGLWidget a) -> Ptr (TQPixmap t1) -> CInt -> IO CUInt
instance QbindTexture (QGLWidget a) ((QPixmap t1, Int, Int)) where
bindTexture x0 (x1, x2, x3)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_bindTexture6 cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QGLWidget_bindTexture6" qtc_QGLWidget_bindTexture6 :: Ptr (TQGLWidget a) -> Ptr (TQPixmap t1) -> CInt -> CInt -> IO CUInt
instance QbindTexture (QGLWidget a) ((String)) where
bindTexture x0 (x1)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGLWidget_bindTexture cobj_x0 cstr_x1
foreign import ccall "qtc_QGLWidget_bindTexture" qtc_QGLWidget_bindTexture :: Ptr (TQGLWidget a) -> CWString -> IO CUInt
colormap :: QGLWidget a -> (()) -> IO (QGLColormap ())
colormap x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_colormap cobj_x0
foreign import ccall "qtc_QGLWidget_colormap" qtc_QGLWidget_colormap :: Ptr (TQGLWidget a) -> IO (Ptr (TQGLColormap ()))
instance Qcontext (QGLWidget a) (()) (IO (QGLContext ())) where
context x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_context cobj_x0
foreign import ccall "qtc_QGLWidget_context" qtc_QGLWidget_context :: Ptr (TQGLWidget a) -> IO (Ptr (TQGLContext ()))
qGLWidgetConvertToGLFormat :: ((QImage t1)) -> IO (QImage ())
qGLWidgetConvertToGLFormat (x1)
= withQImageResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_convertToGLFormat cobj_x1
foreign import ccall "qtc_QGLWidget_convertToGLFormat" qtc_QGLWidget_convertToGLFormat :: Ptr (TQImage t1) -> IO (Ptr (TQImage ()))
qGLWidgetConvertToGLFormat_nf :: ((QImage t1)) -> IO (QImage ())
qGLWidgetConvertToGLFormat_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_convertToGLFormat cobj_x1
instance QdeleteTexture (QGLWidget a) ((Int)) where
deleteTexture x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_deleteTexture cobj_x0 (toCUInt x1)
foreign import ccall "qtc_QGLWidget_deleteTexture" qtc_QGLWidget_deleteTexture :: Ptr (TQGLWidget a) -> CUInt -> IO ()
instance QdoneCurrent (QGLWidget a) (()) (IO ()) where
doneCurrent x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_doneCurrent cobj_x0
foreign import ccall "qtc_QGLWidget_doneCurrent" qtc_QGLWidget_doneCurrent :: Ptr (TQGLWidget a) -> IO ()
instance QdoubleBuffer (QGLWidget a) (()) where
doubleBuffer x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_doubleBuffer cobj_x0
foreign import ccall "qtc_QGLWidget_doubleBuffer" qtc_QGLWidget_doubleBuffer :: Ptr (TQGLWidget a) -> IO CBool
instance Qevent (QGLWidget ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_event_h" qtc_QGLWidget_event_h :: Ptr (TQGLWidget a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QGLWidgetSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_event_h cobj_x0 cobj_x1
class QfontDisplayListBase x0 x1 where
fontDisplayListBase :: x0 -> x1 -> IO (Int)
instance QfontDisplayListBase (QGLWidget ()) ((QFont t1)) where
fontDisplayListBase x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_fontDisplayListBase cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_fontDisplayListBase" qtc_QGLWidget_fontDisplayListBase :: Ptr (TQGLWidget a) -> Ptr (TQFont t1) -> IO CInt
instance QfontDisplayListBase (QGLWidgetSc a) ((QFont t1)) where
fontDisplayListBase x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_fontDisplayListBase cobj_x0 cobj_x1
instance QfontDisplayListBase (QGLWidget ()) ((QFont t1, Int)) where
fontDisplayListBase x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_fontDisplayListBase1 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QGLWidget_fontDisplayListBase1" qtc_QGLWidget_fontDisplayListBase1 :: Ptr (TQGLWidget a) -> Ptr (TQFont t1) -> CInt -> IO CInt
instance QfontDisplayListBase (QGLWidgetSc a) ((QFont t1, Int)) where
fontDisplayListBase x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_fontDisplayListBase1 cobj_x0 cobj_x1 (toCInt x2)
instance Qformat (QGLWidget a) (()) (IO (QGLFormat ())) where
format x0 ()
= withQGLFormatResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_format cobj_x0
foreign import ccall "qtc_QGLWidget_format" qtc_QGLWidget_format :: Ptr (TQGLWidget a) -> IO (Ptr (TQGLFormat ()))
class QglDraw x0 x1 where
glDraw :: x0 -> x1 -> IO ()
instance QglDraw (QGLWidget ()) (()) where
glDraw x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_glDraw_h cobj_x0
foreign import ccall "qtc_QGLWidget_glDraw_h" qtc_QGLWidget_glDraw_h :: Ptr (TQGLWidget a) -> IO ()
instance QglDraw (QGLWidgetSc a) (()) where
glDraw x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_glDraw_h cobj_x0
class QglInit x0 x1 where
glInit :: x0 -> x1 -> IO ()
instance QglInit (QGLWidget ()) (()) where
glInit x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_glInit_h cobj_x0
foreign import ccall "qtc_QGLWidget_glInit_h" qtc_QGLWidget_glInit_h :: Ptr (TQGLWidget a) -> IO ()
instance QglInit (QGLWidgetSc a) (()) where
glInit x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_glInit_h cobj_x0
class QgrabFrameBuffer x0 x1 where
grabFrameBuffer :: x0 -> x1 -> IO (QImage ())
class QgrabFrameBuffer_nf x0 x1 where
grabFrameBuffer_nf :: x0 -> x1 -> IO (QImage ())
instance QgrabFrameBuffer (QGLWidget ()) (()) where
grabFrameBuffer x0 ()
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_grabFrameBuffer cobj_x0
foreign import ccall "qtc_QGLWidget_grabFrameBuffer" qtc_QGLWidget_grabFrameBuffer :: Ptr (TQGLWidget a) -> IO (Ptr (TQImage ()))
instance QgrabFrameBuffer (QGLWidgetSc a) (()) where
grabFrameBuffer x0 ()
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_grabFrameBuffer cobj_x0
instance QgrabFrameBuffer_nf (QGLWidget ()) (()) where
grabFrameBuffer_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_grabFrameBuffer cobj_x0
instance QgrabFrameBuffer_nf (QGLWidgetSc a) (()) where
grabFrameBuffer_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_grabFrameBuffer cobj_x0
instance QgrabFrameBuffer (QGLWidget ()) ((Bool)) where
grabFrameBuffer x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_grabFrameBuffer1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLWidget_grabFrameBuffer1" qtc_QGLWidget_grabFrameBuffer1 :: Ptr (TQGLWidget a) -> CBool -> IO (Ptr (TQImage ()))
instance QgrabFrameBuffer (QGLWidgetSc a) ((Bool)) where
grabFrameBuffer x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_grabFrameBuffer1 cobj_x0 (toCBool x1)
instance QgrabFrameBuffer_nf (QGLWidget ()) ((Bool)) where
grabFrameBuffer_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_grabFrameBuffer1 cobj_x0 (toCBool x1)
instance QgrabFrameBuffer_nf (QGLWidgetSc a) ((Bool)) where
grabFrameBuffer_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_grabFrameBuffer1 cobj_x0 (toCBool x1)
class QinitializeGL x0 x1 where
initializeGL :: x0 -> x1 -> IO ()
instance QinitializeGL (QGLWidget ()) (()) where
initializeGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_initializeGL_h cobj_x0
foreign import ccall "qtc_QGLWidget_initializeGL_h" qtc_QGLWidget_initializeGL_h :: Ptr (TQGLWidget a) -> IO ()
instance QinitializeGL (QGLWidgetSc a) (()) where
initializeGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_initializeGL_h cobj_x0
class QinitializeOverlayGL x0 x1 where
initializeOverlayGL :: x0 -> x1 -> IO ()
instance QinitializeOverlayGL (QGLWidget ()) (()) where
initializeOverlayGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_initializeOverlayGL_h cobj_x0
foreign import ccall "qtc_QGLWidget_initializeOverlayGL_h" qtc_QGLWidget_initializeOverlayGL_h :: Ptr (TQGLWidget a) -> IO ()
instance QinitializeOverlayGL (QGLWidgetSc a) (()) where
initializeOverlayGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_initializeOverlayGL_h cobj_x0
instance QisSharing (QGLWidget a) (()) where
isSharing x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_isSharing cobj_x0
foreign import ccall "qtc_QGLWidget_isSharing" qtc_QGLWidget_isSharing :: Ptr (TQGLWidget a) -> IO CBool
instance QqisValid (QGLWidget ()) (()) where
qisValid x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_isValid cobj_x0
foreign import ccall "qtc_QGLWidget_isValid" qtc_QGLWidget_isValid :: Ptr (TQGLWidget a) -> IO CBool
instance QqisValid (QGLWidgetSc a) (()) where
qisValid x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_isValid cobj_x0
instance QmakeCurrent (QGLWidget a) (()) (IO ()) where
makeCurrent x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_makeCurrent cobj_x0
foreign import ccall "qtc_QGLWidget_makeCurrent" qtc_QGLWidget_makeCurrent :: Ptr (TQGLWidget a) -> IO ()
makeOverlayCurrent :: QGLWidget a -> (()) -> IO ()
makeOverlayCurrent x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_makeOverlayCurrent cobj_x0
foreign import ccall "qtc_QGLWidget_makeOverlayCurrent" qtc_QGLWidget_makeOverlayCurrent :: Ptr (TQGLWidget a) -> IO ()
overlayContext :: QGLWidget a -> (()) -> IO (QGLContext ())
overlayContext x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_overlayContext cobj_x0
foreign import ccall "qtc_QGLWidget_overlayContext" qtc_QGLWidget_overlayContext :: Ptr (TQGLWidget a) -> IO (Ptr (TQGLContext ()))
instance QpaintEngine (QGLWidget ()) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_paintEngine_h cobj_x0
foreign import ccall "qtc_QGLWidget_paintEngine_h" qtc_QGLWidget_paintEngine_h :: Ptr (TQGLWidget a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine (QGLWidgetSc a) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_paintEngine_h cobj_x0
instance QpaintEvent (QGLWidget ()) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_paintEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_paintEvent_h" qtc_QGLWidget_paintEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent (QGLWidgetSc a) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_paintEvent_h cobj_x0 cobj_x1
class QpaintGL x0 x1 where
paintGL :: x0 -> x1 -> IO ()
instance QpaintGL (QGLWidget ()) (()) where
paintGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_paintGL_h cobj_x0
foreign import ccall "qtc_QGLWidget_paintGL_h" qtc_QGLWidget_paintGL_h :: Ptr (TQGLWidget a) -> IO ()
instance QpaintGL (QGLWidgetSc a) (()) where
paintGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_paintGL_h cobj_x0
class QpaintOverlayGL x0 x1 where
paintOverlayGL :: x0 -> x1 -> IO ()
instance QpaintOverlayGL (QGLWidget ()) (()) where
paintOverlayGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_paintOverlayGL_h cobj_x0
foreign import ccall "qtc_QGLWidget_paintOverlayGL_h" qtc_QGLWidget_paintOverlayGL_h :: Ptr (TQGLWidget a) -> IO ()
instance QpaintOverlayGL (QGLWidgetSc a) (()) where
paintOverlayGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_paintOverlayGL_h cobj_x0
qglClearColor :: QGLWidget a -> ((QColor t1)) -> IO ()
qglClearColor x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_qglClearColor cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_qglClearColor" qtc_QGLWidget_qglClearColor :: Ptr (TQGLWidget a) -> Ptr (TQColor t1) -> IO ()
qglColor :: QGLWidget a -> ((QColor t1)) -> IO ()
qglColor x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_qglColor cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_qglColor" qtc_QGLWidget_qglColor :: Ptr (TQGLWidget a) -> Ptr (TQColor t1) -> IO ()
class QrenderPixmap x0 x1 where
renderPixmap :: x0 -> x1 -> IO (QPixmap ())
class QrenderPixmap_nf x0 x1 where
renderPixmap_nf :: x0 -> x1 -> IO (QPixmap ())
instance QrenderPixmap (QGLWidget ()) (()) where
renderPixmap x0 ()
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap cobj_x0
foreign import ccall "qtc_QGLWidget_renderPixmap" qtc_QGLWidget_renderPixmap :: Ptr (TQGLWidget a) -> IO (Ptr (TQPixmap ()))
instance QrenderPixmap (QGLWidgetSc a) (()) where
renderPixmap x0 ()
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap cobj_x0
instance QrenderPixmap_nf (QGLWidget ()) (()) where
renderPixmap_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap cobj_x0
instance QrenderPixmap_nf (QGLWidgetSc a) (()) where
renderPixmap_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap cobj_x0
instance QrenderPixmap (QGLWidget ()) ((Int)) where
renderPixmap x0 (x1)
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap1 cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGLWidget_renderPixmap1" qtc_QGLWidget_renderPixmap1 :: Ptr (TQGLWidget a) -> CInt -> IO (Ptr (TQPixmap ()))
instance QrenderPixmap (QGLWidgetSc a) ((Int)) where
renderPixmap x0 (x1)
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap1 cobj_x0 (toCInt x1)
instance QrenderPixmap_nf (QGLWidget ()) ((Int)) where
renderPixmap_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap1 cobj_x0 (toCInt x1)
instance QrenderPixmap_nf (QGLWidgetSc a) ((Int)) where
renderPixmap_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap1 cobj_x0 (toCInt x1)
instance QrenderPixmap (QGLWidget ()) ((Int, Int)) where
renderPixmap x0 (x1, x2)
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap2 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QGLWidget_renderPixmap2" qtc_QGLWidget_renderPixmap2 :: Ptr (TQGLWidget a) -> CInt -> CInt -> IO (Ptr (TQPixmap ()))
instance QrenderPixmap (QGLWidgetSc a) ((Int, Int)) where
renderPixmap x0 (x1, x2)
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap2 cobj_x0 (toCInt x1) (toCInt x2)
instance QrenderPixmap_nf (QGLWidget ()) ((Int, Int)) where
renderPixmap_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap2 cobj_x0 (toCInt x1) (toCInt x2)
instance QrenderPixmap_nf (QGLWidgetSc a) ((Int, Int)) where
renderPixmap_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap2 cobj_x0 (toCInt x1) (toCInt x2)
instance QrenderPixmap (QGLWidget ()) ((Int, Int, Bool)) where
renderPixmap x0 (x1, x2, x3)
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap3 cobj_x0 (toCInt x1) (toCInt x2) (toCBool x3)
foreign import ccall "qtc_QGLWidget_renderPixmap3" qtc_QGLWidget_renderPixmap3 :: Ptr (TQGLWidget a) -> CInt -> CInt -> CBool -> IO (Ptr (TQPixmap ()))
instance QrenderPixmap (QGLWidgetSc a) ((Int, Int, Bool)) where
renderPixmap x0 (x1, x2, x3)
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap3 cobj_x0 (toCInt x1) (toCInt x2) (toCBool x3)
instance QrenderPixmap_nf (QGLWidget ()) ((Int, Int, Bool)) where
renderPixmap_nf x0 (x1, x2, x3)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap3 cobj_x0 (toCInt x1) (toCInt x2) (toCBool x3)
instance QrenderPixmap_nf (QGLWidgetSc a) ((Int, Int, Bool)) where
renderPixmap_nf x0 (x1, x2, x3)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap3 cobj_x0 (toCInt x1) (toCInt x2) (toCBool x3)
class QrenderText x1 where
renderText :: QGLWidget a -> x1 -> IO ()
instance QrenderText ((Double, Double, Double, String)) where
renderText x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x4 $ \cstr_x4 ->
qtc_QGLWidget_renderText2 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) cstr_x4
foreign import ccall "qtc_QGLWidget_renderText2" qtc_QGLWidget_renderText2 :: Ptr (TQGLWidget a) -> CDouble -> CDouble -> CDouble -> CWString -> IO ()
instance QrenderText ((Double, Double, Double, String, QFont t5)) where
renderText x0 (x1, x2, x3, x4, x5)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x4 $ \cstr_x4 ->
withObjectPtr x5 $ \cobj_x5 ->
qtc_QGLWidget_renderText3 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) cstr_x4 cobj_x5
foreign import ccall "qtc_QGLWidget_renderText3" qtc_QGLWidget_renderText3 :: Ptr (TQGLWidget a) -> CDouble -> CDouble -> CDouble -> CWString -> Ptr (TQFont t5) -> IO ()
instance QrenderText ((Double, Double, Double, String, QFont t5, Int)) where
renderText x0 (x1, x2, x3, x4, x5, x6)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x4 $ \cstr_x4 ->
withObjectPtr x5 $ \cobj_x5 ->
qtc_QGLWidget_renderText5 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) cstr_x4 cobj_x5 (toCInt x6)
foreign import ccall "qtc_QGLWidget_renderText5" qtc_QGLWidget_renderText5 :: Ptr (TQGLWidget a) -> CDouble -> CDouble -> CDouble -> CWString -> Ptr (TQFont t5) -> CInt -> IO ()
instance QrenderText ((Int, Int, String)) where
renderText x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x3 $ \cstr_x3 ->
qtc_QGLWidget_renderText cobj_x0 (toCInt x1) (toCInt x2) cstr_x3
foreign import ccall "qtc_QGLWidget_renderText" qtc_QGLWidget_renderText :: Ptr (TQGLWidget a) -> CInt -> CInt -> CWString -> IO ()
instance QrenderText ((Int, Int, String, QFont t4)) where
renderText x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x3 $ \cstr_x3 ->
withObjectPtr x4 $ \cobj_x4 ->
qtc_QGLWidget_renderText1 cobj_x0 (toCInt x1) (toCInt x2) cstr_x3 cobj_x4
foreign import ccall "qtc_QGLWidget_renderText1" qtc_QGLWidget_renderText1 :: Ptr (TQGLWidget a) -> CInt -> CInt -> CWString -> Ptr (TQFont t4) -> IO ()
instance QrenderText ((Int, Int, String, QFont t4, Int)) where
renderText x0 (x1, x2, x3, x4, x5)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x3 $ \cstr_x3 ->
withObjectPtr x4 $ \cobj_x4 ->
qtc_QGLWidget_renderText4 cobj_x0 (toCInt x1) (toCInt x2) cstr_x3 cobj_x4 (toCInt x5)
foreign import ccall "qtc_QGLWidget_renderText4" qtc_QGLWidget_renderText4 :: Ptr (TQGLWidget a) -> CInt -> CInt -> CWString -> Ptr (TQFont t4) -> CInt -> IO ()
instance QresizeEvent (QGLWidget ()) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_resizeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_resizeEvent_h" qtc_QGLWidget_resizeEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent (QGLWidgetSc a) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_resizeEvent_h cobj_x0 cobj_x1
class QresizeGL x0 x1 where
resizeGL :: x0 -> x1 -> IO ()
instance QresizeGL (QGLWidget ()) ((Int, Int)) where
resizeGL x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_resizeGL_h cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QGLWidget_resizeGL_h" qtc_QGLWidget_resizeGL_h :: Ptr (TQGLWidget a) -> CInt -> CInt -> IO ()
instance QresizeGL (QGLWidgetSc a) ((Int, Int)) where
resizeGL x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_resizeGL_h cobj_x0 (toCInt x1) (toCInt x2)
class QresizeOverlayGL x0 x1 where
resizeOverlayGL :: x0 -> x1 -> IO ()
instance QresizeOverlayGL (QGLWidget ()) ((Int, Int)) where
resizeOverlayGL x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_resizeOverlayGL_h cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QGLWidget_resizeOverlayGL_h" qtc_QGLWidget_resizeOverlayGL_h :: Ptr (TQGLWidget a) -> CInt -> CInt -> IO ()
instance QresizeOverlayGL (QGLWidgetSc a) ((Int, Int)) where
resizeOverlayGL x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_resizeOverlayGL_h cobj_x0 (toCInt x1) (toCInt x2)
class QsetAutoBufferSwap x0 x1 where
setAutoBufferSwap :: x0 -> x1 -> IO ()
instance QsetAutoBufferSwap (QGLWidget ()) ((Bool)) where
setAutoBufferSwap x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_setAutoBufferSwap cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLWidget_setAutoBufferSwap" qtc_QGLWidget_setAutoBufferSwap :: Ptr (TQGLWidget a) -> CBool -> IO ()
instance QsetAutoBufferSwap (QGLWidgetSc a) ((Bool)) where
setAutoBufferSwap x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_setAutoBufferSwap cobj_x0 (toCBool x1)
setColormap :: QGLWidget a -> ((QGLColormap t1)) -> IO ()
setColormap x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_setColormap cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_setColormap" qtc_QGLWidget_setColormap :: Ptr (TQGLWidget a) -> Ptr (TQGLColormap t1) -> IO ()
instance QsetContext (QGLWidget a) ((QGLContext t1)) where
setContext x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_setContext cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_setContext" qtc_QGLWidget_setContext :: Ptr (TQGLWidget a) -> Ptr (TQGLContext t1) -> IO ()
instance QsetContext (QGLWidget a) ((QGLContext t1, QGLContext t2)) where
setContext x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLWidget_setContext1 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGLWidget_setContext1" qtc_QGLWidget_setContext1 :: Ptr (TQGLWidget a) -> Ptr (TQGLContext t1) -> Ptr (TQGLContext t2) -> IO ()
instance QsetContext (QGLWidget a) ((QGLContext t1, QGLContext t2, Bool)) where
setContext x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLWidget_setContext2 cobj_x0 cobj_x1 cobj_x2 (toCBool x3)
foreign import ccall "qtc_QGLWidget_setContext2" qtc_QGLWidget_setContext2 :: Ptr (TQGLWidget a) -> Ptr (TQGLContext t1) -> Ptr (TQGLContext t2) -> CBool -> IO ()
instance QsetFormat (QGLWidget a) ((QGLFormat t1)) where
setFormat x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_setFormat cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_setFormat" qtc_QGLWidget_setFormat :: Ptr (TQGLWidget a) -> Ptr (TQGLFormat t1) -> IO ()
instance QsetMouseTracking (QGLWidget ()) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_setMouseTracking cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLWidget_setMouseTracking" qtc_QGLWidget_setMouseTracking :: Ptr (TQGLWidget a) -> CBool -> IO ()
instance QsetMouseTracking (QGLWidgetSc a) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_setMouseTracking cobj_x0 (toCBool x1)
instance QswapBuffers (QGLWidget a) (()) where
swapBuffers x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_swapBuffers cobj_x0
foreign import ccall "qtc_QGLWidget_swapBuffers" qtc_QGLWidget_swapBuffers :: Ptr (TQGLWidget a) -> IO ()
class QupdateGL x0 x1 where
updateGL :: x0 -> x1 -> IO ()
instance QupdateGL (QGLWidget ()) (()) where
updateGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_updateGL_h cobj_x0
foreign import ccall "qtc_QGLWidget_updateGL_h" qtc_QGLWidget_updateGL_h :: Ptr (TQGLWidget a) -> IO ()
instance QupdateGL (QGLWidgetSc a) (()) where
updateGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_updateGL_h cobj_x0
class QupdateOverlayGL x0 x1 where
updateOverlayGL :: x0 -> x1 -> IO ()
instance QupdateOverlayGL (QGLWidget ()) (()) where
updateOverlayGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_updateOverlayGL_h cobj_x0
foreign import ccall "qtc_QGLWidget_updateOverlayGL_h" qtc_QGLWidget_updateOverlayGL_h :: Ptr (TQGLWidget a) -> IO ()
instance QupdateOverlayGL (QGLWidgetSc a) (()) where
updateOverlayGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_updateOverlayGL_h cobj_x0
qGLWidget_delete :: QGLWidget a -> IO ()
qGLWidget_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_delete cobj_x0
foreign import ccall "qtc_QGLWidget_delete" qtc_QGLWidget_delete :: Ptr (TQGLWidget a) -> IO ()
qGLWidget_deleteLater :: QGLWidget a -> IO ()
qGLWidget_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_deleteLater cobj_x0
foreign import ccall "qtc_QGLWidget_deleteLater" qtc_QGLWidget_deleteLater :: Ptr (TQGLWidget a) -> IO ()
instance QactionEvent (QGLWidget ()) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_actionEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_actionEvent_h" qtc_QGLWidget_actionEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent (QGLWidgetSc a) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_actionEvent_h cobj_x0 cobj_x1
instance QaddAction (QGLWidget ()) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_addAction cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_addAction" qtc_QGLWidget_addAction :: Ptr (TQGLWidget a) -> Ptr (TQAction t1) -> IO ()
instance QaddAction (QGLWidgetSc a) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_addAction cobj_x0 cobj_x1
instance QchangeEvent (QGLWidget ()) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_changeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_changeEvent_h" qtc_QGLWidget_changeEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent (QGLWidgetSc a) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_changeEvent_h cobj_x0 cobj_x1
instance QcloseEvent (QGLWidget ()) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_closeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_closeEvent_h" qtc_QGLWidget_closeEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent (QGLWidgetSc a) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_closeEvent_h cobj_x0 cobj_x1
instance QcontextMenuEvent (QGLWidget ()) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_contextMenuEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_contextMenuEvent_h" qtc_QGLWidget_contextMenuEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent (QGLWidgetSc a) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_contextMenuEvent_h cobj_x0 cobj_x1
instance Qcreate (QGLWidget ()) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_create cobj_x0
foreign import ccall "qtc_QGLWidget_create" qtc_QGLWidget_create :: Ptr (TQGLWidget a) -> IO ()
instance Qcreate (QGLWidgetSc a) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_create cobj_x0
instance Qcreate (QGLWidget ()) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_create1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_create1" qtc_QGLWidget_create1 :: Ptr (TQGLWidget a) -> Ptr (TQVoid t1) -> IO ()
instance Qcreate (QGLWidgetSc a) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_create1 cobj_x0 cobj_x1
instance Qcreate (QGLWidget ()) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_create2 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QGLWidget_create2" qtc_QGLWidget_create2 :: Ptr (TQGLWidget a) -> Ptr (TQVoid t1) -> CBool -> IO ()
instance Qcreate (QGLWidgetSc a) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_create2 cobj_x0 cobj_x1 (toCBool x2)
instance Qcreate (QGLWidget ()) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
foreign import ccall "qtc_QGLWidget_create3" qtc_QGLWidget_create3 :: Ptr (TQGLWidget a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO ()
instance Qcreate (QGLWidgetSc a) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
instance Qdestroy (QGLWidget ()) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_destroy cobj_x0
foreign import ccall "qtc_QGLWidget_destroy" qtc_QGLWidget_destroy :: Ptr (TQGLWidget a) -> IO ()
instance Qdestroy (QGLWidgetSc a) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_destroy cobj_x0
instance Qdestroy (QGLWidget ()) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_destroy1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLWidget_destroy1" qtc_QGLWidget_destroy1 :: Ptr (TQGLWidget a) -> CBool -> IO ()
instance Qdestroy (QGLWidgetSc a) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_destroy1 cobj_x0 (toCBool x1)
instance Qdestroy (QGLWidget ()) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
foreign import ccall "qtc_QGLWidget_destroy2" qtc_QGLWidget_destroy2 :: Ptr (TQGLWidget a) -> CBool -> CBool -> IO ()
instance Qdestroy (QGLWidgetSc a) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
instance QdevType (QGLWidget ()) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_devType_h cobj_x0
foreign import ccall "qtc_QGLWidget_devType_h" qtc_QGLWidget_devType_h :: Ptr (TQGLWidget a) -> IO CInt
instance QdevType (QGLWidgetSc a) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_devType_h cobj_x0
instance QdragEnterEvent (QGLWidget ()) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_dragEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_dragEnterEvent_h" qtc_QGLWidget_dragEnterEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent (QGLWidgetSc a) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_dragEnterEvent_h cobj_x0 cobj_x1
instance QdragLeaveEvent (QGLWidget ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_dragLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_dragLeaveEvent_h" qtc_QGLWidget_dragLeaveEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent (QGLWidgetSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_dragLeaveEvent_h cobj_x0 cobj_x1
instance QdragMoveEvent (QGLWidget ()) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_dragMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_dragMoveEvent_h" qtc_QGLWidget_dragMoveEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent (QGLWidgetSc a) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_dragMoveEvent_h cobj_x0 cobj_x1
instance QdropEvent (QGLWidget ()) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_dropEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_dropEvent_h" qtc_QGLWidget_dropEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent (QGLWidgetSc a) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_dropEvent_h cobj_x0 cobj_x1
instance QenabledChange (QGLWidget ()) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_enabledChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLWidget_enabledChange" qtc_QGLWidget_enabledChange :: Ptr (TQGLWidget a) -> CBool -> IO ()
instance QenabledChange (QGLWidgetSc a) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_enabledChange cobj_x0 (toCBool x1)
instance QenterEvent (QGLWidget ()) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_enterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_enterEvent_h" qtc_QGLWidget_enterEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent (QGLWidgetSc a) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_enterEvent_h cobj_x0 cobj_x1
instance QfocusInEvent (QGLWidget ()) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_focusInEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_focusInEvent_h" qtc_QGLWidget_focusInEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent (QGLWidgetSc a) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_focusInEvent_h cobj_x0 cobj_x1
instance QfocusNextChild (QGLWidget ()) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_focusNextChild cobj_x0
foreign import ccall "qtc_QGLWidget_focusNextChild" qtc_QGLWidget_focusNextChild :: Ptr (TQGLWidget a) -> IO CBool
instance QfocusNextChild (QGLWidgetSc a) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_focusNextChild cobj_x0
instance QfocusNextPrevChild (QGLWidget ()) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_focusNextPrevChild cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLWidget_focusNextPrevChild" qtc_QGLWidget_focusNextPrevChild :: Ptr (TQGLWidget a) -> CBool -> IO CBool
instance QfocusNextPrevChild (QGLWidgetSc a) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_focusNextPrevChild cobj_x0 (toCBool x1)
instance QfocusOutEvent (QGLWidget ()) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_focusOutEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_focusOutEvent_h" qtc_QGLWidget_focusOutEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent (QGLWidgetSc a) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_focusOutEvent_h cobj_x0 cobj_x1
instance QfocusPreviousChild (QGLWidget ()) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_focusPreviousChild cobj_x0
foreign import ccall "qtc_QGLWidget_focusPreviousChild" qtc_QGLWidget_focusPreviousChild :: Ptr (TQGLWidget a) -> IO CBool
instance QfocusPreviousChild (QGLWidgetSc a) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_focusPreviousChild cobj_x0
instance QfontChange (QGLWidget ()) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_fontChange cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_fontChange" qtc_QGLWidget_fontChange :: Ptr (TQGLWidget a) -> Ptr (TQFont t1) -> IO ()
instance QfontChange (QGLWidgetSc a) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_fontChange cobj_x0 cobj_x1
instance QheightForWidth (QGLWidget ()) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_heightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGLWidget_heightForWidth_h" qtc_QGLWidget_heightForWidth_h :: Ptr (TQGLWidget a) -> CInt -> IO CInt
instance QheightForWidth (QGLWidgetSc a) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_heightForWidth_h cobj_x0 (toCInt x1)
instance QhideEvent (QGLWidget ()) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_hideEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_hideEvent_h" qtc_QGLWidget_hideEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent (QGLWidgetSc a) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_hideEvent_h cobj_x0 cobj_x1
instance QinputMethodEvent (QGLWidget ()) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_inputMethodEvent" qtc_QGLWidget_inputMethodEvent :: Ptr (TQGLWidget a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent (QGLWidgetSc a) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_inputMethodEvent cobj_x0 cobj_x1
instance QinputMethodQuery (QGLWidget ()) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGLWidget_inputMethodQuery_h" qtc_QGLWidget_inputMethodQuery_h :: Ptr (TQGLWidget a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery (QGLWidgetSc a) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyPressEvent (QGLWidget ()) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_keyPressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_keyPressEvent_h" qtc_QGLWidget_keyPressEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent (QGLWidgetSc a) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_keyPressEvent_h cobj_x0 cobj_x1
instance QkeyReleaseEvent (QGLWidget ()) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_keyReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_keyReleaseEvent_h" qtc_QGLWidget_keyReleaseEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent (QGLWidgetSc a) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_keyReleaseEvent_h cobj_x0 cobj_x1
instance QlanguageChange (QGLWidget ()) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_languageChange cobj_x0
foreign import ccall "qtc_QGLWidget_languageChange" qtc_QGLWidget_languageChange :: Ptr (TQGLWidget a) -> IO ()
instance QlanguageChange (QGLWidgetSc a) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_languageChange cobj_x0
instance QleaveEvent (QGLWidget ()) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_leaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_leaveEvent_h" qtc_QGLWidget_leaveEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent (QGLWidgetSc a) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_leaveEvent_h cobj_x0 cobj_x1
instance Qmetric (QGLWidget ()) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_metric cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGLWidget_metric" qtc_QGLWidget_metric :: Ptr (TQGLWidget a) -> CLong -> IO CInt
instance Qmetric (QGLWidgetSc a) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_metric cobj_x0 (toCLong $ qEnum_toInt x1)
instance QqminimumSizeHint (QGLWidget ()) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_minimumSizeHint_h cobj_x0
foreign import ccall "qtc_QGLWidget_minimumSizeHint_h" qtc_QGLWidget_minimumSizeHint_h :: Ptr (TQGLWidget a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint (QGLWidgetSc a) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_minimumSizeHint_h cobj_x0
instance QminimumSizeHint (QGLWidget ()) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QGLWidget_minimumSizeHint_qth_h" qtc_QGLWidget_minimumSizeHint_qth_h :: Ptr (TQGLWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint (QGLWidgetSc a) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QmouseDoubleClickEvent (QGLWidget ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_mouseDoubleClickEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_mouseDoubleClickEvent_h" qtc_QGLWidget_mouseDoubleClickEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent (QGLWidgetSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_mouseDoubleClickEvent_h cobj_x0 cobj_x1
instance QmouseMoveEvent (QGLWidget ()) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_mouseMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_mouseMoveEvent_h" qtc_QGLWidget_mouseMoveEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent (QGLWidgetSc a) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_mouseMoveEvent_h cobj_x0 cobj_x1
instance QmousePressEvent (QGLWidget ()) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_mousePressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_mousePressEvent_h" qtc_QGLWidget_mousePressEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent (QGLWidgetSc a) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_mousePressEvent_h cobj_x0 cobj_x1
instance QmouseReleaseEvent (QGLWidget ()) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_mouseReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_mouseReleaseEvent_h" qtc_QGLWidget_mouseReleaseEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent (QGLWidgetSc a) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_mouseReleaseEvent_h cobj_x0 cobj_x1
instance Qmove (QGLWidget ()) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_move1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QGLWidget_move1" qtc_QGLWidget_move1 :: Ptr (TQGLWidget a) -> CInt -> CInt -> IO ()
instance Qmove (QGLWidgetSc a) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_move1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qmove (QGLWidget ()) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QGLWidget_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QGLWidget_move_qth" qtc_QGLWidget_move_qth :: Ptr (TQGLWidget a) -> CInt -> CInt -> IO ()
instance Qmove (QGLWidgetSc a) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QGLWidget_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance Qqmove (QGLWidget ()) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_move cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_move" qtc_QGLWidget_move :: Ptr (TQGLWidget a) -> Ptr (TQPoint t1) -> IO ()
instance Qqmove (QGLWidgetSc a) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_move cobj_x0 cobj_x1
instance QmoveEvent (QGLWidget ()) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_moveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_moveEvent_h" qtc_QGLWidget_moveEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent (QGLWidgetSc a) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_moveEvent_h cobj_x0 cobj_x1
instance QpaletteChange (QGLWidget ()) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_paletteChange cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_paletteChange" qtc_QGLWidget_paletteChange :: Ptr (TQGLWidget a) -> Ptr (TQPalette t1) -> IO ()
instance QpaletteChange (QGLWidgetSc a) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_paletteChange cobj_x0 cobj_x1
instance Qrepaint (QGLWidget ()) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_repaint cobj_x0
foreign import ccall "qtc_QGLWidget_repaint" qtc_QGLWidget_repaint :: Ptr (TQGLWidget a) -> IO ()
instance Qrepaint (QGLWidgetSc a) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_repaint cobj_x0
instance Qrepaint (QGLWidget ()) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QGLWidget_repaint2" qtc_QGLWidget_repaint2 :: Ptr (TQGLWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qrepaint (QGLWidgetSc a) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance Qrepaint (QGLWidget ()) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_repaint1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_repaint1" qtc_QGLWidget_repaint1 :: Ptr (TQGLWidget a) -> Ptr (TQRegion t1) -> IO ()
instance Qrepaint (QGLWidgetSc a) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_repaint1 cobj_x0 cobj_x1
instance QresetInputContext (QGLWidget ()) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_resetInputContext cobj_x0
foreign import ccall "qtc_QGLWidget_resetInputContext" qtc_QGLWidget_resetInputContext :: Ptr (TQGLWidget a) -> IO ()
instance QresetInputContext (QGLWidgetSc a) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_resetInputContext cobj_x0
instance Qresize (QGLWidget ()) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_resize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QGLWidget_resize1" qtc_QGLWidget_resize1 :: Ptr (TQGLWidget a) -> CInt -> CInt -> IO ()
instance Qresize (QGLWidgetSc a) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_resize1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qqresize (QGLWidget ()) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_resize cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_resize" qtc_QGLWidget_resize :: Ptr (TQGLWidget a) -> Ptr (TQSize t1) -> IO ()
instance Qqresize (QGLWidgetSc a) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_resize cobj_x0 cobj_x1
instance Qresize (QGLWidget ()) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QGLWidget_resize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QGLWidget_resize_qth" qtc_QGLWidget_resize_qth :: Ptr (TQGLWidget a) -> CInt -> CInt -> IO ()
instance Qresize (QGLWidgetSc a) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QGLWidget_resize_qth cobj_x0 csize_x1_w csize_x1_h
instance QsetGeometry (QGLWidget ()) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QGLWidget_setGeometry1" qtc_QGLWidget_setGeometry1 :: Ptr (TQGLWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QGLWidgetSc a) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance QqsetGeometry (QGLWidget ()) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_setGeometry cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_setGeometry" qtc_QGLWidget_setGeometry :: Ptr (TQGLWidget a) -> Ptr (TQRect t1) -> IO ()
instance QqsetGeometry (QGLWidgetSc a) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_setGeometry cobj_x0 cobj_x1
instance QsetGeometry (QGLWidget ()) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QGLWidget_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QGLWidget_setGeometry_qth" qtc_QGLWidget_setGeometry_qth :: Ptr (TQGLWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QGLWidgetSc a) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QGLWidget_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance QsetVisible (QGLWidget ()) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_setVisible_h cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLWidget_setVisible_h" qtc_QGLWidget_setVisible_h :: Ptr (TQGLWidget a) -> CBool -> IO ()
instance QsetVisible (QGLWidgetSc a) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_setVisible_h cobj_x0 (toCBool x1)
instance QshowEvent (QGLWidget ()) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_showEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_showEvent_h" qtc_QGLWidget_showEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent (QGLWidgetSc a) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_showEvent_h cobj_x0 cobj_x1
instance QqsizeHint (QGLWidget ()) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_sizeHint_h cobj_x0
foreign import ccall "qtc_QGLWidget_sizeHint_h" qtc_QGLWidget_sizeHint_h :: Ptr (TQGLWidget a) -> IO (Ptr (TQSize ()))
instance QqsizeHint (QGLWidgetSc a) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_sizeHint_h cobj_x0
instance QsizeHint (QGLWidget ()) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QGLWidget_sizeHint_qth_h" qtc_QGLWidget_sizeHint_qth_h :: Ptr (TQGLWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint (QGLWidgetSc a) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QtabletEvent (QGLWidget ()) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_tabletEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_tabletEvent_h" qtc_QGLWidget_tabletEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent (QGLWidgetSc a) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_tabletEvent_h cobj_x0 cobj_x1
instance QupdateMicroFocus (QGLWidget ()) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_updateMicroFocus cobj_x0
foreign import ccall "qtc_QGLWidget_updateMicroFocus" qtc_QGLWidget_updateMicroFocus :: Ptr (TQGLWidget a) -> IO ()
instance QupdateMicroFocus (QGLWidgetSc a) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_updateMicroFocus cobj_x0
instance QwheelEvent (QGLWidget ()) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_wheelEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_wheelEvent_h" qtc_QGLWidget_wheelEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent (QGLWidgetSc a) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_wheelEvent_h cobj_x0 cobj_x1
instance QwindowActivationChange (QGLWidget ()) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_windowActivationChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLWidget_windowActivationChange" qtc_QGLWidget_windowActivationChange :: Ptr (TQGLWidget a) -> CBool -> IO ()
instance QwindowActivationChange (QGLWidgetSc a) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_windowActivationChange cobj_x0 (toCBool x1)
instance QchildEvent (QGLWidget ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_childEvent" qtc_QGLWidget_childEvent :: Ptr (TQGLWidget a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QGLWidgetSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QGLWidget ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGLWidget_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QGLWidget_connectNotify" qtc_QGLWidget_connectNotify :: Ptr (TQGLWidget a) -> CWString -> IO ()
instance QconnectNotify (QGLWidgetSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGLWidget_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QGLWidget ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_customEvent" qtc_QGLWidget_customEvent :: Ptr (TQGLWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QGLWidgetSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QGLWidget ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGLWidget_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QGLWidget_disconnectNotify" qtc_QGLWidget_disconnectNotify :: Ptr (TQGLWidget a) -> CWString -> IO ()
instance QdisconnectNotify (QGLWidgetSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGLWidget_disconnectNotify cobj_x0 cstr_x1
instance QeventFilter (QGLWidget ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLWidget_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGLWidget_eventFilter_h" qtc_QGLWidget_eventFilter_h :: Ptr (TQGLWidget a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QGLWidgetSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLWidget_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QGLWidget ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGLWidget_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QGLWidget_receivers" qtc_QGLWidget_receivers :: Ptr (TQGLWidget a) -> CWString -> IO CInt
instance Qreceivers (QGLWidgetSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGLWidget_receivers cobj_x0 cstr_x1
instance Qsender (QGLWidget ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_sender cobj_x0
foreign import ccall "qtc_QGLWidget_sender" qtc_QGLWidget_sender :: Ptr (TQGLWidget a) -> IO (Ptr (TQObject ()))
instance Qsender (QGLWidgetSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_sender cobj_x0
instance QtimerEvent (QGLWidget ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_timerEvent" qtc_QGLWidget_timerEvent :: Ptr (TQGLWidget a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QGLWidgetSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_timerEvent cobj_x0 cobj_x1
| uduki/hsQt | Qtc/Opengl/QGLWidget.hs | bsd-2-clause | 70,417 | 0 | 15 | 11,708 | 23,771 | 12,088 | 11,683 | -1 | -1 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module YesodDsl.ParserState (ParserMonad, initParserState, getParserState,
getPath, getParsed,
setParserState, runParser, pushScope, popScope,
declare, declareClassInstances, declareGlobal, SymType(..),
addClassInstances,
ParserState, mkLoc, parseErrorCount, withSymbol, withGlobalSymbol, withSymbolNow,
pError,
hasReserved,
getEntitySymbol,
symbolMatches,
requireClass,
requireEnumName,
requireEntity,
requireEntityResult,
requireEntityOrClass,
requireEntityId,
requireEntityField,
requireEntityFieldSelectedOrResult,
requireField,
requireEnum,
requireEnumValue,
requireParam,
requireFunction,
setCurrentHandlerType,
getCurrentHandlerType,
requireHandlerType,
validateExtractField,
validateInsert,
beginHandler,
statement,
lastStatement,
postValidation) where
import qualified Data.Map as Map
import Control.Monad.State.Lazy
import YesodDsl.AST
import YesodDsl.Lexer
import qualified Data.List as L
import Data.Maybe
import System.IO
data SymType = SEnum EnumType
| SEnumName EnumName
| SClass Class
| SEntity EntityName
| SEntityResult EntityName
| SEntityId EntityName
| SField Field
| SFieldType FieldType
| SUnique Unique
| SRoute Route
| SHandler Handler
| SParam
| SForParam FieldRef
| SReserved
| SFunction
instance Show SymType where
show st = case st of
SEnum _ -> "enum"
SEnumName _ -> "enum name"
SClass _ -> "class"
SEntity _ -> "entity"
SEntityResult _ -> "get-entity"
SEntityId _ -> "entity id"
SField _ -> "field"
SFieldType _ -> "field type"
SUnique _ -> "unique"
SRoute _ -> "route"
SHandler _ -> "handler"
SParam -> "param"
SForParam _ -> "for-param"
SReserved -> "reserved"
SFunction -> "function"
data Sym = Sym Int Location SymType deriving (Show)
type ParserMonad = StateT ParserState IO
type Syms = Map.Map String [Sym]
type EntityValidation = (EntityName, Entity -> ParserMonad ())
type PendingValidation = Syms -> ParserMonad ()
data ParserState = ParserState {
psSyms :: Syms,
psScopeId :: Int,
psPath :: FilePath,
psParsed :: [FilePath],
psErrors :: Int,
psHandlerType :: Maybe HandlerType,
psPendingValidations :: [[PendingValidation]],
psEntityValidations :: [EntityValidation],
psLastStatement :: Maybe (Location, String),
psChecks :: [(Location,String,FieldType)],
psClassInstances :: Map.Map ClassName [EntityName]
} deriving (Show)
instance Show (Syms -> ParserMonad ()) where
show _ = "<pendingvalidation>"
instance Show (Entity -> ParserMonad ()) where
show _ = "<entityvalidation>"
initParserState :: ParserState
initParserState = ParserState {
psSyms = Map.fromList [
("ClassInstance", [ Sym 0 (Loc "<builtin>" 0 0) (SEntity "ClassInstance") ])
],
psScopeId = 0,
psPath = "",
psParsed = [],
psErrors = 0,
psHandlerType = Nothing,
psPendingValidations = [],
psEntityValidations = [],
psLastStatement = Nothing,
psChecks = [],
psClassInstances = Map.empty
}
getParserState :: ParserMonad ParserState
getParserState = get
getPath :: ParserMonad FilePath
getPath = gets psPath
getParsed :: ParserMonad [FilePath]
getParsed = gets psParsed
addClassInstances :: EntityName -> [ClassName] -> ParserMonad ()
addClassInstances en cns = modify $ \ps -> ps {
psClassInstances = Map.unionWith (++) (psClassInstances ps) m
}
where
m = Map.fromListWith (++) [ (cn,[en]) | cn <- cns ]
setCurrentHandlerType :: HandlerType -> ParserMonad ()
setCurrentHandlerType ht = modify $ \ps -> ps {
psHandlerType = Just ht
}
requireHandlerType :: Location -> String -> (HandlerType -> Bool) -> ParserMonad ()
requireHandlerType l n f = do
mht <- gets psHandlerType
when (fmap f mht /= Just True) $
pError l $ n ++ " not allowed "
++ (fromMaybe "outside handler" $
mht >>= \ht' -> return $ "in " ++ show ht' ++ " handler")
getCurrentHandlerType :: ParserMonad (Maybe HandlerType)
getCurrentHandlerType = gets psHandlerType
setParserState :: ParserState -> ParserMonad ()
setParserState = put
runEntityValidation :: Module -> EntityValidation -> ParserMonad ()
runEntityValidation m (en,f) = do
case L.find (\e -> entityName e == en) $ modEntities m of
Just e -> f e
Nothing -> return ()
validateExtractField :: Location -> String -> ParserMonad ()
validateExtractField l s = if s `elem` validFields
then return ()
else pError l $ "Unknown subfield '" ++ s ++ "' to extract"
where
validFields = [
"century", "day", "decade", "dow", "doy", "epoch", "hour",
"isodow", "microseconds", "millennium", "milliseconds",
"minute", "month", "quarter", "second", "timezone",
"timezone_hour", "timezone_minute", "week", "year"
]
validateInsert :: Location -> Entity -> Maybe (Maybe VariableName, [FieldRefMapping]) -> ParserMonad ()
validateInsert l e (Just (Nothing, ifs)) = do
case [ fieldName f | f <- entityFields e,
(not . fieldOptional) f,
isNothing (fieldDefault f) ]
L.\\ [ fn | (fn,_,_) <- ifs ] of
fs@(_:_) -> pError l $ "Missing required fields without default value: " ++ (show fs)
_ -> return ()
validateInsert _ _ _ = return ()
beginHandler :: ParserMonad ()
beginHandler = modify $ \ps -> ps {
psLastStatement = Nothing
}
statement :: Location -> String -> ParserMonad ()
statement l s= do
mlast <- gets psLastStatement
fromMaybe (return ()) (mlast >>= \(l',s') -> do
return $ pError l $ "'" ++ s ++ "' not allowed after '" ++ s' ++ "' in "
++ show l')
lastStatement :: Location -> String -> ParserMonad ()
lastStatement l s = do
statement l s
modify $ \ps -> ps {
psLastStatement = listToMaybe $ catMaybes [
psLastStatement ps, Just (l,s)
]
}
postValidation :: Module -> ParserState -> IO Int
postValidation m ps = do
ps' <- execStateT f ps
return $ psErrors ps'
where
f = do
forM_ (psEntityValidations ps) (runEntityValidation m)
when (isNothing $ modName m) $ globalError "Missing top-level module name"
runParser :: FilePath -> ParserState -> ParserMonad a -> IO (a,ParserState)
runParser path ps m = do
(r,ps') <- runStateT m $ ps { psPath = path, psParsed = path:psParsed ps }
return (r, ps' { psPath = psPath ps} )
pushScope :: ParserMonad ()
pushScope = do
modify $ \ps -> ps {
psScopeId = psScopeId ps + 1,
psPendingValidations = []:psPendingValidations ps
}
popScope :: ParserMonad ()
popScope = do
(vs:_) <- gets psPendingValidations
syms <- gets psSyms
forM_ vs $ \v -> v syms
modify $ \ps -> ps {
psSyms = Map.filter (not . null) $
Map.map (filter (\(Sym s _ _) -> s < psScopeId ps)) $ psSyms ps,
psScopeId = psScopeId ps - 1,
psPendingValidations = tail $ psPendingValidations ps
}
pError :: Location -> String -> ParserMonad ()
pError l e = do
lift $ hPutStrLn stderr $ show l ++ ": " ++ e
modify $ \ps -> ps { psErrors = psErrors ps + 1 }
globalError :: String -> ParserMonad ()
globalError e = do
lift $ hPutStrLn stderr e
modify $ \ps -> ps { psErrors = psErrors ps + 1 }
declare :: Location -> String -> SymType -> ParserMonad ()
declare l n t = declare' False l n t
declareClassInstances :: ClassName -> Location -> String -> ParserMonad ()
declareClassInstances cn l n = do
ps <- get
forM_ (Map.findWithDefault [] cn $ psClassInstances ps) $ \en -> do
declare l (n ++ "_" ++ en) (SEntity en)
declareGlobal :: Location -> String -> SymType -> ParserMonad ()
declareGlobal l n t = declare' True l n t
declare' :: Bool -> Location -> String -> SymType -> ParserMonad ()
declare' global l n t = do
ps <- get
let scopeId = if global then 0 else psScopeId ps
sym = [Sym scopeId l t ]
case Map.lookup n (psSyms ps) of
Just ((Sym s l' _):_) -> if s == scopeId
then do
pError l $ "'" ++ n
++ "' already declared in " ++ show l'
return ()
else put $ ps {
psSyms = Map.adjust (sym++) n (psSyms ps)
}
_ -> put $ ps {
psSyms = Map.insert n sym $ psSyms ps
}
mkLoc :: Token -> ParserMonad Location
mkLoc t = do
path <- gets psPath
return $ Loc path (tokenLineNum t) (tokenColNum t)
parseErrorCount :: ParserState -> Int
parseErrorCount = psErrors
addEntityValidation :: EntityValidation -> ParserMonad ()
addEntityValidation ev = modify $ \ps -> ps {
psEntityValidations = psEntityValidations ps ++ [ev]
}
addPendingValidation :: (Syms -> ParserMonad ()) -> ParserMonad ()
addPendingValidation v = modify $ \ps -> let vs = psPendingValidations ps in ps {
psPendingValidations = (v:(head vs)):tail vs
}
addGlobalPendingValidation :: (Syms -> ParserMonad ()) -> ParserMonad ()
addGlobalPendingValidation v = modify $ \ps -> let vs = psPendingValidations ps in ps {
psPendingValidations = init vs ++ [v : last vs]
}
hasReserved :: String -> ParserMonad Bool
hasReserved n = do
syms <- gets psSyms
return $ fromMaybe False $
Map.lookup n syms >>= return . (not . null . (filter match))
where
match (Sym _ _ SReserved) = True
match _ = False
withSymbol' :: Syms -> a -> Location -> String -> (Location -> Location -> SymType -> ParserMonad a) -> ParserMonad a
withSymbol' syms d l n f = do
case Map.lookup n syms >>= return . (filter notReserved) of
Just ((Sym _ l' st):_) -> f l l' st
_ -> pError l ("Reference to an undeclared identifier '"
++ n ++ "'") >> return d
notReserved :: Sym -> Bool
notReserved (Sym _ _ SReserved) = False
notReserved _ = True
withSymbolNow :: a -> Location -> String -> (Location -> Location -> SymType -> ParserMonad a) -> ParserMonad a
withSymbolNow d l n f = do
syms <- gets psSyms
withSymbol' syms d l n f
withSymbol :: Location -> String -> (Location -> Location -> SymType -> ParserMonad ()) -> ParserMonad ()
withSymbol l n f = addPendingValidation $ \syms -> void $ withSymbol' syms () l n f
withGlobalSymbol :: Location -> String -> (Location -> Location -> SymType -> ParserMonad ()) -> ParserMonad ()
withGlobalSymbol l n f = addGlobalPendingValidation $ \syms -> void $ withSymbol' syms () l n f
getEntitySymbol :: Location -> Location -> SymType -> ParserMonad (Maybe EntityName)
getEntitySymbol _ _ (SEntity en) = return $ Just en
getEntitySymbol _ _ _ = return Nothing
symbolMatches :: String -> (SymType -> Bool) -> ParserMonad Bool
symbolMatches n f = do
syms <- gets psSyms
case Map.lookup n syms >>= return . (filter notReserved) of
Just ((Sym _ _ st):_) -> return $ f st
_ -> return False
requireClass :: (Class -> ParserMonad ()) -> (Location -> Location -> SymType -> ParserMonad ())
requireClass f = f'
where f' _ _ (SClass c) = f c
f' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected class)"
requireEntity :: (Entity -> ParserMonad ()) -> (Location -> Location -> SymType -> ParserMonad ())
requireEntity f = f'
where f' _ _ (SEntity en) = addEntityValidation (en, f)
f' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected entity)"
requireEntityResult :: (Entity -> ParserMonad ()) -> (Location -> Location -> SymType -> ParserMonad ())
requireEntityResult f = f'
where f' _ _ (SEntityResult en) = addEntityValidation (en, f)
f' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected get-entity)"
requireEntityOrClass :: (Location -> Location -> SymType -> ParserMonad ())
requireEntityOrClass = f'
where f' _ _ (SEntity _) = return ()
f' _ _ (SClass _) = return ()
f' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected entity or class)"
requireEntityId :: (EntityName -> ParserMonad (Maybe a)) -> (Location -> Location -> SymType -> ParserMonad (Maybe a))
requireEntityId f = f'
where f' _ _ (SEntityId en) = f en
f' l1 l2 st = pError l1 ("Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected entity id)") >> return Nothing
requireEnumName :: (EntityName -> ParserMonad (Maybe a)) -> (Location -> Location -> SymType -> ParserMonad (Maybe a))
requireEnumName f = f'
where f' _ _ (SEnumName en) = f en
f' l1 l2 st = pError l1 ("Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected enum name)") >> return Nothing
requireEntityField :: Location -> FieldName -> ((Entity,Field) -> ParserMonad ()) -> (Location -> Location -> SymType -> ParserMonad ())
requireEntityField l fn fun = fun'
where fun' _ _ (SEntity en) = addEntityValidation (en, \e ->
case L.find (\f -> fieldName f == fn) $ entityFields e ++ entityClassFields e of
Just f -> fun (e,f)
Nothing -> pError l ("Reference to undeclared field '"
++ fn ++ "' of entity '" ++ entityName e ++ "'"))
fun' l1 l2 st = pError l1 ( "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected entity)")
requireEntityFieldSelectedOrResult :: Location -> FieldName -> (Location -> Location -> SymType -> ParserMonad ())
requireEntityFieldSelectedOrResult l fn = fun'
where
fun' _ _ (SEntity en) = validate en
fun' _ _ (SEntityResult en) = validate en
fun' l1 l2 st = pError l1 ( "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected entity or get-entity)")
validate en = addEntityValidation (en, \e ->
case L.find (\f -> fieldName f == fn) $ entityFields e ++ entityClassFields e of
Just _ -> return ()
Nothing -> pError l ("Reference to undeclared field '"
++ fn ++ "' of entity '" ++ entityName e ++ "'"))
requireEnum :: Location -> Location -> SymType -> ParserMonad ()
requireEnum = fun'
where
fun' _ _ (SEnum e) = return ()
fun' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected enum)"
requireEnumValue :: Location -> EnumValue -> (Location -> Location -> SymType -> ParserMonad ())
requireEnumValue l ev = fun'
where
fun' _ _ (SEnum e) =
case L.find (\ev' -> ev' == ev) $ enumValues e of
Just _ -> return ()
Nothing -> pError l $ "Reference to undeclared enum value '"
++ ev ++ "' of enum '" ++ enumName e ++ "'"
fun' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected enum)"
requireParam :: (Location -> Location -> SymType -> ParserMonad ())
requireParam = fun'
where
fun' _ _ SParam = return ()
fun' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected param)"
requireField:: (Field -> ParserMonad ()) -> (Location -> Location -> SymType -> ParserMonad ())
requireField f = f'
where f' _ _ (SField sf) = f sf
f' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected field)"
requireFunction :: (Location -> Location -> SymType -> ParserMonad ())
requireFunction = fun'
where
fun' _ _ SFunction = return ()
fun' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected function)"
| tlaitinen/yesod-dsl | YesodDsl/ParserState.hs | bsd-2-clause | 16,297 | 1 | 20 | 4,512 | 5,554 | 2,831 | 2,723 | 344 | 4 |
module HSH.Evaluate where
import HSH.CommandLineParse
import HSH.ShellState
import HSH.Exec
import Control.Monad
import Control.Monad.State
import System.IO
import qualified System.Environment as SysEnv
import qualified System.Posix.Directory as Posix
import qualified Data.Map as Map
import Data.Maybe
import Data.Foldable
import GHC.IO.Exception (ExitCode(..))
{-
- Command Evaluation
-}
-- | Evaluate a shell command abstract syntax tree.
evaluate :: ShellAST -> StateT ShellState IO ()
{- setenv -}
evaluate (SetEnv varname value) = do
candidateNewState <- setEnv varname value <$> get
newState <- if varname == "PATH"
then lift $ initialPathLoad candidateNewState
else return candidateNewState
put newState
{- getenv -}
evaluate (GetEnv varname) = do
env <- envVars <$> get
lift $ putStrLn $ fromMaybe
("Undefined environment variable '" ++ varname ++ "'.")
(Map.lookup varname env)
{- showstate -}
evaluate DebugState = get >>= lift . print
{- showparse -}
evaluate (ShowParse ast) = lift $ print ast
{- cd -}
evaluate (Chdir dir) = lift $ Posix.changeWorkingDirectory dir
{- Invoke external commands -}
evaluate (External command) = do
currentState <- get
(exitCode, messages) <- lift $ runExternalCommand command currentState
-- Report all execution errors
mapM_ (lift . hPutStrLn stderr) messages
-- Keep ${?} updated
put $ setEnv "?" (numericString exitCode) currentState
where
numericString ExitSuccess = numericString (ExitFailure 0)
numericString (ExitFailure num) = show num
{- REPL Functions -}
replEvaluate :: ShellAST -> StateT ShellState IO ()
replEvaluate ast = do
currentState <- get
newState <- lift $ refreshPath currentState
put newState
evaluate ast
-- | Read, evaluate, and print a single command.
rep :: StateT ShellState IO ()
rep = do
state <- get
lift $ putStr $ shellPrompt state
line <- lift getLine
case parseLine line state of
Just x -> replEvaluate x
Nothing -> lift $ hPutStrLn stderr "Parsing input line failed."
-- | Add looping to the REP.
repl :: StateT ShellState IO ()
repl = forever rep
-- | The 'clearEnv' function clears out the running process's ENV vars. This must be run
-- at shell start, otherwise 'System.Process.createProcess' will behave as if there is an
-- implicit merge between ShellState's envVars and the process's inherited `ENV`.
clearEnv :: IO ()
clearEnv = do
vars <- map fst <$> SysEnv.getEnvironment
traverse_ SysEnv.unsetEnv vars
-- | Run the Shell REPL.
runREPL :: IO ()
runREPL = do
hSetBuffering stdout NoBuffering
clearEnv
initialState <- initialPathLoad defaultShellState
evalStateT repl initialState
| jessekempf/hsh | src/HSH/Evaluate.hs | bsd-2-clause | 2,746 | 0 | 11 | 561 | 683 | 344 | 339 | 61 | 3 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Type checking of type signatures in interface files
-}
{-# LANGUAGE CPP #-}
module TcIface (
tcLookupImported_maybe,
importDecl, checkWiredInTyCon, tcHiBootIface, typecheckIface,
tcIfaceDecl, tcIfaceInst, tcIfaceFamInst, tcIfaceRules,
tcIfaceVectInfo, tcIfaceAnnotations,
tcIfaceExpr, -- Desired by HERMIT (Trac #7683)
tcIfaceGlobal
) where
#include "HsVersions.h"
import TcTypeNats(typeNatCoAxiomRules)
import IfaceSyn
import LoadIface
import IfaceEnv
import BuildTyCl
import TcRnMonad
import TcType
import Type
import Coercion
import CoAxiom
import TyCoRep -- needs to build types & coercions in a knot
import HscTypes
import Annotations
import InstEnv
import FamInstEnv
import CoreSyn
import CoreUtils
import CoreUnfold
import CoreLint
import MkCore
import Id
import MkId
import IdInfo
import Class
import TyCon
import ConLike
import DataCon
import PrelNames
import TysWiredIn
import Literal
import Var
import VarEnv
import VarSet
import Name
import NameEnv
import NameSet
import OccurAnal ( occurAnalyseExpr )
import Demand
import Module
import UniqFM
import UniqSupply
import Outputable
import Maybes
import SrcLoc
import DynFlags
import Util
import FastString
import BasicTypes hiding ( SuccessFlag(..) )
import ListSetOps
import Data.List
import Control.Monad
import qualified Data.Map as Map
{-
This module takes
IfaceDecl -> TyThing
IfaceType -> Type
etc
An IfaceDecl is populated with RdrNames, and these are not renamed to
Names before typechecking, because there should be no scope errors etc.
-- For (b) consider: f = \$(...h....)
-- where h is imported, and calls f via an hi-boot file.
-- This is bad! But it is not seen as a staging error, because h
-- is indeed imported. We don't want the type-checker to black-hole
-- when simplifying and compiling the splice!
--
-- Simple solution: discard any unfolding that mentions a variable
-- bound in this module (and hence not yet processed).
-- The discarding happens when forkM finds a type error.
************************************************************************
* *
Type-checking a complete interface
* *
************************************************************************
Suppose we discover we don't need to recompile. Then we must type
check the old interface file. This is a bit different to the
incremental type checking we do as we suck in interface files. Instead
we do things similarly as when we are typechecking source decls: we
bring into scope the type envt for the interface all at once, using a
knot. Remember, the decls aren't necessarily in dependency order --
and even if they were, the type decls might be mutually recursive.
-}
typecheckIface :: ModIface -- Get the decls from here
-> TcRnIf gbl lcl ModDetails
typecheckIface iface
= initIfaceTc iface $ \ tc_env_var -> do
-- The tc_env_var is freshly allocated, private to
-- type-checking this particular interface
{ -- Get the right set of decls and rules. If we are compiling without -O
-- we discard pragmas before typechecking, so that we don't "see"
-- information that we shouldn't. From a versioning point of view
-- It's not actually *wrong* to do so, but in fact GHCi is unable
-- to handle unboxed tuples, so it must not see unfoldings.
ignore_prags <- goptM Opt_IgnoreInterfacePragmas
-- Typecheck the decls. This is done lazily, so that the knot-tying
-- within this single module work out right. In the If monad there is
-- no global envt for the current interface; instead, the knot is tied
-- through the if_rec_types field of IfGblEnv
; names_w_things <- loadDecls ignore_prags (mi_decls iface)
; let type_env = mkNameEnv names_w_things
; writeMutVar tc_env_var type_env
-- Now do those rules, instances and annotations
; insts <- mapM tcIfaceInst (mi_insts iface)
; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
; rules <- tcIfaceRules ignore_prags (mi_rules iface)
; anns <- tcIfaceAnnotations (mi_anns iface)
-- Vectorisation information
; vect_info <- tcIfaceVectInfo (mi_module iface) type_env (mi_vect_info iface)
-- Exports
; exports <- ifaceExportNames (mi_exports iface)
-- Finished
; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
-- Careful! If we tug on the TyThing thunks too early
-- we'll infinite loop with hs-boot. See #10083 for
-- an example where this would cause non-termination.
text "Type envt:" <+> ppr (map fst names_w_things)])
; return $ ModDetails { md_types = type_env
, md_insts = insts
, md_fam_insts = fam_insts
, md_rules = rules
, md_anns = anns
, md_vect_info = vect_info
, md_exports = exports
}
}
{-
************************************************************************
* *
Type and class declarations
* *
************************************************************************
-}
tcHiBootIface :: HscSource -> Module -> TcRn SelfBootInfo
-- Load the hi-boot iface for the module being compiled,
-- if it indeed exists in the transitive closure of imports
-- Return the ModDetails; Nothing if no hi-boot iface
tcHiBootIface hsc_src mod
| HsBootFile <- hsc_src -- Already compiling a hs-boot file
= return NoSelfBoot
| otherwise
= do { traceIf (text "loadHiBootInterface" <+> ppr mod)
; mode <- getGhcMode
; if not (isOneShot mode)
-- In --make and interactive mode, if this module has an hs-boot file
-- we'll have compiled it already, and it'll be in the HPT
--
-- We check wheher the interface is a *boot* interface.
-- It can happen (when using GHC from Visual Studio) that we
-- compile a module in TypecheckOnly mode, with a stable,
-- fully-populated HPT. In that case the boot interface isn't there
-- (it's been replaced by the mother module) so we can't check it.
-- And that's fine, because if M's ModInfo is in the HPT, then
-- it's been compiled once, and we don't need to check the boot iface
then do { hpt <- getHpt
; case lookupHpt hpt (moduleName mod) of
Just info | mi_boot (hm_iface info)
-> return (mkSelfBootInfo (hm_details info))
_ -> return NoSelfBoot }
else do
-- OK, so we're in one-shot mode.
-- Re #9245, we always check if there is an hi-boot interface
-- to check consistency against, rather than just when we notice
-- that an hi-boot is necessary due to a circular import.
{ read_result <- findAndReadIface
need mod
True -- Hi-boot file
; case read_result of {
Succeeded (iface, _path) -> do { tc_iface <- typecheckIface iface
; return (mkSelfBootInfo tc_iface) } ;
Failed err ->
-- There was no hi-boot file. But if there is circularity in
-- the module graph, there really should have been one.
-- Since we've read all the direct imports by now,
-- eps_is_boot will record if any of our imports mention the
-- current module, which either means a module loop (not
-- a SOURCE import) or that our hi-boot file has mysteriously
-- disappeared.
do { eps <- getEps
; case lookupUFM (eps_is_boot eps) (moduleName mod) of
Nothing -> return NoSelfBoot -- The typical case
Just (_, False) -> failWithTc moduleLoop
-- Someone below us imported us!
-- This is a loop with no hi-boot in the way
Just (_mod, True) -> failWithTc (elaborate err)
-- The hi-boot file has mysteriously disappeared.
}}}}
where
need = text "Need the hi-boot interface for" <+> ppr mod
<+> text "to compare against the Real Thing"
moduleLoop = text "Circular imports: module" <+> quotes (ppr mod)
<+> text "depends on itself"
elaborate err = hang (text "Could not find hi-boot interface for" <+>
quotes (ppr mod) <> colon) 4 err
mkSelfBootInfo :: ModDetails -> SelfBootInfo
mkSelfBootInfo mds
= SelfBoot { sb_mds = mds
, sb_tcs = mkNameSet (map tyConName (typeEnvTyCons iface_env))
, sb_ids = mkNameSet (map idName (typeEnvIds iface_env)) }
where
iface_env = md_types mds
{-
************************************************************************
* *
Type and class declarations
* *
************************************************************************
When typechecking a data type decl, we *lazily* (via forkM) typecheck
the constructor argument types. This is in the hope that we may never
poke on those argument types, and hence may never need to load the
interface files for types mentioned in the arg types.
E.g.
data Foo.S = MkS Baz.T
Mabye we can get away without even loading the interface for Baz!
This is not just a performance thing. Suppose we have
data Foo.S = MkS Baz.T
data Baz.T = MkT Foo.S
(in different interface files, of course).
Now, first we load and typecheck Foo.S, and add it to the type envt.
If we do explore MkS's argument, we'll load and typecheck Baz.T.
If we explore MkT's argument we'll find Foo.S already in the envt.
If we typechecked constructor args eagerly, when loading Foo.S we'd try to
typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
which isn't done yet.
All very cunning. However, there is a rather subtle gotcha which bit
me when developing this stuff. When we typecheck the decl for S, we
extend the type envt with S, MkS, and all its implicit Ids. Suppose
(a bug, but it happened) that the list of implicit Ids depended in
turn on the constructor arg types. Then the following sequence of
events takes place:
* we build a thunk <t> for the constructor arg tys
* we build a thunk for the extended type environment (depends on <t>)
* we write the extended type envt into the global EPS mutvar
Now we look something up in the type envt
* that pulls on <t>
* which reads the global type envt out of the global EPS mutvar
* but that depends in turn on <t>
It's subtle, because, it'd work fine if we typechecked the constructor args
eagerly -- they don't need the extended type envt. They just get the extended
type envt by accident, because they look at it later.
What this means is that the implicitTyThings MUST NOT DEPEND on any of
the forkM stuff.
-}
tcIfaceDecl :: Bool -- ^ True <=> discard IdInfo on IfaceId bindings
-> IfaceDecl
-> IfL TyThing
tcIfaceDecl = tc_iface_decl Nothing
tc_iface_decl :: Maybe Class -- ^ For associated type/data family declarations
-> Bool -- ^ True <=> discard IdInfo on IfaceId bindings
-> IfaceDecl
-> IfL TyThing
tc_iface_decl _ ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type,
ifIdDetails = details, ifIdInfo = info})
= do { name <- lookupIfaceTop occ_name
; ty <- tcIfaceType iface_type
; details <- tcIdDetails ty details
; info <- tcIdInfo ignore_prags name ty info
; return (AnId (mkGlobalId details name ty info)) }
tc_iface_decl _ _ (IfaceData {ifName = occ_name,
ifCType = cType,
ifBinders = binders,
ifResKind = res_kind,
ifRoles = roles,
ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
ifCons = rdr_cons,
ifParent = mb_parent })
= bindIfaceTyConBinders_AT binders $ \ binders' -> do
{ tc_name <- lookupIfaceTop occ_name
; res_kind' <- tcIfaceType res_kind
; tycon <- fixM $ \ tycon -> do
{ stupid_theta <- tcIfaceCtxt ctxt
; parent' <- tc_parent tc_name mb_parent
; cons <- tcIfaceDataCons tc_name tycon binders' rdr_cons
; return (mkAlgTyCon tc_name binders' res_kind'
roles cType stupid_theta
cons parent' gadt_syn) }
; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
; return (ATyCon tycon) }
where
tc_parent :: Name -> IfaceTyConParent -> IfL AlgTyConFlav
tc_parent tc_name IfNoParent
= do { tc_rep_name <- newTyConRepName tc_name
; return (VanillaAlgTyCon tc_rep_name) }
tc_parent _ (IfDataInstance ax_name _ arg_tys)
= do { ax <- tcIfaceCoAxiom ax_name
; let fam_tc = coAxiomTyCon ax
ax_unbr = toUnbranchedAxiom ax
; lhs_tys <- tcIfaceTcArgs arg_tys
; return (DataFamInstTyCon ax_unbr fam_tc lhs_tys) }
tc_iface_decl _ _ (IfaceSynonym {ifName = occ_name,
ifRoles = roles,
ifSynRhs = rhs_ty,
ifBinders = binders,
ifResKind = res_kind })
= bindIfaceTyConBinders_AT binders $ \ binders' -> do
{ tc_name <- lookupIfaceTop occ_name
; res_kind' <- tcIfaceType res_kind -- Note [Synonym kind loop]
; rhs <- forkM (mk_doc tc_name) $
tcIfaceType rhs_ty
; let tycon = mkSynonymTyCon tc_name binders' res_kind' roles rhs
; return (ATyCon tycon) }
where
mk_doc n = text "Type synonym" <+> ppr n
tc_iface_decl parent _ (IfaceFamily {ifName = occ_name,
ifFamFlav = fam_flav,
ifBinders = binders,
ifResKind = res_kind,
ifResVar = res, ifFamInj = inj })
= bindIfaceTyConBinders_AT binders $ \ binders' -> do
{ tc_name <- lookupIfaceTop occ_name
; res_kind' <- tcIfaceType res_kind -- Note [Synonym kind loop]
; rhs <- forkM (mk_doc tc_name) $
tc_fam_flav tc_name fam_flav
; res_name <- traverse (newIfaceName . mkTyVarOccFS) res
; let tycon = mkFamilyTyCon tc_name binders' res_kind' res_name rhs parent inj
; return (ATyCon tycon) }
where
mk_doc n = text "Type synonym" <+> ppr n
tc_fam_flav :: Name -> IfaceFamTyConFlav -> IfL FamTyConFlav
tc_fam_flav tc_name IfaceDataFamilyTyCon
= do { tc_rep_name <- newTyConRepName tc_name
; return (DataFamilyTyCon tc_rep_name) }
tc_fam_flav _ IfaceOpenSynFamilyTyCon= return OpenSynFamilyTyCon
tc_fam_flav _ (IfaceClosedSynFamilyTyCon mb_ax_name_branches)
= do { ax <- traverse (tcIfaceCoAxiom . fst) mb_ax_name_branches
; return (ClosedSynFamilyTyCon ax) }
tc_fam_flav _ IfaceAbstractClosedSynFamilyTyCon
= return AbstractClosedSynFamilyTyCon
tc_fam_flav _ IfaceBuiltInSynFamTyCon
= pprPanic "tc_iface_decl"
(text "IfaceBuiltInSynFamTyCon in interface file")
tc_iface_decl _parent ignore_prags
(IfaceClass {ifCtxt = rdr_ctxt, ifName = tc_occ,
ifRoles = roles,
ifBinders = binders,
ifFDs = rdr_fds,
ifATs = rdr_ats, ifSigs = rdr_sigs,
ifMinDef = mindef_occ })
-- ToDo: in hs-boot files we should really treat abstract classes specially,
-- as we do abstract tycons
= bindIfaceTyConBinders binders $ \ binders' -> do
{ tc_name <- lookupIfaceTop tc_occ
; traceIf (text "tc-iface-class1" <+> ppr tc_occ)
; ctxt <- mapM tc_sc rdr_ctxt
; traceIf (text "tc-iface-class2" <+> ppr tc_occ)
; sigs <- mapM tc_sig rdr_sigs
; fds <- mapM tc_fd rdr_fds
; traceIf (text "tc-iface-class3" <+> ppr tc_occ)
; mindef <- traverse (lookupIfaceTop . mkVarOccFS) mindef_occ
; cls <- fixM $ \ cls -> do
{ ats <- mapM (tc_at cls) rdr_ats
; traceIf (text "tc-iface-class4" <+> ppr tc_occ)
; buildClass tc_name binders' roles ctxt fds ats sigs mindef }
; return (ATyCon (classTyCon cls)) }
where
tc_sc pred = forkM (mk_sc_doc pred) (tcIfaceType pred)
-- The *length* of the superclasses is used by buildClass, and hence must
-- not be inside the thunk. But the *content* maybe recursive and hence
-- must be lazy (via forkM). Example:
-- class C (T a) => D a where
-- data T a
-- Here the associated type T is knot-tied with the class, and
-- so we must not pull on T too eagerly. See Trac #5970
tc_sig :: IfaceClassOp -> IfL TcMethInfo
tc_sig (IfaceClassOp occ rdr_ty dm)
= do { op_name <- lookupIfaceTop occ
; let doc = mk_op_doc op_name rdr_ty
; op_ty <- forkM (doc <+> text "ty") $ tcIfaceType rdr_ty
-- Must be done lazily for just the same reason as the
-- type of a data con; to avoid sucking in types that
-- it mentions unless it's necessary to do so
; dm' <- tc_dm doc dm
; return (op_name, op_ty, dm') }
tc_dm :: SDoc
-> Maybe (DefMethSpec IfaceType)
-> IfL (Maybe (DefMethSpec (SrcSpan, Type)))
tc_dm _ Nothing = return Nothing
tc_dm _ (Just VanillaDM) = return (Just VanillaDM)
tc_dm doc (Just (GenericDM ty))
= do { -- Must be done lazily to avoid sucking in types
; ty' <- forkM (doc <+> text "dm") $ tcIfaceType ty
; return (Just (GenericDM (noSrcSpan, ty'))) }
tc_at cls (IfaceAT tc_decl if_def)
= do ATyCon tc <- tc_iface_decl (Just cls) ignore_prags tc_decl
mb_def <- case if_def of
Nothing -> return Nothing
Just def -> forkM (mk_at_doc tc) $
extendIfaceTyVarEnv (tyConTyVars tc) $
do { tc_def <- tcIfaceType def
; return (Just (tc_def, noSrcSpan)) }
-- Must be done lazily in case the RHS of the defaults mention
-- the type constructor being defined here
-- e.g. type AT a; type AT b = AT [b] Trac #8002
return (ATI tc mb_def)
mk_sc_doc pred = text "Superclass" <+> ppr pred
mk_at_doc tc = text "Associated type" <+> ppr tc
mk_op_doc op_name op_ty = text "Class op" <+> sep [ppr op_name, ppr op_ty]
tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
; tvs2' <- mapM tcIfaceTyVar tvs2
; return (tvs1', tvs2') }
tc_iface_decl _ _ (IfaceAxiom { ifName = ax_occ, ifTyCon = tc
, ifAxBranches = branches, ifRole = role })
= do { tc_name <- lookupIfaceTop ax_occ
; tc_tycon <- tcIfaceTyCon tc
; tc_branches <- tc_ax_branches branches
; let axiom = CoAxiom { co_ax_unique = nameUnique tc_name
, co_ax_name = tc_name
, co_ax_tc = tc_tycon
, co_ax_role = role
, co_ax_branches = manyBranches tc_branches
, co_ax_implicit = False }
; return (ACoAxiom axiom) }
tc_iface_decl _ _ (IfacePatSyn{ ifName = occ_name
, ifPatMatcher = if_matcher
, ifPatBuilder = if_builder
, ifPatIsInfix = is_infix
, ifPatUnivBndrs = univ_bndrs
, ifPatExBndrs = ex_bndrs
, ifPatProvCtxt = prov_ctxt
, ifPatReqCtxt = req_ctxt
, ifPatArgs = args
, ifPatTy = pat_ty
, ifFieldLabels = field_labels })
= do { name <- lookupIfaceTop occ_name
; traceIf (text "tc_iface_decl" <+> ppr name)
; matcher <- tc_pr if_matcher
; builder <- fmapMaybeM tc_pr if_builder
; bindIfaceForAllBndrs univ_bndrs $ \univ_tvs -> do
{ bindIfaceForAllBndrs ex_bndrs $ \ex_tvs -> do
{ patsyn <- forkM (mk_doc name) $
do { prov_theta <- tcIfaceCtxt prov_ctxt
; req_theta <- tcIfaceCtxt req_ctxt
; pat_ty <- tcIfaceType pat_ty
; arg_tys <- mapM tcIfaceType args
; return $ buildPatSyn name is_infix matcher builder
(univ_tvs, req_theta)
(ex_tvs, prov_theta)
arg_tys pat_ty field_labels }
; return $ AConLike . PatSynCon $ patsyn }}}
where
mk_doc n = text "Pattern synonym" <+> ppr n
tc_pr :: (IfExtName, Bool) -> IfL (Id, Bool)
tc_pr (nm, b) = do { id <- forkM (ppr nm) (tcIfaceExtId nm)
; return (id, b) }
tc_ax_branches :: [IfaceAxBranch] -> IfL [CoAxBranch]
tc_ax_branches if_branches = foldlM tc_ax_branch [] if_branches
tc_ax_branch :: [CoAxBranch] -> IfaceAxBranch -> IfL [CoAxBranch]
tc_ax_branch prev_branches
(IfaceAxBranch { ifaxbTyVars = tv_bndrs, ifaxbCoVars = cv_bndrs
, ifaxbLHS = lhs, ifaxbRHS = rhs
, ifaxbRoles = roles, ifaxbIncomps = incomps })
= bindIfaceTyConBinders_AT
(map (\b -> TvBndr b (NamedTCB Inferred)) tv_bndrs) $ \ tvs ->
-- The _AT variant is needed here; see Note [CoAxBranch type variables] in CoAxiom
bindIfaceIds cv_bndrs $ \ cvs -> do
{ tc_lhs <- tcIfaceTcArgs lhs
; tc_rhs <- tcIfaceType rhs
; let br = CoAxBranch { cab_loc = noSrcSpan
, cab_tvs = binderVars tvs
, cab_cvs = cvs
, cab_lhs = tc_lhs
, cab_roles = roles
, cab_rhs = tc_rhs
, cab_incomps = map (prev_branches `getNth`) incomps }
; return (prev_branches ++ [br]) }
tcIfaceDataCons :: Name -> TyCon -> [TyConBinder] -> IfaceConDecls -> IfL AlgTyConRhs
tcIfaceDataCons tycon_name tycon tc_tybinders if_cons
= case if_cons of
IfAbstractTyCon dis -> return (AbstractTyCon dis)
IfDataTyCon cons _ _ -> do { field_lbls <- mapM (traverse lookupIfaceTop) (ifaceConDeclFields if_cons)
; data_cons <- mapM (tc_con_decl field_lbls) cons
; return (mkDataTyConRhs data_cons) }
IfNewTyCon con _ _ -> do { field_lbls <- mapM (traverse lookupIfaceTop) (ifaceConDeclFields if_cons)
; data_con <- tc_con_decl field_lbls con
; mkNewTyConRhs tycon_name tycon data_con }
where
univ_tv_bndrs :: [TyVarBinder]
univ_tv_bndrs = mkDataConUnivTyVarBinders tc_tybinders
tc_con_decl field_lbls (IfCon { ifConInfix = is_infix,
ifConExTvs = ex_bndrs,
ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
ifConArgTys = args, ifConFields = my_lbls,
ifConStricts = if_stricts,
ifConSrcStricts = if_src_stricts})
= -- Universally-quantified tyvars are shared with
-- parent TyCon, and are alrady in scope
bindIfaceForAllBndrs ex_bndrs $ \ ex_tv_bndrs -> do
{ traceIf (text "Start interface-file tc_con_decl" <+> ppr occ)
; dc_name <- lookupIfaceTop occ
-- Read the context and argument types, but lazily for two reasons
-- (a) to avoid looking tugging on a recursive use of
-- the type itself, which is knot-tied
-- (b) to avoid faulting in the component types unless
-- they are really needed
; ~(eq_spec, theta, arg_tys, stricts) <- forkM (mk_doc dc_name) $
do { eq_spec <- tcIfaceEqSpec spec
; theta <- tcIfaceCtxt ctxt
; arg_tys <- mapM tcIfaceType args
; stricts <- mapM tc_strict if_stricts
-- The IfBang field can mention
-- the type itself; hence inside forkM
; return (eq_spec, theta, arg_tys, stricts) }
-- Look up the field labels for this constructor; note that
-- they should be in the same order as my_lbls!
; let lbl_names = map find_lbl my_lbls
find_lbl x = case find (\ fl -> nameOccName (flSelector fl) == x) field_lbls of
Just fl -> fl
Nothing -> error $ "find_lbl missing " ++ occNameString x
-- Remember, tycon is the representation tycon
; let orig_res_ty = mkFamilyTyConApp tycon
(substTyVars (mkTvSubstPrs (map eqSpecPair eq_spec))
(binderVars tc_tybinders))
; prom_rep_name <- newTyConRepName dc_name
; con <- buildDataCon (pprPanic "tcIfaceDataCons: FamInstEnvs" (ppr dc_name))
dc_name is_infix prom_rep_name
(map src_strict if_src_stricts)
(Just stricts)
-- Pass the HsImplBangs (i.e. final
-- decisions) to buildDataCon; it'll use
-- these to guide the construction of a
-- worker.
-- See Note [Bangs on imported data constructors] in MkId
lbl_names
univ_tv_bndrs ex_tv_bndrs
eq_spec theta
arg_tys orig_res_ty tycon
; traceIf (text "Done interface-file tc_con_decl" <+> ppr dc_name)
; return con }
mk_doc con_name = text "Constructor" <+> ppr con_name
tc_strict :: IfaceBang -> IfL HsImplBang
tc_strict IfNoBang = return (HsLazy)
tc_strict IfStrict = return (HsStrict)
tc_strict IfUnpack = return (HsUnpack Nothing)
tc_strict (IfUnpackCo if_co) = do { co <- tcIfaceCo if_co
; return (HsUnpack (Just co)) }
src_strict :: IfaceSrcBang -> HsSrcBang
src_strict (IfSrcBang unpk bang) = HsSrcBang Nothing unpk bang
tcIfaceEqSpec :: IfaceEqSpec -> IfL [EqSpec]
tcIfaceEqSpec spec
= mapM do_item spec
where
do_item (occ, if_ty) = do { tv <- tcIfaceTyVar occ
; ty <- tcIfaceType if_ty
; return (mkEqSpec tv ty) }
{-
Note [Synonym kind loop]
~~~~~~~~~~~~~~~~~~~~~~~~
Notice that we eagerly grab the *kind* from the interface file, but
build a forkM thunk for the *rhs* (and family stuff). To see why,
consider this (Trac #2412)
M.hs: module M where { import X; data T = MkT S }
X.hs: module X where { import {-# SOURCE #-} M; type S = T }
M.hs-boot: module M where { data T }
When kind-checking M.hs we need S's kind. But we do not want to
find S's kind from (typeKind S-rhs), because we don't want to look at
S-rhs yet! Since S is imported from X.hi, S gets just one chance to
be defined, and we must not do that until we've finished with M.T.
Solution: record S's kind in the interface file; now we can safely
look at it.
************************************************************************
* *
Instances
* *
************************************************************************
-}
tcIfaceInst :: IfaceClsInst -> IfL ClsInst
tcIfaceInst (IfaceClsInst { ifDFun = dfun_occ, ifOFlag = oflag
, ifInstCls = cls, ifInstTys = mb_tcs
, ifInstOrph = orph })
= do { dfun <- forkM (text "Dict fun" <+> ppr dfun_occ) $
tcIfaceExtId dfun_occ
; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
; return (mkImportedInstance cls mb_tcs' dfun oflag orph) }
tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
tcIfaceFamInst (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs
, ifFamInstAxiom = axiom_name } )
= do { axiom' <- forkM (text "Axiom" <+> ppr axiom_name) $
tcIfaceCoAxiom axiom_name
-- will panic if branched, but that's OK
; let axiom'' = toUnbranchedAxiom axiom'
mb_tcs' = map (fmap ifaceTyConName) mb_tcs
; return (mkImportedFamInst fam mb_tcs' axiom'') }
{-
************************************************************************
* *
Rules
* *
************************************************************************
We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
are in the type environment. However, remember that typechecking a Rule may
(as a side effect) augment the type envt, and so we may need to iterate the process.
-}
tcIfaceRules :: Bool -- True <=> ignore rules
-> [IfaceRule]
-> IfL [CoreRule]
tcIfaceRules ignore_prags if_rules
| ignore_prags = return []
| otherwise = mapM tcIfaceRule if_rules
tcIfaceRule :: IfaceRule -> IfL CoreRule
tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
ifRuleAuto = auto, ifRuleOrph = orph })
= do { ~(bndrs', args', rhs') <-
-- Typecheck the payload lazily, in the hope it'll never be looked at
forkM (text "Rule" <+> pprRuleName name) $
bindIfaceBndrs bndrs $ \ bndrs' ->
do { args' <- mapM tcIfaceExpr args
; rhs' <- tcIfaceExpr rhs
; return (bndrs', args', rhs') }
; let mb_tcs = map ifTopFreeName args
; this_mod <- getIfModule
; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
ru_bndrs = bndrs', ru_args = args',
ru_rhs = occurAnalyseExpr rhs',
ru_rough = mb_tcs,
ru_origin = this_mod,
ru_orphan = orph,
ru_auto = auto,
ru_local = False }) } -- An imported RULE is never for a local Id
-- or, even if it is (module loop, perhaps)
-- we'll just leave it in the non-local set
where
-- This function *must* mirror exactly what Rules.roughTopNames does
-- We could have stored the ru_rough field in the iface file
-- but that would be redundant, I think.
-- The only wrinkle is that we must not be deceived by
-- type synonyms at the top of a type arg. Since
-- we can't tell at this point, we are careful not
-- to write them out in coreRuleToIfaceRule
ifTopFreeName :: IfaceExpr -> Maybe Name
ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
ifTopFreeName (IfaceType (IfaceTupleTy s _ ts)) = Just (tupleTyConName s (length (tcArgsIfaceTypes ts)))
ifTopFreeName (IfaceApp f _) = ifTopFreeName f
ifTopFreeName (IfaceExt n) = Just n
ifTopFreeName _ = Nothing
{-
************************************************************************
* *
Annotations
* *
************************************************************************
-}
tcIfaceAnnotations :: [IfaceAnnotation] -> IfL [Annotation]
tcIfaceAnnotations = mapM tcIfaceAnnotation
tcIfaceAnnotation :: IfaceAnnotation -> IfL Annotation
tcIfaceAnnotation (IfaceAnnotation target serialized) = do
target' <- tcIfaceAnnTarget target
return $ Annotation {
ann_target = target',
ann_value = serialized
}
tcIfaceAnnTarget :: IfaceAnnTarget -> IfL (AnnTarget Name)
tcIfaceAnnTarget (NamedTarget occ) = do
name <- lookupIfaceTop occ
return $ NamedTarget name
tcIfaceAnnTarget (ModuleTarget mod) = do
return $ ModuleTarget mod
{-
************************************************************************
* *
Vectorisation information
* *
************************************************************************
-}
-- We need access to the type environment as we need to look up information about type constructors
-- (i.e., their data constructors and whether they are class type constructors). If a vectorised
-- type constructor or class is defined in the same module as where it is vectorised, we cannot
-- look that information up from the type constructor that we obtained via a 'forkM'ed
-- 'tcIfaceTyCon' without recursively loading the interface that we are already type checking again
-- and again and again...
--
tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
tcIfaceVectInfo mod typeEnv (IfaceVectInfo
{ ifaceVectInfoVar = vars
, ifaceVectInfoTyCon = tycons
, ifaceVectInfoTyConReuse = tyconsReuse
, ifaceVectInfoParallelVars = parallelVars
, ifaceVectInfoParallelTyCons = parallelTyCons
})
= do { let parallelTyConsSet = mkNameSet parallelTyCons
; vVars <- mapM vectVarMapping vars
; let varsSet = mkVarSet (map fst vVars)
; tyConRes1 <- mapM (vectTyConVectMapping varsSet) tycons
; tyConRes2 <- mapM (vectTyConReuseMapping varsSet) tyconsReuse
; vParallelVars <- mapM vectVar parallelVars
; let (vTyCons, vDataCons, vScSels) = unzip3 (tyConRes1 ++ tyConRes2)
; return $ VectInfo
{ vectInfoVar = mkDVarEnv vVars `extendDVarEnvList` concat vScSels
, vectInfoTyCon = mkNameEnv vTyCons
, vectInfoDataCon = mkNameEnv (concat vDataCons)
, vectInfoParallelVars = mkDVarSet vParallelVars
, vectInfoParallelTyCons = parallelTyConsSet
}
}
where
vectVarMapping name
= do { vName <- lookupIfaceTop (mkLocalisedOccName mod mkVectOcc name)
; var <- forkM (text "vect var" <+> ppr name) $
tcIfaceExtId name
; vVar <- forkM (text "vect vVar [mod =" <+>
ppr mod <> text "; nameModule =" <+>
ppr (nameModule name) <> text "]" <+> ppr vName) $
tcIfaceExtId vName
; return (var, (var, vVar))
}
-- where
-- lookupLocalOrExternalId name
-- = do { let mb_id = lookupTypeEnv typeEnv name
-- ; case mb_id of
-- -- id is local
-- Just (AnId id) -> return id
-- -- name is not an Id => internal inconsistency
-- Just _ -> notAnIdErr
-- -- Id is external
-- Nothing -> tcIfaceExtId name
-- }
--
-- notAnIdErr = pprPanic "TcIface.tcIfaceVectInfo: not an id" (ppr name)
vectVar name
= forkM (text "vect scalar var" <+> ppr name) $
tcIfaceExtId name
vectTyConVectMapping vars name
= do { vName <- lookupIfaceTop (mkLocalisedOccName mod mkVectTyConOcc name)
; vectTyConMapping vars name vName
}
vectTyConReuseMapping vars name
= vectTyConMapping vars name name
vectTyConMapping vars name vName
= do { tycon <- lookupLocalOrExternalTyCon name
; vTycon <- forkM (text "vTycon of" <+> ppr vName) $
lookupLocalOrExternalTyCon vName
-- Map the data constructors of the original type constructor to those of the
-- vectorised type constructor /unless/ the type constructor was vectorised
-- abstractly; if it was vectorised abstractly, the workers of its data constructors
-- do not appear in the set of vectorised variables.
--
-- NB: This is lazy! We don't pull at the type constructors before we actually use
-- the data constructor mapping.
; let isAbstract | isClassTyCon tycon = False
| datacon:_ <- tyConDataCons tycon
= not $ dataConWrapId datacon `elemVarSet` vars
| otherwise = True
vDataCons | isAbstract = []
| otherwise = [ (dataConName datacon, (datacon, vDatacon))
| (datacon, vDatacon) <- zip (tyConDataCons tycon)
(tyConDataCons vTycon)
]
-- Map the (implicit) superclass and methods selectors as they don't occur in
-- the var map.
vScSels | Just cls <- tyConClass_maybe tycon
, Just vCls <- tyConClass_maybe vTycon
= [ (sel, (sel, vSel))
| (sel, vSel) <- zip (classAllSelIds cls) (classAllSelIds vCls)
]
| otherwise
= []
; return ( (name, (tycon, vTycon)) -- (T, T_v)
, vDataCons -- list of (Ci, Ci_v)
, vScSels -- list of (seli, seli_v)
)
}
where
-- we need a fully defined version of the type constructor to be able to extract
-- its data constructors etc.
lookupLocalOrExternalTyCon name
= do { let mb_tycon = lookupTypeEnv typeEnv name
; case mb_tycon of
-- tycon is local
Just (ATyCon tycon) -> return tycon
-- name is not a tycon => internal inconsistency
Just _ -> notATyConErr
-- tycon is external
Nothing -> tcIfaceTyConByName name
}
notATyConErr = pprPanic "TcIface.tcIfaceVectInfo: not a tycon" (ppr name)
{-
************************************************************************
* *
Types
* *
************************************************************************
-}
tcIfaceType :: IfaceType -> IfL Type
tcIfaceType = go
where
go (IfaceTyVar n) = TyVarTy <$> tcIfaceTyVar n
go (IfaceAppTy t1 t2) = AppTy <$> go t1 <*> go t2
go (IfaceLitTy l) = LitTy <$> tcIfaceTyLit l
go (IfaceFunTy t1 t2) = FunTy <$> go t1 <*> go t2
go (IfaceDFunTy t1 t2) = FunTy <$> go t1 <*> go t2
go (IfaceTupleTy s i tks) = tcIfaceTupleTy s i tks
go (IfaceTyConApp tc tks)
= do { tc' <- tcIfaceTyCon tc
; tks' <- mapM go (tcArgsIfaceTypes tks)
; return (mkTyConApp tc' tks') }
go (IfaceForAllTy bndr t)
= bindIfaceForAllBndr bndr $ \ tv' vis ->
ForAllTy (TvBndr tv' vis) <$> go t
go (IfaceCastTy ty co) = CastTy <$> go ty <*> tcIfaceCo co
go (IfaceCoercionTy co) = CoercionTy <$> tcIfaceCo co
tcIfaceTupleTy :: TupleSort -> IfaceTyConInfo -> IfaceTcArgs -> IfL Type
tcIfaceTupleTy sort info args
= do { args' <- tcIfaceTcArgs args
; let arity = length args'
; base_tc <- tcTupleTyCon True sort arity
; case info of
NoIfaceTyConInfo
-> return (mkTyConApp base_tc args')
IfacePromotedDataCon
-> do { let tc = promoteDataCon (tyConSingleDataCon base_tc)
kind_args = map typeKind args'
; return (mkTyConApp tc (kind_args ++ args')) } }
-- See Note [Unboxed tuple RuntimeRep vars] in TyCon
tcTupleTyCon :: Bool -- True <=> typechecking a *type* (vs. an expr)
-> TupleSort
-> Arity -- the number of args. *not* the tuple arity.
-> IfL TyCon
tcTupleTyCon in_type sort arity
= case sort of
ConstraintTuple -> do { thing <- tcIfaceGlobal (cTupleTyConName arity)
; return (tyThingTyCon thing) }
BoxedTuple -> return (tupleTyCon Boxed arity)
UnboxedTuple -> return (tupleTyCon Unboxed arity')
where arity' | in_type = arity `div` 2
| otherwise = arity
-- in expressions, we only have term args
tcIfaceTcArgs :: IfaceTcArgs -> IfL [Type]
tcIfaceTcArgs = mapM tcIfaceType . tcArgsIfaceTypes
-----------------------------------------
tcIfaceCtxt :: IfaceContext -> IfL ThetaType
tcIfaceCtxt sts = mapM tcIfaceType sts
-----------------------------------------
tcIfaceTyLit :: IfaceTyLit -> IfL TyLit
tcIfaceTyLit (IfaceNumTyLit n) = return (NumTyLit n)
tcIfaceTyLit (IfaceStrTyLit n) = return (StrTyLit n)
{-
%************************************************************************
%* *
Coercions
* *
************************************************************************
-}
tcIfaceCo :: IfaceCoercion -> IfL Coercion
tcIfaceCo = go
where
go (IfaceReflCo r t) = Refl r <$> tcIfaceType t
go (IfaceFunCo r c1 c2) = mkFunCo r <$> go c1 <*> go c2
go (IfaceTyConAppCo r tc cs)
= TyConAppCo r <$> tcIfaceTyCon tc <*> mapM go cs
go (IfaceAppCo c1 c2) = AppCo <$> go c1 <*> go c2
go (IfaceForAllCo tv k c) = do { k' <- go k
; bindIfaceTyVar tv $ \ tv' ->
ForAllCo tv' k' <$> go c }
go (IfaceCoVarCo n) = CoVarCo <$> go_var n
go (IfaceAxiomInstCo n i cs) = AxiomInstCo <$> tcIfaceCoAxiom n <*> pure i <*> mapM go cs
go (IfaceUnivCo p r t1 t2) = UnivCo <$> tcIfaceUnivCoProv p <*> pure r
<*> tcIfaceType t1 <*> tcIfaceType t2
go (IfaceSymCo c) = SymCo <$> go c
go (IfaceTransCo c1 c2) = TransCo <$> go c1
<*> go c2
go (IfaceInstCo c1 t2) = InstCo <$> go c1
<*> go t2
go (IfaceNthCo d c) = NthCo d <$> go c
go (IfaceLRCo lr c) = LRCo lr <$> go c
go (IfaceCoherenceCo c1 c2) = CoherenceCo <$> go c1
<*> go c2
go (IfaceKindCo c) = KindCo <$> go c
go (IfaceSubCo c) = SubCo <$> go c
go (IfaceAxiomRuleCo ax cos) = AxiomRuleCo <$> go_axiom_rule ax
<*> mapM go cos
go_var :: FastString -> IfL CoVar
go_var = tcIfaceLclId
go_axiom_rule :: FastString -> IfL CoAxiomRule
go_axiom_rule n =
case Map.lookup n typeNatCoAxiomRules of
Just ax -> return ax
_ -> pprPanic "go_axiom_rule" (ppr n)
tcIfaceUnivCoProv :: IfaceUnivCoProv -> IfL UnivCoProvenance
tcIfaceUnivCoProv IfaceUnsafeCoerceProv = return UnsafeCoerceProv
tcIfaceUnivCoProv (IfacePhantomProv kco) = PhantomProv <$> tcIfaceCo kco
tcIfaceUnivCoProv (IfaceProofIrrelProv kco) = ProofIrrelProv <$> tcIfaceCo kco
tcIfaceUnivCoProv (IfacePluginProv str) = return $ PluginProv str
{-
************************************************************************
* *
Core
* *
************************************************************************
-}
tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
tcIfaceExpr (IfaceType ty)
= Type <$> tcIfaceType ty
tcIfaceExpr (IfaceCo co)
= Coercion <$> tcIfaceCo co
tcIfaceExpr (IfaceCast expr co)
= Cast <$> tcIfaceExpr expr <*> tcIfaceCo co
tcIfaceExpr (IfaceLcl name)
= Var <$> tcIfaceLclId name
tcIfaceExpr (IfaceExt gbl)
= Var <$> tcIfaceExtId gbl
tcIfaceExpr (IfaceLit lit)
= do lit' <- tcIfaceLit lit
return (Lit lit')
tcIfaceExpr (IfaceFCall cc ty) = do
ty' <- tcIfaceType ty
u <- newUnique
dflags <- getDynFlags
return (Var (mkFCallId dflags u cc ty'))
tcIfaceExpr (IfaceTuple sort args)
= do { args' <- mapM tcIfaceExpr args
; tc <- tcTupleTyCon False sort arity
; let con_tys = map exprType args'
some_con_args = map Type con_tys ++ args'
con_args = case sort of
UnboxedTuple -> map (Type . getRuntimeRep "tcIfaceExpr") con_tys ++ some_con_args
_ -> some_con_args
-- Put the missing type arguments back in
con_id = dataConWorkId (tyConSingleDataCon tc)
; return (mkApps (Var con_id) con_args) }
where
arity = length args
tcIfaceExpr (IfaceLam (bndr, os) body)
= bindIfaceBndr bndr $ \bndr' ->
Lam (tcIfaceOneShot os bndr') <$> tcIfaceExpr body
where
tcIfaceOneShot IfaceOneShot b = setOneShotLambda b
tcIfaceOneShot _ b = b
tcIfaceExpr (IfaceApp fun arg)
= App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
tcIfaceExpr (IfaceECase scrut ty)
= do { scrut' <- tcIfaceExpr scrut
; ty' <- tcIfaceType ty
; return (castBottomExpr scrut' ty') }
tcIfaceExpr (IfaceCase scrut case_bndr alts) = do
scrut' <- tcIfaceExpr scrut
case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
let
scrut_ty = exprType scrut'
case_bndr' = mkLocalIdOrCoVar case_bndr_name scrut_ty
tc_app = splitTyConApp scrut_ty
-- NB: Won't always succeed (polymorphic case)
-- but won't be demanded in those cases
-- NB: not tcSplitTyConApp; we are looking at Core here
-- look through non-rec newtypes to find the tycon that
-- corresponds to the datacon in this case alternative
extendIfaceIdEnv [case_bndr'] $ do
alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
return (Case scrut' case_bndr' (coreAltsType alts') alts')
tcIfaceExpr (IfaceLet (IfaceNonRec (IfLetBndr fs ty info) rhs) body)
= do { name <- newIfaceName (mkVarOccFS fs)
; ty' <- tcIfaceType ty
; id_info <- tcIdInfo False {- Don't ignore prags; we are inside one! -}
name ty' info
; let id = mkLocalIdOrCoVarWithInfo name ty' id_info
; rhs' <- tcIfaceExpr rhs
; body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
; return (Let (NonRec id rhs') body') }
tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
= do { ids <- mapM tc_rec_bndr (map fst pairs)
; extendIfaceIdEnv ids $ do
{ pairs' <- zipWithM tc_pair pairs ids
; body' <- tcIfaceExpr body
; return (Let (Rec pairs') body') } }
where
tc_rec_bndr (IfLetBndr fs ty _)
= do { name <- newIfaceName (mkVarOccFS fs)
; ty' <- tcIfaceType ty
; return (mkLocalIdOrCoVar name ty') }
tc_pair (IfLetBndr _ _ info, rhs) id
= do { rhs' <- tcIfaceExpr rhs
; id_info <- tcIdInfo False {- Don't ignore prags; we are inside one! -}
(idName id) (idType id) info
; return (setIdInfo id id_info, rhs') }
tcIfaceExpr (IfaceTick tickish expr) = do
expr' <- tcIfaceExpr expr
-- If debug flag is not set: Ignore source notes
dbgLvl <- fmap debugLevel getDynFlags
case tickish of
IfaceSource{} | dbgLvl > 0
-> return expr'
_otherwise -> do
tickish' <- tcIfaceTickish tickish
return (Tick tickish' expr')
-------------------------
tcIfaceTickish :: IfaceTickish -> IfM lcl (Tickish Id)
tcIfaceTickish (IfaceHpcTick modl ix) = return (HpcTick modl ix)
tcIfaceTickish (IfaceSCC cc tick push) = return (ProfNote cc tick push)
tcIfaceTickish (IfaceSource src name) = return (SourceNote src name)
-------------------------
tcIfaceLit :: Literal -> IfL Literal
-- Integer literals deserialise to (LitInteger i <error thunk>)
-- so tcIfaceLit just fills in the type.
-- See Note [Integer literals] in Literal
tcIfaceLit (LitInteger i _)
= do t <- tcIfaceTyConByName integerTyConName
return (mkLitInteger i (mkTyConTy t))
tcIfaceLit lit = return lit
-------------------------
tcIfaceAlt :: CoreExpr -> (TyCon, [Type])
-> (IfaceConAlt, [FastString], IfaceExpr)
-> IfL (AltCon, [TyVar], CoreExpr)
tcIfaceAlt _ _ (IfaceDefault, names, rhs)
= ASSERT( null names ) do
rhs' <- tcIfaceExpr rhs
return (DEFAULT, [], rhs')
tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
= ASSERT( null names ) do
lit' <- tcIfaceLit lit
rhs' <- tcIfaceExpr rhs
return (LitAlt lit', [], rhs')
-- A case alternative is made quite a bit more complicated
-- by the fact that we omit type annotations because we can
-- work them out. True enough, but its not that easy!
tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
= do { con <- tcIfaceDataCon data_occ
; when (debugIsOn && not (con `elem` tyConDataCons tycon))
(failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
; tcIfaceDataAlt con inst_tys arg_strs rhs }
tcIfaceDataAlt :: DataCon -> [Type] -> [FastString] -> IfaceExpr
-> IfL (AltCon, [TyVar], CoreExpr)
tcIfaceDataAlt con inst_tys arg_strs rhs
= do { us <- newUniqueSupply
; let uniqs = uniqsFromSupply us
; let (ex_tvs, arg_ids)
= dataConRepFSInstPat arg_strs uniqs con inst_tys
; rhs' <- extendIfaceEnvs ex_tvs $
extendIfaceIdEnv arg_ids $
tcIfaceExpr rhs
; return (DataAlt con, ex_tvs ++ arg_ids, rhs') }
{-
************************************************************************
* *
IdInfo
* *
************************************************************************
-}
tcIdDetails :: Type -> IfaceIdDetails -> IfL IdDetails
tcIdDetails _ IfVanillaId = return VanillaId
tcIdDetails ty IfDFunId
= return (DFunId (isNewTyCon (classTyCon cls)))
where
(_, _, cls, _) = tcSplitDFunTy ty
tcIdDetails _ (IfRecSelId tc naughty)
= do { tc' <- either (fmap RecSelData . tcIfaceTyCon)
(fmap (RecSelPatSyn . tyThingPatSyn) . tcIfaceDecl False)
tc
; return (RecSelId { sel_tycon = tc', sel_naughty = naughty }) }
where
tyThingPatSyn (AConLike (PatSynCon ps)) = ps
tyThingPatSyn _ = panic "tcIdDetails: expecting patsyn"
tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
tcIdInfo ignore_prags name ty info
| ignore_prags = return vanillaIdInfo
| otherwise = case info of
NoInfo -> return vanillaIdInfo
HasInfo info -> foldlM tcPrag init_info info
where
-- Set the CgInfo to something sensible but uninformative before
-- we start; default assumption is that it has CAFs
init_info = vanillaIdInfo
tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
tcPrag info (HsStrictness str) = return (info `setStrictnessInfo` str)
tcPrag info (HsInline prag) = return (info `setInlinePragInfo` prag)
-- The next two are lazy, so they don't transitively suck stuff in
tcPrag info (HsUnfold lb if_unf)
= do { unf <- tcUnfolding name ty info if_unf
; let info1 | lb = info `setOccInfo` strongLoopBreaker
| otherwise = info
; return (info1 `setUnfoldingInfoLazily` unf) }
tcUnfolding :: Name -> Type -> IdInfo -> IfaceUnfolding -> IfL Unfolding
tcUnfolding name _ info (IfCoreUnfold stable if_expr)
= do { dflags <- getDynFlags
; mb_expr <- tcPragExpr name if_expr
; let unf_src | stable = InlineStable
| otherwise = InlineRhs
; return $ case mb_expr of
Nothing -> NoUnfolding
Just expr -> mkUnfolding dflags unf_src
True {- Top level -}
(isBottomingSig strict_sig)
expr
}
where
-- Strictness should occur before unfolding!
strict_sig = strictnessInfo info
tcUnfolding name _ _ (IfCompulsory if_expr)
= do { mb_expr <- tcPragExpr name if_expr
; return (case mb_expr of
Nothing -> NoUnfolding
Just expr -> mkCompulsoryUnfolding expr) }
tcUnfolding name _ _ (IfInlineRule arity unsat_ok boring_ok if_expr)
= do { mb_expr <- tcPragExpr name if_expr
; return (case mb_expr of
Nothing -> NoUnfolding
Just expr -> mkCoreUnfolding InlineStable True expr guidance )}
where
guidance = UnfWhen { ug_arity = arity, ug_unsat_ok = unsat_ok, ug_boring_ok = boring_ok }
tcUnfolding name dfun_ty _ (IfDFunUnfold bs ops)
= bindIfaceBndrs bs $ \ bs' ->
do { mb_ops1 <- forkM_maybe doc $ mapM tcIfaceExpr ops
; return (case mb_ops1 of
Nothing -> noUnfolding
Just ops1 -> mkDFunUnfolding bs' (classDataCon cls) ops1) }
where
doc = text "Class ops for dfun" <+> ppr name
(_, _, cls, _) = tcSplitDFunTy dfun_ty
{-
For unfoldings we try to do the job lazily, so that we never type check
an unfolding that isn't going to be looked at.
-}
tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
tcPragExpr name expr
= forkM_maybe doc $ do
core_expr' <- tcIfaceExpr expr
-- Check for type consistency in the unfolding
whenGOptM Opt_DoCoreLinting $ do
in_scope <- get_in_scope
dflags <- getDynFlags
case lintUnfolding dflags noSrcLoc in_scope core_expr' of
Nothing -> return ()
Just fail_msg -> do { mod <- getIfModule
; pprPanic "Iface Lint failure"
(vcat [ text "In interface for" <+> ppr mod
, hang doc 2 fail_msg
, ppr name <+> equals <+> ppr core_expr'
, text "Iface expr =" <+> ppr expr ]) }
return core_expr'
where
doc = text "Unfolding of" <+> ppr name
get_in_scope :: IfL VarSet -- Totally disgusting; but just for linting
get_in_scope
= do { (gbl_env, lcl_env) <- getEnvs
; rec_ids <- case if_rec_types gbl_env of
Nothing -> return []
Just (_, get_env) -> do
{ type_env <- setLclEnv () get_env
; return (typeEnvIds type_env) }
; return (bindingsVars (if_tv_env lcl_env) `unionVarSet`
bindingsVars (if_id_env lcl_env) `unionVarSet`
mkVarSet rec_ids) }
bindingsVars :: FastStringEnv Var -> VarSet
bindingsVars ufm = mkVarSet $ nonDetEltsUFM ufm
-- It's OK to use nonDetEltsUFM here because we immediately forget
-- the ordering by creating a set
{-
************************************************************************
* *
Getting from Names to TyThings
* *
************************************************************************
-}
tcIfaceGlobal :: Name -> IfL TyThing
tcIfaceGlobal name
| Just thing <- wiredInNameTyThing_maybe name
-- Wired-in things include TyCons, DataCons, and Ids
-- Even though we are in an interface file, we want to make
-- sure the instances and RULES of this thing (particularly TyCon) are loaded
-- Imagine: f :: Double -> Double
= do { ifCheckWiredInThing thing; return thing }
| otherwise
= do { env <- getGblEnv
; case if_rec_types env of { -- Note [Tying the knot]
Just (mod, get_type_env)
| nameIsLocalOrFrom mod name
-> do -- It's defined in the module being compiled
{ type_env <- setLclEnv () get_type_env -- yuk
; case lookupNameEnv type_env name of
Just thing -> return thing
Nothing ->
pprPanic "tcIfaceGlobal (local): not found"
(ifKnotErr name (if_doc env) type_env)
}
; _ -> do
{ hsc_env <- getTopEnv
; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
; case mb_thing of {
Just thing -> return thing ;
Nothing -> do
{ mb_thing <- importDecl name -- It's imported; go get it
; case mb_thing of
Failed err -> failIfM err
Succeeded thing -> return thing
}}}}}
ifKnotErr :: Name -> SDoc -> TypeEnv -> SDoc
ifKnotErr name env_doc type_env = vcat
[ text "You are in a maze of twisty little passages, all alike."
, text "While forcing the thunk for TyThing" <+> ppr name
, text "which was lazily initialized by" <+> env_doc <> text ","
, text "I tried to tie the knot, but I couldn't find" <+> ppr name
, text "in the current type environment."
, text "If you are developing GHC, please read Note [Tying the knot]"
, text "and Note [Type-checking inside the knot]."
, text "Consider rebuilding GHC with profiling for a better stack trace."
, hang (text "Contents of current type environment:")
2 (ppr type_env)
]
-- Note [Tying the knot]
-- ~~~~~~~~~~~~~~~~~~~~~
-- The if_rec_types field is used in two situations:
--
-- a) Compiling M.hs, which indirectly imports Foo.hi, which mentions M.T
-- Then we look up M.T in M's type environment, which is splatted into if_rec_types
-- after we've built M's type envt.
--
-- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
-- is up to date. So we call typecheckIface on M.hi. This splats M.T into
-- if_rec_types so that the (lazily typechecked) decls see all the other decls
--
-- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
-- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
-- emasculated form (e.g. lacking data constructors).
tcIfaceTyConByName :: IfExtName -> IfL TyCon
tcIfaceTyConByName name
= do { thing <- tcIfaceGlobal name
; return (tyThingTyCon thing) }
tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
tcIfaceTyCon (IfaceTyCon name info)
= do { thing <- tcIfaceGlobal name
; return $ case info of
NoIfaceTyConInfo -> tyThingTyCon thing
IfacePromotedDataCon -> promoteDataCon $ tyThingDataCon thing }
tcIfaceCoAxiom :: Name -> IfL (CoAxiom Branched)
tcIfaceCoAxiom name = do { thing <- tcIfaceGlobal name
; return (tyThingCoAxiom thing) }
tcIfaceDataCon :: Name -> IfL DataCon
tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
; case thing of
AConLike (RealDataCon dc) -> return dc
_ -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
tcIfaceExtId :: Name -> IfL Id
tcIfaceExtId name = do { thing <- tcIfaceGlobal name
; case thing of
AnId id -> return id
_ -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
{-
************************************************************************
* *
Bindings
* *
************************************************************************
-}
bindIfaceId :: IfaceIdBndr -> (Id -> IfL a) -> IfL a
bindIfaceId (fs, ty) thing_inside
= do { name <- newIfaceName (mkVarOccFS fs)
; ty' <- tcIfaceType ty
; let id = mkLocalIdOrCoVar name ty'
; extendIfaceIdEnv [id] (thing_inside id) }
bindIfaceIds :: [IfaceIdBndr] -> ([Id] -> IfL a) -> IfL a
bindIfaceIds [] thing_inside = thing_inside []
bindIfaceIds (b:bs) thing_inside
= bindIfaceId b $ \b' ->
bindIfaceIds bs $ \bs' ->
thing_inside (b':bs')
bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
bindIfaceBndr (IfaceIdBndr bndr) thing_inside
= bindIfaceId bndr thing_inside
bindIfaceBndr (IfaceTvBndr bndr) thing_inside
= bindIfaceTyVar bndr thing_inside
bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
bindIfaceBndrs [] thing_inside = thing_inside []
bindIfaceBndrs (b:bs) thing_inside
= bindIfaceBndr b $ \ b' ->
bindIfaceBndrs bs $ \ bs' ->
thing_inside (b':bs')
-----------------------
bindIfaceForAllBndrs :: [IfaceForAllBndr] -> ([TyVarBinder] -> IfL a) -> IfL a
bindIfaceForAllBndrs [] thing_inside = thing_inside []
bindIfaceForAllBndrs (bndr:bndrs) thing_inside
= bindIfaceForAllBndr bndr $ \tv vis ->
bindIfaceForAllBndrs bndrs $ \bndrs' ->
thing_inside (mkTyVarBinder vis tv : bndrs')
bindIfaceForAllBndr :: IfaceForAllBndr -> (TyVar -> ArgFlag -> IfL a) -> IfL a
bindIfaceForAllBndr (TvBndr tv vis) thing_inside
= bindIfaceTyVar tv $ \tv' -> thing_inside tv' vis
bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
bindIfaceTyVar (occ,kind) thing_inside
= do { name <- newIfaceName (mkTyVarOccFS occ)
; tyvar <- mk_iface_tyvar name kind
; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
mk_iface_tyvar name ifKind
= do { kind <- tcIfaceType ifKind
; return (Var.mkTyVar name kind) }
bindIfaceTyConBinders :: [IfaceTyConBinder]
-> ([TyConBinder] -> IfL a) -> IfL a
bindIfaceTyConBinders [] thing_inside = thing_inside []
bindIfaceTyConBinders (b:bs) thing_inside
= bindIfaceTyConBinderX bindIfaceTyVar b $ \ b' ->
bindIfaceTyConBinders bs $ \ bs' ->
thing_inside (b':bs')
bindIfaceTyConBinders_AT :: [IfaceTyConBinder]
-> ([TyConBinder] -> IfL a) -> IfL a
-- Used for type variable in nested associated data/type declarations
-- where some of the type variables are already in scope
-- class C a where { data T a b }
-- Here 'a' is in scope when we look at the 'data T'
bindIfaceTyConBinders_AT [] thing_inside
= thing_inside []
bindIfaceTyConBinders_AT (b : bs) thing_inside
= bindIfaceTyConBinderX bind_tv b $ \b' ->
bindIfaceTyConBinders_AT bs $ \bs' ->
thing_inside (b':bs')
where
bind_tv tv thing
= do { mb_tv <- lookupIfaceTyVar tv
; case mb_tv of
Just b' -> thing b'
Nothing -> bindIfaceTyVar tv thing }
bindIfaceTyConBinderX :: (IfaceTvBndr -> (TyVar -> IfL a) -> IfL a)
-> IfaceTyConBinder
-> (TyConBinder -> IfL a) -> IfL a
bindIfaceTyConBinderX bind_tv (TvBndr tv vis) thing_inside
= bind_tv tv $ \tv' ->
thing_inside (TvBndr tv' vis)
| vTurbine/ghc | compiler/iface/TcIface.hs | bsd-3-clause | 66,022 | 324 | 24 | 22,850 | 11,219 | 6,075 | 5,144 | -1 | -1 |
module Benchmarks.Day04 (benchmarks) where
import Criterion (Benchmark, bench, nf)
import Day04
import Text.Heredoc
benchmarks :: [Benchmark]
benchmarks =
[ bench "findAdventCoin5"
$ nf (findAdventCoin input) 5
, bench "findAdventCoin6"
$ nf (findAdventCoin input) 6
]
input = [there|./inputs/Day04.txt|] | patrickherrmann/advent | bench/Benchmarks/Day04.hs | bsd-3-clause | 325 | 0 | 9 | 58 | 97 | 56 | 41 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-|
Module : Network.Spotify.Api.Types.Scope
Description : OAuth scopes for the Spotify Web API
Stability : experimental
Scopes let you specify exactly what types of data your application wants to
access, and the set of scopes you pass in your call determines what access
permissions the user is asked to grant.
-}
module Network.Spotify.Api.Types.Scope where
import Data.Aeson (FromJSON (parseJSON), ToJSON, toJSON, withText)
import Data.Text (Text, pack, unpack, words)
import Prelude hiding (words)
import Servant (ToHttpApiData (..), toQueryParam)
-- | If no scope is specified, access is permitted only to publicly available
-- information: that is, only information normally visible to normal
-- logged-in users of the Spotify desktop, web, and mobile clients
-- (e.g. public playlists).
data Scope = Scope
{ getScopes :: [Text]
}
instance Show Scope where
show s = unwords $ map unpack (getScopes s)
instance ToHttpApiData Scope where
toQueryParam = pack . show
instance FromJSON Scope where
parseJSON = withText "Scope" $ \scopes -> do
let parsedScope = scopeFromList (words scopes)
return parsedScope
instance ToJSON Scope where
toJSON = toJSON . show
-- | Create a 'Scope' from a textual list of scopes
scopeFromList :: [Text] -> Scope
scopeFromList scopes = Scope { getScopes = scopes }
-- * Available Spotify Web API Scopes
-- | Read access to user's private playlists.
playlistReadPrivate :: Text
playlistReadPrivate = "playlist-read-private"
-- | Include collaborative playlists when requesting a user's playlists.
playlistReadCollaborative :: Text
playlistReadCollaborative = "playlist-read-collaborative"
-- | Write access to a user's public playlists.
playlistModifyPublic :: Text
playlistModifyPublic = "playlist-modify-public"
-- | Write access to a user's private playlists.
playlistModifyPrivate :: Text
playlistModifyPrivate = "playlist-modify-private"
-- | Control playback of a Spotify track. This scope is currently only available
-- to Spotify native SDKs (for example, the iOS SDK and the Android SDK). The
-- user must have a Spotify Premium account.
streaming :: Text
streaming = "streaming"
-- | Write/delete access to the list of artists and other users that the user follows.
userFollowModify :: Text
userFollowModify = "user-follow-modify"
-- | Read access to the list of artists and other users that the user follows.
userFollowRead :: Text
userFollowRead = "user-follow-read"
-- | Read access to a user's 'Your Music' library.
userLibraryRead :: Text
userLibraryRead = "user-library-read"
-- | Write/delete access to a user's 'Your Music' library.
userLibraryModify :: Text
userLibraryModify = "user-library-modify"
-- | Read access to user's subscription details (type of user account).
userReadPrivate :: Text
userReadPrivate = "user-read-private"
-- | Read access to the user's birthdate.
userReadBirthdate :: Text
userReadBirthdate = "user-read-birthdate"
-- | Read access to user's email address.
userReadEmail :: Text
userReadEmail = "user-read-email"
-- | Read access to a user's top artists and tracks
userTopRead :: Text
userTopRead = "user-top-read"
| chances/servant-spotify | src/Network/Spotify/Api/Types/Scope.hs | bsd-3-clause | 3,257 | 0 | 15 | 580 | 388 | 234 | 154 | 46 | 1 |
import Test.Hspec (hspec)
import ParseTest (parseSpecs)
import GeometryTest (geometrySpecs)
main :: IO ()
main = hspec $ do
parseSpecs
geometrySpecs
| albertov/kml2obj | tests/main.hs | bsd-3-clause | 155 | 0 | 7 | 26 | 52 | 28 | 24 | 7 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE QuasiQuotes #-}
module Horbits.UI.Camera.Trace(logCamera, orthoCameraColatitudeDeg, orthoCameraLongitudeDeg) where
import Control.Lens
import Data.Foldable (mapM_)
import Data.StateVar
import Linear
import Prelude hiding (mapM_)
import Text.Printf.TH
import Horbits.Data.Binding
import Horbits.UI.Camera.Internal
degrees :: (Floating a) => Iso' a a
degrees = iso (* (180 / pi)) (* (pi / 180))
orthoCameraColatitudeDeg :: Floating a => Lens' (OrthoCamera a) a
orthoCameraColatitudeDeg = orthoCameraColatitude . degrees
orthoCameraLongitudeDeg :: Floating a => Lens' (OrthoCamera a) a
orthoCameraLongitudeDeg = orthoCameraLongitude . degrees
logCamera :: (HasGetter v (OrthoCamera a), Show a, RealFloat a, Epsilon a) => v -> IO ()
logCamera cam = do
c <- readVar cam
putStrLn $ [s|O: %.2e %.2e %.2e|] (c ^. orthoCameraCenter . _x)
(c ^. orthoCameraCenter . _y)
(c ^. orthoCameraCenter . _z)
putStrLn $ [s|r: %.2e th: %.2e la: %.2e|] (c ^. orthoCameraScale)
(c ^. orthoCameraLongitudeDeg)
(c ^. orthoCameraColatitudeDeg)
mapM_ showMRow . orthoCameraMatrix $ c
where
showMRow (V4 x y z w) = putStrLn $ [s|%8.2e %8.2e %8.2e %8.2e|] x y z w
| chwthewke/horbits | src/horbits/Horbits/UI/Camera/Trace.hs | bsd-3-clause | 1,499 | 0 | 11 | 483 | 397 | 219 | 178 | -1 | -1 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-|
Module : Numeric.AERN.RealArithmetic.Basis.MPFR.FieldOps
Description : rounded arithmetic instances for MPFR
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : portable
Rounded arithmetic instances for MPFR.
This is a private module reexported publicly via its parent.
-}
module Numeric.AERN.RealArithmetic.Basis.MPFR.FieldOps
()
where
import Numeric.AERN.RealArithmetic.Basis.MPFR.Basics
import Numeric.AERN.RealArithmetic.Basis.MPFR.ExactOps
import Numeric.AERN.RealArithmetic.Basis.MPFR.NumericOrder
import Numeric.AERN.RealArithmetic.Basis.MPFR.Utilities
import Numeric.AERN.RealArithmetic.NumericOrderRounding
import Numeric.AERN.Basics.Effort
import Numeric.AERN.Misc.Debug
instance RoundedAddEffort MPFR where
type AddEffortIndicator MPFR = ()
addDefaultEffort _ = ()
instance RoundedAdd MPFR where
addUpEff _ d1 d2 =
detectNaNUp ("addition " ++ show d1 ++ " +^ " ++ show d2 ) $
liftRoundedToMPFR2 "+^" (+) d1 d2
addDnEff _ d1 d2 =
detectNaNDn ("addition " ++ show d1 ++ " +. " ++ show d2 ) $
liftRoundedToMPFR2 "+." (\ a b -> -((-a) + (-b))) d1 d2
instance RoundedSubtr MPFR
instance RoundedAbsEffort MPFR where
type AbsEffortIndicator MPFR = ()
absDefaultEffort _ = ()
instance RoundedAbs MPFR where
absDnEff _ = liftRoundedToMPFR1 abs
absUpEff _ = liftRoundedToMPFR1 abs
instance RoundedMultiplyEffort MPFR where
type MultEffortIndicator MPFR = ()
multDefaultEffort _ = ()
instance RoundedMultiply MPFR where
multUpEff _ d1 d2 =
-- unsafePrintReturn
-- (
-- "MPFR multiplication UP with prec = " ++ show prec
-- ++ " " ++ show d1 ++ " * " ++ show d2 ++ " = "
-- ) $
detectNaNUp ("multiplication " ++ show d1 ++ " *^ " ++ show d2 ) $
liftRoundedToMPFR2 "*^" (*) d1 d2
multDnEff _ d1 d2 =
-- unsafePrintReturn
-- (
-- "MPFR multiplication DOWN with prec = " ++ show prec
-- ++ " " ++ show d1 ++ " * " ++ show d2 ++ " = "
-- ) $
detectNaNDn ("multiplication " ++ show d1 ++ " *. " ++ show d2 ) $
liftRoundedToMPFR2 "*." (\ a b -> -((-a) * b)) d1 d2
instance RoundedPowerNonnegToNonnegIntEffort MPFR where
type PowerNonnegToNonnegIntEffortIndicator MPFR = ()
powerNonnegToNonnegIntDefaultEffort _ = ()
instance RoundedPowerNonnegToNonnegInt MPFR where
-- TODO: add to rounded an interface to MPFR powi
powerNonnegToNonnegIntUpEff _ =
powerNonnegToNonnegIntUpEffFromMult ()
-- M.powi M.Up (M.getPrec x) x n
powerNonnegToNonnegIntDnEff _ =
powerNonnegToNonnegIntDnEffFromMult ()
-- M.powi M.Down (M.getPrec x) x n
instance RoundedPowerToNonnegIntEffort MPFR where
type PowerToNonnegIntEffortIndicator MPFR = ()
powerToNonnegIntDefaultEffort _ = ()
instance RoundedPowerToNonnegInt MPFR where
-- TODO: add to rounded an interface to MPFR powi
powerToNonnegIntUpEff _ =
powerToNonnegIntUpEffFromMult ((),(),())
-- M.powi M.Up (M.getPrec x) x n
powerToNonnegIntDnEff _ =
powerToNonnegIntDnEffFromMult ((),(),())
-- M.powi M.Down (M.getPrec x) x n
instance RoundedDivideEffort MPFR where
type DivEffortIndicator MPFR = ()
divDefaultEffort _ = ()
instance RoundedDivide MPFR where
divUpEff _ d1 d2 =
detectNaNUp ("division " ++ show d1 ++ " *^ " ++ show d2 ) $
liftRoundedToMPFR2 "/^" (/) d1 d2
divDnEff _ d1 d2 =
detectNaNDn ("division " ++ show d1 ++ " *. " ++ show d2 ) $
liftRoundedToMPFR2 "/." (\ a b -> -((-a) / b)) d1 d2
instance RoundedRingEffort MPFR
where
type RingOpsEffortIndicator MPFR = ()
ringOpsDefaultEffort _ = ()
ringEffortAdd _ _ = ()
ringEffortMult _ _ = ()
ringEffortPow _ _ = ()
instance RoundedRing MPFR
instance RoundedFieldEffort MPFR
where
type FieldOpsEffortIndicator MPFR = ()
fieldOpsDefaultEffort _ = ()
fldEffortAdd _ _ = ()
fldEffortMult _ _ = ()
fldEffortPow _ _ = ()
fldEffortDiv _ _ = ()
instance RoundedField MPFR
| michalkonecny/aern | aern-mpfr-rounded/src/Numeric/AERN/RealArithmetic/Basis/MPFR/FieldOps.hs | bsd-3-clause | 4,335 | 0 | 14 | 1,105 | 951 | 506 | 445 | 79 | 0 |
module Sexy.Instances.Nil.Function where
import Sexy.Classes (Nil(..))
instance (Nil b) => Nil (a -> b) where
nil = (\_ -> nil)
| DanBurton/sexy | src/Sexy/Instances/Nil/Function.hs | bsd-3-clause | 133 | 0 | 7 | 25 | 59 | 36 | 23 | 4 | 0 |
module Graphics.Gnuplot.Frame.OptionSet (
OptionSet.T,
deflt,
OptionSet.add,
OptionSet.remove,
OptionSet.boolean,
OptionSet.addBool,
size,
title,
key,
keyInside,
keyOutside,
xRange2d,
yRange2d,
xRange3d,
yRange3d,
zRange3d,
xLabel,
yLabel,
zLabel,
xTicks2d,
yTicks2d,
xTicks3d,
yTicks3d,
zTicks3d,
xLogScale,
yLogScale,
zLogScale,
grid,
gridXTicks,
gridYTicks,
gridZTicks,
xFormat,
yFormat,
zFormat,
view,
viewMap,
boxwidthRelative,
boxwidthAbsolute,
tmargin,
bmargin,
lmargin,
rmargin,
margin,
) where
import qualified Graphics.Gnuplot.Graph.ThreeDimensional as Graph3D
import qualified Graphics.Gnuplot.Graph.TwoDimensional as Graph2D
import qualified Graphics.Gnuplot.Private.FrameOptionSet as OptionSet
import qualified Graphics.Gnuplot.Private.FrameOption as Option
import qualified Graphics.Gnuplot.Private.Graph as Graph
import qualified Graphics.Gnuplot.Value.Atom as Atom
import qualified Graphics.Gnuplot.Value.Tuple as Tuple
import Graphics.Gnuplot.Private.FrameOptionSet (T, )
import Graphics.Gnuplot.Utility (quote, )
import qualified Data.List as List
deflt :: Graph.C graph => T graph
deflt = Graph.defltOptions
size :: Graph.C graph => Double -> Double -> T graph -> T graph
size x y =
OptionSet.add Option.sizeScale [show x ++ ", " ++ show y]
title :: Graph.C graph => String -> T graph -> T graph
title text =
OptionSet.add Option.title [quote text]
key :: Graph.C graph => Bool -> T graph -> T graph
key = OptionSet.boolean Option.keyShow
keyInside :: Graph.C graph => T graph -> T graph
keyInside = OptionSet.add Option.keyPosition ["inside"]
keyOutside :: Graph.C graph => T graph -> T graph
keyOutside = OptionSet.add Option.keyPosition ["outside"]
{-
xRange :: Graph.C graph => (Double, Double) -> T graph -> T graph
xRange = range Option.xRange
yRange :: Graph.C graph => (Double, Double) -> T graph -> T graph
yRange = range Option.yRange
zRange :: (Double, Double) -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
zRange = range Option.zRange
-}
xRange2d ::
(Atom.C x, Atom.C y, Tuple.C x) =>
(x, x) -> T (Graph2D.T x y) -> T (Graph2D.T x y)
xRange2d = range Option.xRangeBounds
yRange2d ::
(Atom.C x, Atom.C y, Tuple.C y) =>
(y, y) -> T (Graph2D.T x y) -> T (Graph2D.T x y)
yRange2d = range Option.yRangeBounds
xRange3d ::
(Atom.C x, Atom.C y, Atom.C z, Tuple.C x) =>
(x, x) -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
xRange3d = range Option.xRangeBounds
yRange3d ::
(Atom.C x, Atom.C y, Atom.C z, Tuple.C y) =>
(y, y) -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
yRange3d = range Option.yRangeBounds
zRange3d ::
(Atom.C x, Atom.C y, Atom.C z, Tuple.C z) =>
(z, z) -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
zRange3d = range Option.zRangeBounds
range ::
(Atom.C a, Tuple.C a, Graph.C graph) =>
Option.T -> (a, a) -> T graph -> T graph
range opt (x,y) =
OptionSet.add opt
[showString "[" . atomText x .
showString ":" . atomText y $
"]"]
atomText ::
(Atom.C a, Tuple.C a) =>
a -> ShowS
atomText x =
case Tuple.text x of
[s] -> s
_ -> error "OptionSet.fromSingleton: types of Atom class must generate single representation texts"
xLabel :: Graph.C graph => String -> T graph -> T graph
xLabel = label Option.xLabelText
yLabel :: Graph.C graph => String -> T graph -> T graph
yLabel = label Option.yLabelText
zLabel ::
(Atom.C x, Atom.C y, Atom.C z) =>
String -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
zLabel = label Option.zLabelText
label :: Graph.C graph => Option.T -> String -> T graph -> T graph
label opt x =
OptionSet.add opt [quote x]
xFormat :: Graph.C graph => String -> T graph -> T graph
xFormat = format Option.xFormat
yFormat :: Graph.C graph => String -> T graph -> T graph
yFormat = format Option.yFormat
zFormat ::
(Atom.C x, Atom.C y, Atom.C z) =>
String -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
zFormat = format Option.zFormat
format :: Graph.C graph => Option.T -> String -> T graph -> T graph
format opt x =
OptionSet.add opt [quote x]
{- |
Set parameters of viewing a surface graph.
See <info:gnuplot/view>
-}
view ::
Double {- ^ rotateX -} ->
Double {- ^ rotateZ -} ->
Double {- ^ scale -} ->
Double {- ^ scaleZ -} ->
T (Graph3D.T x y z) -> T (Graph3D.T x y z)
view rotateX rotateZ scale scaleZ =
OptionSet.add Option.view [show rotateX, show rotateZ, show scale, show scaleZ]
{- |
Show flat pixel map.
-}
viewMap :: T (Graph3D.T x y z) -> T (Graph3D.T x y z)
viewMap =
OptionSet.add Option.view ["map"]
xTicks2d ::
(Atom.C x, Atom.C y, Tuple.C x) =>
[(String, x)] -> T (Graph2D.T x y) -> T (Graph2D.T x y)
xTicks2d = ticks Option.xTickLabels
yTicks2d ::
(Atom.C x, Atom.C y, Tuple.C y) =>
[(String, y)] -> T (Graph2D.T x y) -> T (Graph2D.T x y)
yTicks2d = ticks Option.yTickLabels
xTicks3d ::
(Atom.C x, Atom.C y, Atom.C z, Tuple.C x) =>
[(String, x)] -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
xTicks3d = ticks Option.xTickLabels
yTicks3d ::
(Atom.C x, Atom.C y, Atom.C z, Tuple.C y) =>
[(String, y)] -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
yTicks3d = ticks Option.yTickLabels
zTicks3d ::
(Atom.C x, Atom.C y, Atom.C z, Tuple.C z) =>
[(String, z)] -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
zTicks3d = ticks Option.zTickLabels
ticks ::
(Atom.C a, Tuple.C a, Graph.C graph) =>
Option.T -> [(String, a)] -> T graph -> T graph
ticks opt labels =
OptionSet.add opt
[('(' :) $ foldr ($) ")" $
List.intersperse (showString ", ") $
map
(\(lab,pos) ->
showString (quote lab) .
showString " " .
atomText pos)
labels]
xLogScale :: Graph.C graph => T graph -> T graph
xLogScale = OptionSet.add Option.xLogScale []
yLogScale :: Graph.C graph => T graph -> T graph
yLogScale = OptionSet.add Option.yLogScale []
zLogScale ::
(Atom.C x, Atom.C y, Atom.C z) =>
T (Graph3D.T x y z) -> T (Graph3D.T x y z)
zLogScale = OptionSet.add Option.zLogScale []
grid :: Graph.C graph => Bool -> T graph -> T graph
grid b =
OptionSet.addBool Option.gridXTicks b .
OptionSet.addBool Option.gridYTicks b .
OptionSet.addBool Option.gridZTicks b
gridXTicks :: Graph.C graph => Bool -> T graph -> T graph
gridXTicks = OptionSet.addBool Option.gridXTicks
gridYTicks :: Graph.C graph => Bool -> T graph -> T graph
gridYTicks = OptionSet.addBool Option.gridYTicks
gridZTicks ::
(Atom.C x, Atom.C y, Atom.C z) =>
Bool -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
gridZTicks = OptionSet.addBool Option.gridZTicks
boxwidthRelative ::
(Graph.C graph) =>
Double -> T graph -> T graph
boxwidthRelative width =
OptionSet.add Option.boxwidth [show width, "relative"]
boxwidthAbsolute ::
(Graph.C graph) =>
Double -> T graph -> T graph
boxwidthAbsolute width =
OptionSet.add Option.boxwidth [show width, "absolute"]
tmargin :: Graph.C graph => Int -> T graph -> T graph
tmargin x =
OptionSet.add (Option.tmargin "") [show x]
bmargin :: Graph.C graph => Int -> T graph -> T graph
bmargin x =
OptionSet.add (Option.bmargin "") [show x]
lmargin :: Graph.C graph => Int -> T graph -> T graph
lmargin x =
OptionSet.add (Option.lmargin "") [show x]
rmargin :: Graph.C graph => Int -> T graph -> T graph
rmargin x =
OptionSet.add (Option.rmargin "") [show x]
margin :: Graph.C graph => Int -> T graph -> T graph
margin x = tmargin x . bmargin x . lmargin x . rmargin x
{-
cornerToColor :: CornersToColor -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
type3d :: Plot3dType -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
-}
| kubkon/gnuplot | src/Graphics/Gnuplot/Frame/OptionSet.hs | bsd-3-clause | 7,742 | 0 | 15 | 1,717 | 3,144 | 1,614 | 1,530 | 214 | 2 |
-- |
-- This module reexports most of the types from \"containers\",
-- \"unordered-containers\", \"array\", and \"vector\". No
-- functions are exported.
--
module Prelude.Containers.Types
( module E
) where
-- array types
import Data.Array as E (Array)
import Data.Array.IArray as E (IArray)
import Data.Array.IO as E (IOArray,IOUArray)
import Data.Array.MArray as E (MArray)
import Data.Array.ST as E (STArray,STUArray)
import Data.Array.Storable as E (StorableArray)
import Data.Array.Unboxed as E (UArray)
-- containers
import Data.IntMap as E (IntMap)
import Data.IntSet as E (IntSet)
import Data.Map as E (Map)
import Data.Sequence as E (Seq)
import Data.Set as E (Set)
import Data.Tree as E (Tree)
-- unordered-containers
import Data.HashMap.Strict as E (HashMap)
import Data.HashSet as E (HashSet)
-- vector
import Data.Vector as E (Vector)
import Data.Vector.Mutable as E (MVector,IOVector,STVector)
| andrewthad/lens-prelude | src/Prelude/Containers/Types.hs | bsd-3-clause | 953 | 0 | 5 | 167 | 246 | 170 | 76 | 19 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module Webcrank.Internal.ReqData where
import Control.Applicative
import Control.Lens
import Control.Monad.State
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LB
import qualified Data.HashMap.Strict as HashMap
import Data.Maybe
import Network.HTTP.Media
import Network.HTTP.Types
import Prelude
import Webcrank.Internal.Types
-- | Smart constructor for creating a @ReqData@ value with initial values.
newReqData :: ReqData
newReqData = ReqData
{ _reqDataDispPath = []
, _reqDataRespMediaType = "application" // "octet-stream"
, _reqDataRespCharset = Nothing
, _reqDataRespEncoding = Nothing
, _reqDataRespHeaders = HashMap.empty
, _reqDataRespBody = Nothing
}
-- | Lookup a response header.
getResponseHeader
:: (Functor m, MonadState s m, HasReqData s)
=> HeaderName
-> m (Maybe ByteString)
getResponseHeader h = (listToMaybe =<<) . HashMap.lookup h <$> use reqDataRespHeaders
-- | Replace any existing response headers for the header name with the
-- new value.
putResponseHeader
:: (MonadState s m, HasReqData s)
=> HeaderName
-> ByteString
-> m ()
putResponseHeader h v = reqDataRespHeaders %= HashMap.insert h [v]
-- | Replace any existing response headers for the header name with the
-- new values.
putResponseHeaders
:: (MonadState s m, HasReqData s)
=> ResponseHeaders
-> m ()
putResponseHeaders = mapM_ (uncurry putResponseHeader)
-- | Remove the response header.
removeResponseHeader
:: (MonadState s m, HasReqData s)
=> HeaderName
-> m ()
removeResponseHeader h = reqDataRespHeaders %= HashMap.delete h
-- | Lookup the response @Location@ header.
getResponseLocation
:: (Functor m, MonadState s m, HasReqData s)
=> m (Maybe ByteString)
getResponseLocation = getResponseHeader hLocation
-- | Set the response @Location@ header.
putResponseLocation
:: (MonadState s m, HasReqData s)
=> ByteString
-> m ()
putResponseLocation = putResponseHeader hLocation
-- | Use the lazy @ByteString@ as the response body.
writeLBS
:: (MonadState s m, HasReqData s)
=> LB.ByteString
-> m ()
writeLBS = (reqDataRespBody ?=)
| webcrank/webcrank.hs | src/Webcrank/Internal/ReqData.hs | bsd-3-clause | 2,186 | 0 | 9 | 355 | 492 | 277 | 215 | 57 | 1 |
{-# LANGUAGE ScopedTypeVariables, GeneralizedNewtypeDeriving, TypeSynonymInstances, FlexibleInstances, OverlappingInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Actions.GridSelect
-- Copyright : Clemens Fruhwirth <[email protected]>
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Clemens Fruhwirth <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- GridSelect displays items(e.g. the opened windows) in a 2D grid and lets
-- the user select from it with the cursor/hjkl keys or the mouse.
--
-----------------------------------------------------------------------------
module XMonad.Actions.GridSelect (
-- * Usage
-- $usage
-- ** Customizing
-- *** Using a common GSConfig
-- $commonGSConfig
-- *** Custom keybindings
-- $keybindings
-- * Configuration
GSConfig(..),
defaultGSConfig,
TwoDPosition,
buildDefaultGSConfig,
-- * Variations on 'gridselect'
gridselect,
gridselectWindow,
withSelectedWindow,
bringSelected,
goToSelected,
gridselectWorkspace,
spawnSelected,
runSelectedAction,
-- * Colorizers
HasColorizer(defaultColorizer),
fromClassName,
stringColorizer,
colorRangeFromClassName,
-- * Navigation Mode assembly
TwoD,
makeXEventhandler,
shadowWithKeymap,
-- * Built-in Navigation Mode
defaultNavigation,
substringSearch,
navNSearch,
-- * Navigation Components
setPos,
move,
select,
cancel,
transformSearchString
-- * Screenshots
-- $screenshots
) where
import Data.Maybe
import Data.Bits
import Data.Char
import Control.Applicative
import Control.Monad.State
import Control.Arrow
import Data.List as L
import qualified Data.Map as M
import XMonad hiding (liftX)
import XMonad.Util.Font
import XMonad.Prompt (mkUnmanagedWindow)
import XMonad.StackSet as W
import XMonad.Layout.Decoration
import XMonad.Util.NamedWindows
import XMonad.Actions.WindowBringer (bringWindow)
import Text.Printf
import System.Random (mkStdGen, genRange, next)
import Data.Word (Word8)
-- $usage
--
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Actions.GridSelect
--
-- Then add a keybinding, e.g.
--
-- > , ((modm, xK_g), goToSelected defaultGSConfig)
--
-- This module also supports displaying arbitrary information in a grid and letting
-- the user select from it. E.g. to spawn an application from a given list, you
-- can use the following:
--
-- > , ((modm, xK_s), spawnSelected defaultGSConfig ["xterm","gmplayer","gvim"])
-- $commonGSConfig
--
-- It is possible to bind a @gsconfig@ at top-level in your configuration. Like so:
--
-- > -- the top of your config
-- > {-# LANGUAGE NoMonomorphismRestriction #-}
-- > import XMonad
-- > ...
-- > gsconfig1 = defaultGSConfig { gs_cellheight = 30, gs_cellwidth = 100 }
--
-- An example where 'buildDefaultGSConfig' is used instead of 'defaultGSConfig'
-- in order to specify a custom colorizer is @gsconfig2@ (found in
-- "XMonad.Actions.GridSelect#Colorizers"):
--
-- > gsconfig2 colorizer = (buildDefaultGSConfig colorizer) { gs_cellheight = 30, gs_cellwidth = 100 }
--
-- > -- | A green monochrome colorizer based on window class
-- > greenColorizer = colorRangeFromClassName
-- > black -- lowest inactive bg
-- > (0x70,0xFF,0x70) -- highest inactive bg
-- > black -- active bg
-- > white -- inactive fg
-- > white -- active fg
-- > where black = minBound
-- > white = maxBound
--
-- Then you can bind to:
--
-- > ,((modm, xK_g), goToSelected $ gsconfig2 myWinColorizer)
-- > ,((modm, xK_p), spawnSelected $ spawnSelected defaultColorizer)
-- $keybindings
--
-- You can build you own navigation mode and submodes by combining the
-- exported action ingredients and assembling them using 'makeXEventhandler' and 'shadowWithKeymap'.
--
-- > myNavigation :: TwoD a (Maybe a)
-- > myNavigation = makeXEventhandler $ shadowWithKeymap navKeyMap navDefaultHandler
-- > where navKeyMap = M.fromList [
-- > ((0,xK_Escape), cancel)
-- > ,((0,xK_Return), select)
-- > ,((0,xK_slash) , substringSearch myNavigation)
-- > ,((0,xK_Left) , move (-1,0) >> myNavigation)
-- > ,((0,xK_h) , move (-1,0) >> myNavigation)
-- > ,((0,xK_Right) , move (1,0) >> myNavigation)
-- > ,((0,xK_l) , move (1,0) >> myNavigation)
-- > ,((0,xK_Down) , move (0,1) >> myNavigation)
-- > ,((0,xK_j) , move (0,1) >> myNavigation)
-- > ,((0,xK_Up) , move (0,-1) >> myNavigation)
-- > ,((0,xK_y) , move (-1,-1) >> myNavigation)
-- > ,((0,xK_i) , move (1,-1) >> myNavigation)
-- > ,((0,xK_n) , move (-1,1) >> myNavigation)
-- > ,((0,xK_m) , move (1,-1) >> myNavigation)
-- > ,((0,xK_space) , setPos (0,0) >> myNavigation)
-- > ]
-- > -- The navigation handler ignores unknown key symbols
-- > navDefaultHandler = const myNavigation
--
-- You can then define @gsconfig3@ which may be used in exactly the same manner as @gsconfig1@:
--
-- > gsconfig3 = defaultGSConfig
-- > { gs_cellheight = 30
-- > , gs_cellwidth = 100
-- > , gs_navigate = myNavigation
-- > }
-- $screenshots
--
-- Selecting a workspace:
--
-- <<http://haskell.org/wikiupload/a/a9/Xmonad-gridselect-workspace.png>>
--
-- Selecting a window by title:
--
-- <<http://haskell.org/wikiupload/3/35/Xmonad-gridselect-window-aavogt.png>>
data GSConfig a = GSConfig {
gs_cellheight :: Integer,
gs_cellwidth :: Integer,
gs_cellpadding :: Integer,
gs_colorizer :: a -> Bool -> X (String, String),
gs_font :: String,
gs_navigate :: TwoD a (Maybe a),
gs_originFractX :: Double,
gs_originFractY :: Double
}
-- | That is 'fromClassName' if you are selecting a 'Window', or
-- 'defaultColorizer' if you are selecting a 'String'. The catch-all instance
-- @HasColorizer a@ uses the 'focusedBorderColor' and 'normalBorderColor'
-- colors.
class HasColorizer a where
defaultColorizer :: a -> Bool -> X (String, String)
instance HasColorizer Window where
defaultColorizer = fromClassName
instance HasColorizer String where
defaultColorizer = stringColorizer
instance HasColorizer a where
defaultColorizer _ isFg =
let getColor = if isFg then focusedBorderColor else normalBorderColor
in asks $ flip (,) "black" . getColor . config
-- | A basic configuration for 'gridselect', with the colorizer chosen based on the type.
--
-- If you want to replace the 'gs_colorizer' field, use 'buildDefaultGSConfig'
-- instead, to avoid ambiguous type variables.
defaultGSConfig :: HasColorizer a => GSConfig a
defaultGSConfig = buildDefaultGSConfig defaultColorizer
type TwoDPosition = (Integer, Integer)
type TwoDElementMap a = [(TwoDPosition,(String,a))]
data TwoDState a = TwoDState { td_curpos :: TwoDPosition
, td_availSlots :: [TwoDPosition]
, td_elements :: [(String,a)]
, td_gsconfig :: GSConfig a
, td_font :: XMonadFont
, td_paneX :: Integer
, td_paneY :: Integer
, td_drawingWin :: Window
, td_searchString :: String
}
td_elementmap :: TwoDState a -> [(TwoDPosition,(String,a))]
td_elementmap s =
let positions = td_availSlots s
elements = L.filter (((td_searchString s) `isSubstringOf`) . fst) (td_elements s)
in zipWith (,) positions elements
where sub `isSubstringOf` string = or [ (upper sub) `isPrefixOf` t | t <- tails (upper string) ]
upper = map toUpper
newtype TwoD a b = TwoD { unTwoD :: StateT (TwoDState a) X b }
deriving (Monad,Functor,MonadState (TwoDState a))
instance Applicative (TwoD a) where
(<*>) = ap
pure = return
liftX :: X a1 -> TwoD a a1
liftX = TwoD . lift
evalTwoD :: TwoD a1 a -> TwoDState a1 -> X a
evalTwoD m s = flip evalStateT s $ unTwoD m
diamondLayer :: (Enum b', Num b') => b' -> [(b', b')]
diamondLayer 0 = [(0,0)]
diamondLayer n =
-- tr = top right
-- r = ur ++ 90 degree clock-wise rotation of ur
let tr = [ (x,n-x) | x <- [0..n-1] ]
r = tr ++ (map (\(x,y) -> (y,-x)) tr)
in r ++ (map (negate *** negate) r)
diamond :: (Enum a, Num a) => [(a, a)]
diamond = concatMap diamondLayer [0..]
diamondRestrict :: Integer -> Integer -> Integer -> Integer -> [(Integer, Integer)]
diamondRestrict x y originX originY =
L.filter (\(x',y') -> abs x' <= x && abs y' <= y) .
map (\(x', y') -> (x' + fromInteger originX, y' + fromInteger originY)) .
take 1000 $ diamond
findInElementMap :: (Eq a) => a -> [(a, b)] -> Maybe (a, b)
findInElementMap pos = find ((== pos) . fst)
drawWinBox :: Window -> XMonadFont -> (String, String) -> Integer -> Integer -> String -> Integer -> Integer -> Integer -> X ()
drawWinBox win font (fg,bg) ch cw text x y cp =
withDisplay $ \dpy -> do
gc <- liftIO $ createGC dpy win
bordergc <- liftIO $ createGC dpy win
liftIO $ do
Just fgcolor <- initColor dpy fg
Just bgcolor <- initColor dpy bg
Just bordercolor <- initColor dpy borderColor
setForeground dpy gc fgcolor
setBackground dpy gc bgcolor
setForeground dpy bordergc bordercolor
fillRectangle dpy win gc (fromInteger x) (fromInteger y) (fromInteger cw) (fromInteger ch)
drawRectangle dpy win bordergc (fromInteger x) (fromInteger y) (fromInteger cw) (fromInteger ch)
stext <- shrinkWhile (shrinkIt shrinkText)
(\n -> do size <- liftIO $ textWidthXMF dpy font n
return $ size > (fromInteger (cw-(2*cp))))
text
printStringXMF dpy win font gc bg fg (fromInteger (x+cp)) (fromInteger (y+(div ch 2))) stext
liftIO $ freeGC dpy gc
liftIO $ freeGC dpy bordergc
updateAllElements :: TwoD a ()
updateAllElements =
do
s <- get
updateElements (td_elementmap s)
grayoutAllElements :: TwoD a ()
grayoutAllElements =
do
s <- get
updateElementsWithColorizer grayOnly (td_elementmap s)
where grayOnly _ _ = return ("#808080", "#808080")
updateElements :: TwoDElementMap a -> TwoD a ()
updateElements elementmap = do
s <- get
updateElementsWithColorizer (gs_colorizer (td_gsconfig s)) elementmap
updateElementsWithColorizer :: (a -> Bool -> X (String, String)) -> TwoDElementMap a -> TwoD a ()
updateElementsWithColorizer colorizer elementmap = do
TwoDState { td_curpos = curpos,
td_drawingWin = win,
td_gsconfig = gsconfig,
td_font = font,
td_paneX = paneX,
td_paneY = paneY} <- get
let cellwidth = gs_cellwidth gsconfig
cellheight = gs_cellheight gsconfig
paneX' = div (paneX-cellwidth) 2
paneY' = div (paneY-cellheight) 2
updateElement (pos@(x,y),(text, element)) = liftX $ do
colors <- colorizer element (pos == curpos)
drawWinBox win font
colors
cellheight
cellwidth
text
(paneX'+x*cellwidth)
(paneY'+y*cellheight)
(gs_cellpadding gsconfig)
mapM_ updateElement elementmap
stdHandle :: Event -> TwoD a (Maybe a) -> TwoD a (Maybe a)
stdHandle (ButtonEvent { ev_event_type = t, ev_x = x, ev_y = y }) contEventloop
| t == buttonRelease = do
s @ TwoDState { td_paneX = px, td_paneY = py,
td_gsconfig = (GSConfig ch cw _ _ _ _ _ _) } <- get
let gridX = (fi x - (px - cw) `div` 2) `div` cw
gridY = (fi y - (py - ch) `div` 2) `div` ch
case lookup (gridX,gridY) (td_elementmap s) of
Just (_,el) -> return (Just el)
Nothing -> contEventloop
| otherwise = contEventloop
stdHandle (ExposeEvent { }) contEventloop = updateAllElements >> contEventloop
stdHandle _ contEventloop = contEventloop
-- | Embeds a key handler into the X event handler that dispatches key
-- events to the key handler, while non-key event go to the standard
-- handler.
makeXEventhandler :: ((KeySym, String, KeyMask) -> TwoD a (Maybe a)) -> TwoD a (Maybe a)
makeXEventhandler keyhandler = fix $ \me -> join $ liftX $ withDisplay $ \d -> liftIO $ allocaXEvent $ \e -> do
maskEvent d (exposureMask .|. keyPressMask .|. buttonReleaseMask) e
ev <- getEvent e
if ev_event_type ev == keyPress
then do
(ks,s) <- lookupString $ asKeyEvent e
return $ do
mask <- liftX $ cleanMask (ev_state ev)
keyhandler (fromMaybe xK_VoidSymbol ks, s, mask)
else
return $ stdHandle ev me
-- | When the map contains (KeySym,KeyMask) tuple for the given event,
-- the associated action in the map associated shadows the default key
-- handler
shadowWithKeymap :: M.Map (KeyMask, KeySym) a -> ((KeySym, String, KeyMask) -> a) -> (KeySym, String, KeyMask) -> a
shadowWithKeymap keymap dflt keyEvent@(ks,_,m') = fromMaybe (dflt keyEvent) (M.lookup (m',ks) keymap)
-- Helper functions to use for key handler functions
-- | Closes gridselect returning the element under the cursor
select :: TwoD a (Maybe a)
select = do
s <- get
return $ fmap (snd . snd) $ findInElementMap (td_curpos s) (td_elementmap s)
-- | Closes gridselect returning no element.
cancel :: TwoD a (Maybe a)
cancel = return Nothing
-- | Sets the absolute position of the cursor.
setPos :: (Integer, Integer) -> TwoD a ()
setPos newPos = do
s <- get
let elmap = td_elementmap s
newSelectedEl = findInElementMap newPos (td_elementmap s)
oldPos = td_curpos s
when (isJust newSelectedEl && newPos /= oldPos) $ do
put s { td_curpos = newPos }
updateElements (catMaybes [(findInElementMap oldPos elmap), newSelectedEl])
-- | Moves the cursor by the offsets specified
move :: (Integer, Integer) -> TwoD a ()
move (dx,dy) = do
s <- get
let (x,y) = td_curpos s
newPos = (x+dx,y+dy)
setPos newPos
-- | Apply a transformation function the current search string
transformSearchString :: (String -> String) -> TwoD a ()
transformSearchString f = do
s <- get
let oldSearchString = td_searchString s
newSearchString = f oldSearchString
when (newSearchString /= oldSearchString) $ do
-- FIXME: grayoutAllElements + updateAllElements paint some fields twice causing flickering
-- we would need a much smarter update strategy to fix that
when (length newSearchString > length oldSearchString) grayoutAllElements
-- FIXME curpos might end up outside new bounds
put s { td_searchString = newSearchString }
updateAllElements
-- | By default gridselect used the defaultNavigation action, which
-- binds left,right,up,down and vi-style h,l,j,k navigation. Return
-- quits gridselect, returning the selected element, while Escape
-- cancels the selection. Slash enters the substring search mode. In
-- substring search mode, every string-associated keystroke is
-- added to a search string, which narrows down the object
-- selection. Substring search mode comes back to regular navigation
-- via Return, while Escape cancels the search. If you want that
-- navigation style, add 'defaultNavigation' as 'gs_navigate' to your
-- 'GSConfig' object. This is done by 'buildDefaultGSConfig' automatically.
defaultNavigation :: TwoD a (Maybe a)
defaultNavigation = makeXEventhandler $ shadowWithKeymap navKeyMap navDefaultHandler
where navKeyMap = M.fromList [
((0,xK_Escape), cancel)
,((0,xK_Return), select)
,((0,xK_slash) , substringSearch defaultNavigation)
,((0,xK_Left) , move (-1,0) >> defaultNavigation)
,((0,xK_h) , move (-1,0) >> defaultNavigation)
,((0,xK_Right) , move (1,0) >> defaultNavigation)
,((0,xK_l) , move (1,0) >> defaultNavigation)
,((0,xK_Down) , move (0,1) >> defaultNavigation)
,((0,xK_j) , move (0,1) >> defaultNavigation)
,((0,xK_Up) , move (0,-1) >> defaultNavigation)
,((0,xK_k) , move (0,-1) >> defaultNavigation)
]
-- The navigation handler ignores unknown key symbols, therefore we const
navDefaultHandler = const defaultNavigation
-- | This navigation style combines navigation and search into one mode at the cost of losing vi style
-- navigation. With this style, there is no substring search submode,
-- but every typed character is added to the substring search.
navNSearch :: TwoD a (Maybe a)
navNSearch = makeXEventhandler $ shadowWithKeymap navNSearchKeyMap navNSearchDefaultHandler
where navNSearchKeyMap = M.fromList [
((0,xK_Escape), cancel)
,((0,xK_Return), select)
,((0,xK_Left) , move (-1,0) >> navNSearch)
,((0,xK_Right) , move (1,0) >> navNSearch)
,((0,xK_Down) , move (0,1) >> navNSearch)
,((0,xK_Up) , move (0,-1) >> navNSearch)
,((0,xK_BackSpace), transformSearchString (\s -> if (s == "") then "" else init s) >> navNSearch)
]
-- The navigation handler ignores unknown key symbols, therefore we const
navNSearchDefaultHandler (_,s,_) = do
transformSearchString (++ s)
navNSearch
-- | Navigation submode used for substring search. It returns to the
-- first argument navigation style when the user hits Return.
substringSearch :: TwoD a (Maybe a) -> TwoD a (Maybe a)
substringSearch returnNavigation = fix $ \me ->
let searchKeyMap = M.fromList [
((0,xK_Escape) , transformSearchString (const "") >> returnNavigation)
,((0,xK_Return) , returnNavigation)
,((0,xK_BackSpace), transformSearchString (\s -> if (s == "") then "" else init s) >> me)
]
searchDefaultHandler (_,s,_) = do
transformSearchString (++ s)
me
in makeXEventhandler $ shadowWithKeymap searchKeyMap searchDefaultHandler
-- FIXME probably move that into Utils?
-- Conversion scheme as in http://en.wikipedia.org/wiki/HSV_color_space
hsv2rgb :: Fractional a => (Integer,a,a) -> (a,a,a)
hsv2rgb (h,s,v) =
let hi = (div h 60) `mod` 6 :: Integer
f = (((fromInteger h)/60) - (fromInteger hi)) :: Fractional a => a
q = v * (1-f)
p = v * (1-s)
t = v * (1-(1-f)*s)
in case hi of
0 -> (v,t,p)
1 -> (q,v,p)
2 -> (p,v,t)
3 -> (p,q,v)
4 -> (t,p,v)
5 -> (v,p,q)
_ -> error "The world is ending. x mod a >= a."
-- | Default colorizer for Strings
stringColorizer :: String -> Bool -> X (String, String)
stringColorizer s active =
let seed x = toInteger (sum $ map ((*x).fromEnum) s) :: Integer
(r,g,b) = hsv2rgb ((seed 83) `mod` 360,
(fromInteger ((seed 191) `mod` 1000))/2500+0.4,
(fromInteger ((seed 121) `mod` 1000))/2500+0.4)
in if active
then return ("#faff69", "black")
else return ("#" ++ concat (map (twodigitHex.(round :: Double -> Word8).(*256)) [r, g, b] ), "white")
-- | Colorize a window depending on it's className.
fromClassName :: Window -> Bool -> X (String, String)
fromClassName w active = runQuery className w >>= flip defaultColorizer active
twodigitHex :: Word8 -> String
twodigitHex a = printf "%02x" a
-- | A colorizer that picks a color inside a range,
-- and depending on the window's class.
colorRangeFromClassName :: (Word8, Word8, Word8) -- ^ Beginning of the color range
-> (Word8, Word8, Word8) -- ^ End of the color range
-> (Word8, Word8, Word8) -- ^ Background of the active window
-> (Word8, Word8, Word8) -- ^ Inactive text color
-> (Word8, Word8, Word8) -- ^ Active text color
-> Window -> Bool -> X (String, String)
colorRangeFromClassName startC endC activeC inactiveT activeT w active =
do classname <- runQuery className w
if active
then return (rgbToHex activeC, rgbToHex activeT)
else return (rgbToHex $ mix startC endC
$ stringToRatio classname, rgbToHex inactiveT)
where rgbToHex :: (Word8, Word8, Word8) -> String
rgbToHex (r, g, b) = '#':twodigitHex r
++twodigitHex g++twodigitHex b
-- | Creates a mix of two colors according to a ratio
-- (1 -> first color, 0 -> second color).
mix :: (Word8, Word8, Word8) -> (Word8, Word8, Word8)
-> Double -> (Word8, Word8, Word8)
mix (r1, g1, b1) (r2, g2, b2) r = (mix' r1 r2, mix' g1 g2, mix' b1 b2)
where mix' a b = truncate $ (fi a * r) + (fi b * (1 - r))
-- | Generates a Double from a string, trying to
-- achieve a random distribution.
-- We create a random seed from the sum of all characters
-- in the string, and use it to generate a ratio between 0 and 1
stringToRatio :: String -> Double
stringToRatio "" = 0
stringToRatio s = let gen = mkStdGen $ sum $ map fromEnum s
range = (\(a, b) -> b - a) $ genRange gen
randomInt = foldr1 combine $ replicate 20 next
combine f1 f2 g = let (_, g') = f1 g in f2 g'
in fi (fst $ randomInt gen) / fi range
-- | Brings up a 2D grid of elements in the center of the screen, and one can
-- select an element with cursors keys. The selected element is returned.
gridselect :: GSConfig a -> [(String,a)] -> X (Maybe a)
gridselect _ [] = return Nothing
gridselect gsconfig elements =
withDisplay $ \dpy -> do
rootw <- asks theRoot
s <- gets $ screenRect . W.screenDetail . W.current . windowset
win <- liftIO $ mkUnmanagedWindow dpy (defaultScreenOfDisplay dpy) rootw
(rect_x s) (rect_y s) (rect_width s) (rect_height s)
liftIO $ mapWindow dpy win
liftIO $ selectInput dpy win (exposureMask .|. keyPressMask .|. buttonReleaseMask)
status <- io $ grabKeyboard dpy win True grabModeAsync grabModeAsync currentTime
io $ grabButton dpy button1 anyModifier win True buttonReleaseMask grabModeAsync grabModeAsync none none
font <- initXMF (gs_font gsconfig)
let screenWidth = toInteger $ rect_width s;
screenHeight = toInteger $ rect_height s;
selectedElement <- if (status == grabSuccess) then do
let restriction ss cs = (fromInteger ss/fromInteger (cs gsconfig)-1)/2 :: Double
restrictX = floor $ restriction screenWidth gs_cellwidth
restrictY = floor $ restriction screenHeight gs_cellheight
originPosX = floor $ ((gs_originFractX gsconfig) - (1/2)) * 2 * fromIntegral restrictX
originPosY = floor $ ((gs_originFractY gsconfig) - (1/2)) * 2 * fromIntegral restrictY
coords = diamondRestrict restrictX restrictY originPosX originPosY
evalTwoD (updateAllElements >> (gs_navigate gsconfig)) TwoDState { td_curpos = (head coords),
td_availSlots = coords,
td_elements = elements,
td_gsconfig = gsconfig,
td_font = font,
td_paneX = screenWidth,
td_paneY = screenHeight,
td_drawingWin = win,
td_searchString = "" }
else
return Nothing
liftIO $ do
unmapWindow dpy win
destroyWindow dpy win
sync dpy False
releaseXMF font
return selectedElement
-- | Like `gridSelect' but with the current windows and their titles as elements
gridselectWindow :: GSConfig Window -> X (Maybe Window)
gridselectWindow gsconf = windowMap >>= gridselect gsconf
-- | Brings up a 2D grid of windows in the center of the screen, and one can
-- select a window with cursors keys. The selected window is then passed to
-- a callback function.
withSelectedWindow :: (Window -> X ()) -> GSConfig Window -> X ()
withSelectedWindow callback conf = do
mbWindow <- gridselectWindow conf
case mbWindow of
Just w -> callback w
Nothing -> return ()
windowMap :: X [(String,Window)]
windowMap = do
ws <- gets windowset
wins <- mapM keyValuePair (W.allWindows ws)
return wins
where keyValuePair w = flip (,) w `fmap` decorateName' w
decorateName' :: Window -> X String
decorateName' w = do
fmap show $ getName w
-- | Builds a default gs config from a colorizer function.
buildDefaultGSConfig :: (a -> Bool -> X (String,String)) -> GSConfig a
buildDefaultGSConfig col = GSConfig 50 130 10 col "xft:Sans-8" defaultNavigation (1/2) (1/2)
borderColor :: String
borderColor = "white"
-- | Brings selected window to the current workspace.
bringSelected :: GSConfig Window -> X ()
bringSelected = withSelectedWindow $ \w -> do
windows (bringWindow w)
XMonad.focus w
windows W.shiftMaster
-- | Switches to selected window's workspace and focuses that window.
goToSelected :: GSConfig Window -> X ()
goToSelected = withSelectedWindow $ windows . W.focusWindow
-- | Select an application to spawn from a given list
spawnSelected :: GSConfig String -> [String] -> X ()
spawnSelected conf lst = gridselect conf (zip lst lst) >>= flip whenJust spawn
-- | Select an action and run it in the X monad
runSelectedAction :: GSConfig (X ()) -> [(String, X ())] -> X ()
runSelectedAction conf actions = do
selectedActionM <- gridselect conf actions
case selectedActionM of
Just selectedAction -> selectedAction
Nothing -> return ()
-- | Select a workspace and view it using the given function
-- (normally 'W.view' or 'W.greedyView')
--
-- Another option is to shift the current window to the selected workspace:
--
-- > gridselectWorkspace (\ws -> W.greedyView ws . W.shift ws)
gridselectWorkspace :: GSConfig WorkspaceId ->
(WorkspaceId -> WindowSet -> WindowSet) -> X ()
gridselectWorkspace conf viewFunc = withWindowSet $ \ws -> do
let wss = map W.tag $ W.hidden ws ++ map W.workspace (W.current ws : W.visible ws)
gridselect conf (zip wss wss) >>= flip whenJust (windows . viewFunc) | MasseR/xmonadcontrib | XMonad/Actions/GridSelect.hs | bsd-3-clause | 27,412 | 3 | 23 | 7,682 | 6,581 | 3,578 | 3,003 | 399 | 7 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.EXT.FogCoord
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- All raw functions and tokens from the EXT_fog_coord extension, see
-- <http://www.opengl.org/registry/specs/EXT/fog_coord.txt>.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.EXT.FogCoord (
-- * Functions
glFogCoordf,
glFogCoordd,
glFogCoordfv,
glFogCoorddv,
glFogCoordPointer,
-- * Tokens
gl_FOG_COORDINATE_SOURCE,
gl_FOG_COORDINATE,
gl_FRAGMENT_DEPTH,
gl_CURRENT_FOG_COORDINATE,
gl_FOG_COORDINATE_ARRAY_TYPE,
gl_FOG_COORDINATE_ARRAY_STRIDE,
gl_FOG_COORDINATE_ARRAY_POINTER,
gl_FOG_COORDINATE_ARRAY
) where
import Graphics.Rendering.OpenGL.Raw.ARB.Compatibility
| mfpi/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/EXT/FogCoord.hs | bsd-3-clause | 1,004 | 0 | 4 | 142 | 76 | 58 | 18 | 15 | 0 |
module Main where
import System.Environment (getArgs)
import Data.Either.Combinators (fromRight')
import Text.Blaze.Html.Renderer.Pretty (renderHtml)
import Parse (iParse, doc)
import Semantics (semantic)
import Compile (compile)
main :: IO ()
main = do
[f] <- getArgs
s <- readFile f
case iParse doc f s of
Left err -> print err
Right result -> (putStr . renderHtml . compile . semantic) result
| RoganMurley/dreamail | app/Main.hs | bsd-3-clause | 436 | 0 | 14 | 98 | 153 | 83 | 70 | 14 | 2 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module NeuroSpider.UiManager
( setupMenuToolBars
, UiAction(..)
) where
import BasicPrelude hiding (empty, on)
import Data.Char (isUpper)
import Data.Text (pack, unpack, toLower, breakOn)
import Graphics.UI.Gtk
import Text.XML
import Text.XML.Writer
import qualified Data.Map as Map (insert, empty, lookup)
import qualified Data.Text.Lazy as Lazy
data UiAction =
File
| New | Open | Save | SaveAs | Quit |
Edit
| Cut | Copy | Paste | Delete |
Graph
| CreateNode | CreateEdge | Rename | Show |
Help
| About
deriving (Eq, Show, Read, Enum, Bounded, Ord)
name :: UiAction -> Text
name SaveAs = "Save _As"
name Cut = "Cu_t"
name CreateNode = "_Node"
name CreateEdge = "_Edge"
name a = ("_"<>) . unwords . upperSplit . show $ a
stock :: UiAction -> Text
stock CreateNode = stock_ "Add"
stock CreateEdge = stock_ "Connect"
stock Rename = stock_ "Convert"
stock Show = stock_ "Print"
stock a = stock_ $ show a
stock_ :: Text -> Text
stock_ = ("gtk-"<>) . toLower . intercalate "-" . upperSplit
data ActionActivate = Skip | FireEvent | DoIO (IO ())
activate :: UiAction -> ActionActivate
activate Quit = DoIO mainQuit
activate a | a `elem`
[File,Edit,Graph,Help] = Skip
| otherwise = FireEvent
uiXmlString :: Text
uiXmlString = snd . breakOn "<ui>" . Lazy.toStrict . renderText def $ uiXml
uiXml :: Document
uiXml = ui $ do
menubar $ do
menu File $ do
menuitem New
menuitem Open
menuitem Save
menuitem SaveAs
separator
menuitem Quit
menu Edit $ do
menuitem Cut
menuitem Copy
menuitem Paste
menuitem Delete
menu Graph $ do
menuitem CreateNode
menuitem CreateEdge
menuitem Rename
menuitem Show
menu Help $ do
menuitem About
toolbar $ do
toolitem New
toolitem Open
toolitem Save
separator
toolitem Cut
toolitem Copy
toolitem Paste
separator
toolitem CreateNode
toolitem CreateEdge
toolitem Rename
toolitem Delete
separator
toolitem Show
where
ui = document "ui"
menubar = element "menubar"
toolbar = element "toolbar"
menu = elemA "menu"
menuitem a = elemA "menuitem" a empty
toolitem a = elemA "toolitem" a empty
separator = element "separator" empty
elemA e a = elementA e [("action", show a), ("name", name a)]
setupMenuToolBars :: (WindowClass w, BoxClass b)
=> w -> b -> Map UiAction (IO ())
-> IO (Map UiAction Action)
setupMenuToolBars window box activations = do
stockIds <- stockListIds
actiongroup <- actionGroupNew "actiongroup"
actions <- forM [minBound..maxBound] $ \a -> do
let stock' = if stock a `elem` stockIds then Just (stock a) else Nothing
action <- actionNew (show a) (name a) Nothing stock'
actionGroupAddActionWithAccel actiongroup action (Nothing :: Maybe Text)
let activation = maybe (activate a) DoIO $ Map.lookup a activations
case activation of
Skip -> return id
FireEvent -> return $ Map.insert a action
DoIO io -> on action actionActivated io >> return id
uimanager <- uiManagerNew
uiManagerInsertActionGroup uimanager actiongroup 0
_ <- uiManagerAddUiFromString uimanager uiXmlString
accelgroup <- uiManagerGetAccelGroup uimanager
windowAddAccelGroup window accelgroup
menubar' <- uiManagerGetWidget uimanager "ui/menubar"
toolbar' <- uiManagerGetWidget uimanager "ui/toolbar"
let menubar = maybe (error "menubar setup") castToMenuBar menubar'
let toolbar = maybe (error "toolbar setup") castToToolbar toolbar'
boxPackStart box menubar PackNatural 0
boxPackStart box toolbar PackNatural 1
return $ foldr ($) Map.empty actions
upperSplit :: Text -> [Text]
upperSplit = map pack . takeWhile (/= "") . dropWhile (== "")
. map fst . iterate (upperSplit_ . snd) . ("",) . unpack
upperSplit_ :: String -> (String, String)
upperSplit_ s = if length startUpper > 1
then (startUpper, rest)
else (startUpper ++ s1, s2)
where (startUpper, rest) = span isUpper s
(s1, s2) = break isUpper rest
| pavelkogan/NeuroSpider | src/NeuroSpider/UiManager.hs | bsd-3-clause | 4,273 | 0 | 18 | 1,060 | 1,423 | 703 | 720 | 127 | 4 |
{-# LANGUAGE GeneralizedNewtypeDeriving, DoRec, ExistentialQuantification, FlexibleContexts #-}
module TermSet2 where
import Control.Arrow((***))
import Control.Monad.State
import Control.Monad.Reader
import qualified Data.IntMap as IntMap
import Data.IntMap(IntMap)
import Test.QuickCheck hiding (label)
import Test.QuickCheck.Gen
import Test.QuickCheck.GenT hiding (liftGen)
import qualified Test.QuickCheck.GenT as GenT
import Data.Typeable
import TestTree
newtype Label v a = Label { unLabel :: State (Int, IntMap v) a } deriving (Functor, Monad, MonadFix)
label :: v -> Label v (Labelled v)
label x = Label $ do
(i, m) <- get
put (i+1, IntMap.insert i x m)
return (Labelled i x)
data Labelled a = Labelled Int a
runLabel :: Label v a -> (a, IntMap v)
runLabel = (id *** snd) . flip runState (0, IntMap.empty) . unLabel
-- test :: Assoc Int ()
-- test = do
-- rec x <- assoc y
-- y <- assoc x
-- return ()
data UntypedTestResults = forall a. Typeable a => UntypedTestResults (TestResults a)
newtype Univ a = Univ { unUniv :: ReaderT Int (GenT (Label UntypedTestResults)) a }
deriving (Functor, Monad, MonadFix, MonadReader Int)
testCases :: Gen a -> Gen [a]
testCases g = forM (cycle [1..50]) $ \n -> resize n g
generate :: Typeable a => TestTree a -> Univ (Labelled a)
generate t = do
n <- ask
liftLabel (label (UntypedTestResults (cutOff n t)))
liftGen :: Gen a -> Univ a
liftGen = Univ . lift . GenT.liftGen
liftLabel :: Label UntypedTestResults a -> Univ a
liftLabel = Univ . lift . lift
base :: (Ord a, Eval a, Typeable a, Arbitrary (TestCase a)) => [a] -> Univ (Labelled a)
base ts = do
tcs <- liftGen (testCases arbitrary)
generate (test tcs ts)
apply :: Labelled (a -> b) -> Labelled a -> Univ (Labelled b)
apply fs xs = do
tcs <- liftGen (testCases arbitrary)
undefined
-- generate (test tcs (
| jystic/QuickSpec | TermSet2.hs | bsd-3-clause | 1,852 | 0 | 13 | 349 | 715 | 381 | 334 | 43 | 1 |
module Mud.Error
( MudError(..)
, humanReadableMudError
) where
import GHC.Conc.Signal
data MudError
= MudErrorNoConfigFound FilePath
| MudErrorNotInMudDirectory
| MudErrorUnreadableConfig String
| MudErrorUnreadableHistory String
| MudErrorNoRollbackPlanFound
| MudErrorScriptFailure (Either Int Signal)
| MudErrorString String
deriving (Show, Eq)
humanReadableMudError :: MudError -> String
humanReadableMudError mudError = case mudError of
MudErrorNoConfigFound path -> "no configuration file found for base: " ++ path
MudErrorNotInMudDirectory -> "configuration must be in the mud directory"
MudErrorUnreadableConfig str -> "can't read configuration file: " ++ str
MudErrorUnreadableHistory str -> "can't read history file: " ++ str
MudErrorNoRollbackPlanFound -> "can't find a rollback plan"
MudErrorScriptFailure (Left code) ->
"script failed with exit code " ++ show code
MudErrorScriptFailure (Right sig) ->
"script interrupted with signal " ++ show sig
MudErrorString str -> str
| thoferon/mud | src/Mud/Error.hs | bsd-3-clause | 1,037 | 0 | 10 | 173 | 203 | 106 | 97 | 25 | 8 |
module CorrectEmptyWhere where
class X a where
y :: a -> a
y 2 = 2
class Y b where
x :: b -> Int
x _ = 2
main2 = 2 where
main3 = 1
class Z z
g :: Int -> Int
g _ = 0
| roberth/uu-helium | test/typeClassesParse/CorrectEmptyWhere.hs | gpl-3.0 | 201 | 0 | 7 | 84 | 91 | 48 | 43 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables, NoMonomorphismRestriction, RecordWildCards #-}
module Main where
import Control.Applicative
import Control.Monad
import Control.Monad.Error
import Control.Monad.Reader
import Control.Monad.State
import Data.Conduit
import qualified Data.Conduit.List as CL
import qualified Data.Traversable as T
import qualified Data.HashMap.Lazy as HM
import Data.Maybe
import Data.Monoid
import System.Directory
import System.Environment
import System.FilePath ((</>))
import System.IO
import System.Log.Logger
--
import HEP.Automation.EventChain.Driver
import HEP.Automation.EventChain.File
import HEP.Automation.EventChain.LHEConn
import HEP.Automation.EventChain.Type.MultiProcess
import HEP.Automation.EventChain.Type.Skeleton
import HEP.Automation.EventChain.Type.Spec
import HEP.Automation.EventChain.Type.Process
import HEP.Automation.EventChain.SpecDSL
import HEP.Automation.EventChain.Simulator
import HEP.Automation.EventChain.Process
import HEP.Automation.EventChain.Process.Generator
import HEP.Automation.EventGeneration.Config
import HEP.Automation.EventGeneration.Type
import HEP.Automation.EventGeneration.Work
import HEP.Automation.MadGraph.Model
import HEP.Automation.MadGraph.Model.SimplifiedSUSYlep
import HEP.Automation.MadGraph.Run
import HEP.Automation.MadGraph.SetupType
import HEP.Automation.MadGraph.Type
import HEP.Parser.LHE.Type
import HEP.Parser.LHE.Sanitizer.Type
import HEP.Storage.WebDAV
--
import qualified Paths_madgraph_auto as PMadGraph
import qualified Paths_madgraph_auto_model as PModel
jets = [1,2,3,4,-1,-2,-3,-4,21]
leptons = [11,13,-11,-13]
lepplusneut = [11,12,13,14,-11,-12,-13,-14]
tauplusneut = [15,16,-15,-16]
lightobjs = jets++lepplusneut++tauplusneut
neut = 1000022
charginos = [1000024, -1000024]
p_gluino :: DDecay
p_gluino = d ( [1000021], [ p_chargino, t jets, t jets ] )
p_chargino :: DDecay
p_chargino = d ( charginos, [neut, t lightobjs, t lightobjs] )
p_lep1step_2sg :: DCross
p_lep1step_2sg = x (t proton, t proton, [p_gluino, p_gluino])
map_lep1step_2sg :: ProcSpecMap
map_lep1step_2sg =
HM.fromList [ (Nothing, MGProc []
["p p > go go QED=0"])
, (Just (3, 1000021,[]), MGProc ["define x1 = x1+ x1-"] ["go > x1 j j"])
--
, (Just (4, 1000021,[]), MGProc ["define x1 = x1+ x1-"] ["go > x1 j j"])
--
, (Just (1, 1000024,[3]), MGProc [] [ "x1+ > w+ > n1 ve e+ QED=2"
, "x1+ > w+ > n1 vm mu+ QED=2"
, "x1+ > w+ > n1 vt ta+ QED=2"
, "x1+ > w+ > n1 j j QED=2" ])
, (Just (1,-1000024,[3]), MGProc [] [ "x1- > w- > n1 ve~ e- QED=2"
, "x1- > w- > n1 vm~ mu- QED=2"
, "x1- > w- > n1 vt~ ta- QED=2"
, "x1- > w- > n1 j j QED=2" ])
--
, (Just (1, 1000024,[4]), MGProc [] [ "x1+ > w+ > n1 ve e+ QED=2"
, "x1+ > w+ > n1 vm mu+ QED=2"
, "x1+ > w+ > n1 vt ta+ QED=2"
, "x1+ > w+ > n1 j j QED=2" ])
, (Just (1,-1000024,[4]), MGProc [] [ "x1- > w- > n1 ve~ e- QED=2"
, "x1- > w- > n1 vm~ mu- QED=2"
, "x1- > w- > n1 vt~ ta- QED=2"
, "x1- > w- > n1 j j QED=2" ])
]
pdir = ProcDir "Work20130724" "montecarlo/admproject/SimplifiedSUSYlep/8TeV" "scan"
sproc = SingleProc "1step_2sg" p_lep1step_2sg map_lep1step_2sg mgrunsetup
mprocs = mkMultiProc pdir [sproc]
-- |
mgrunsetup :: NumOfEv -> SetNum -> RunSetup
mgrunsetup (NumOfEv nev) (SetNum sn) =
RS { numevent = nev
, machine = LHC8 ATLAS
, rgrun = Auto
, rgscale = 200.0
, match = NoMatch
, cut = NoCut
, pythia = RunPYTHIA
, lhesanitizer = [Replace [(9000201,1000022),(-9000201,1000022)]]
, pgs = RunPGS (AntiKTJet 0.4,NoTau)
, uploadhep = NoUploadHEP
, setnum = sn
}
minfty :: Double
minfty = 50000.0
worksets :: [ (String, ModelParam SimplifiedSUSYlep, Int) ]
worksets = [ ("1step_2sg",SimplifiedSUSYlepParam mn mg minfty mc minfty minfty,10000)
| (mg,mn) <- mgmn, let mc = (mg+mn)*0.5 ]
where mgmn = [ (mg,mn) | mg <- [ 200,250..1500 ], mn <- [ 50,100..mg-50] ]
main :: IO ()
main = do
args <- getArgs
let fp = args !! 0
n1 = read (args !! 1) :: Int
n2 = read (args !! 2) :: Int
updateGlobalLogger "MadGraphAuto" (setLevel DEBUG)
-- print $ length worksets
-- mapM_ print $ worksets
mapM_ (scanwork fp) (drop (n1-1) . take n2 $ worksets )
scanwork :: FilePath -> (String,ModelParam SimplifiedSUSYlep,Int) -> IO ()
scanwork fp (cmd,param,n) = do
homedir <- getHomeDirectory
getConfig fp >>=
maybe (return ()) (\ec -> do
let ssetup = evgen_scriptsetup ec
whost = evgen_webdavroot ec
pkey = evgen_privatekeyfile ec
pswd = evgen_passwordstore ec
Just cr <- getCredential pkey pswd
let wdavcfg = WebDAVConfig { webdav_credential = cr
, webdav_baseurl = whost }
-- param = modelparam mneut mgl msq
-- let mjob = Just ("1step_2sg", NumOfEv n, SetNum 1)
-- print mjob
-- maybe (return ()) (genMultiProcess SimplifiedSUSYlep ssetup mprocs param wdavcfg) mjob
let nev = NumOfEv n
sn = SetNum 1
genPhase1 SimplifiedSUSYlep ssetup pdir sproc param (nev,sn)
genPhase2 SimplifiedSUSYlep ssetup pdir sproc param (nev,sn)
genPhase3 SimplifiedSUSYlep ssetup pdir sproc param (nev,sn) wdavcfg
return ()
)
| wavewave/lhc-analysis-collection | exe/2013-07-24-SimplifiedSUSYlepgluglu.hs | gpl-3.0 | 6,215 | 0 | 17 | 2,022 | 1,534 | 904 | 630 | 125 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.S3.GetBucketNotificationConfiguration
-- Copyright : (c) 2013-2014 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)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Returns the notification configuration of a bucket.
--
-- <http://docs.aws.amazon.com/AmazonS3/latest/API/GetBucketNotificationConfiguration.html>
module Network.AWS.S3.GetBucketNotificationConfiguration
(
-- * Request
GetBucketNotificationConfiguration
-- ** Request constructor
, getBucketNotificationConfiguration
-- ** Request lenses
, gbnc1Bucket
-- * Response
, GetBucketNotificationConfigurationResponse
-- ** Response constructor
, getBucketNotificationConfigurationResponse
-- ** Response lenses
, gbncrLambdaFunctionConfigurations
, gbncrQueueConfigurations
, gbncrTopicConfigurations
) where
import Network.AWS.Prelude
import Network.AWS.Request.S3
import Network.AWS.S3.Types
import qualified GHC.Exts
newtype GetBucketNotificationConfiguration = GetBucketNotificationConfiguration
{ _gbnc1Bucket :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'GetBucketNotificationConfiguration' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'gbnc1Bucket' @::@ 'Text'
--
getBucketNotificationConfiguration :: Text -- ^ 'gbnc1Bucket'
-> GetBucketNotificationConfiguration
getBucketNotificationConfiguration p1 = GetBucketNotificationConfiguration
{ _gbnc1Bucket = p1
}
-- | Name of the buket to get the notification configuration for.
gbnc1Bucket :: Lens' GetBucketNotificationConfiguration Text
gbnc1Bucket = lens _gbnc1Bucket (\s a -> s { _gbnc1Bucket = a })
data GetBucketNotificationConfigurationResponse = GetBucketNotificationConfigurationResponse
{ _gbncrLambdaFunctionConfigurations :: List "CloudFunctionConfiguration" LambdaFunctionConfiguration
, _gbncrQueueConfigurations :: List "QueueConfiguration" QueueConfiguration
, _gbncrTopicConfigurations :: List "TopicConfiguration" TopicConfiguration
} deriving (Eq, Read, Show)
-- | 'GetBucketNotificationConfigurationResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'gbncrLambdaFunctionConfigurations' @::@ ['LambdaFunctionConfiguration']
--
-- * 'gbncrQueueConfigurations' @::@ ['QueueConfiguration']
--
-- * 'gbncrTopicConfigurations' @::@ ['TopicConfiguration']
--
getBucketNotificationConfigurationResponse :: GetBucketNotificationConfigurationResponse
getBucketNotificationConfigurationResponse = GetBucketNotificationConfigurationResponse
{ _gbncrTopicConfigurations = mempty
, _gbncrQueueConfigurations = mempty
, _gbncrLambdaFunctionConfigurations = mempty
}
gbncrLambdaFunctionConfigurations :: Lens' GetBucketNotificationConfigurationResponse [LambdaFunctionConfiguration]
gbncrLambdaFunctionConfigurations =
lens _gbncrLambdaFunctionConfigurations
(\s a -> s { _gbncrLambdaFunctionConfigurations = a })
. _List
gbncrQueueConfigurations :: Lens' GetBucketNotificationConfigurationResponse [QueueConfiguration]
gbncrQueueConfigurations =
lens _gbncrQueueConfigurations
(\s a -> s { _gbncrQueueConfigurations = a })
. _List
gbncrTopicConfigurations :: Lens' GetBucketNotificationConfigurationResponse [TopicConfiguration]
gbncrTopicConfigurations =
lens _gbncrTopicConfigurations
(\s a -> s { _gbncrTopicConfigurations = a })
. _List
instance ToPath GetBucketNotificationConfiguration where
toPath GetBucketNotificationConfiguration{..} = mconcat
[ "/"
, toText _gbnc1Bucket
]
instance ToQuery GetBucketNotificationConfiguration where
toQuery = const "notification"
instance ToHeaders GetBucketNotificationConfiguration
instance ToXMLRoot GetBucketNotificationConfiguration where
toXMLRoot = const (namespaced ns "GetBucketNotificationConfiguration" [])
instance ToXML GetBucketNotificationConfiguration
instance AWSRequest GetBucketNotificationConfiguration where
type Sv GetBucketNotificationConfiguration = S3
type Rs GetBucketNotificationConfiguration = GetBucketNotificationConfigurationResponse
request = get
response = xmlResponse
instance FromXML GetBucketNotificationConfigurationResponse where
parseXML x = GetBucketNotificationConfigurationResponse
<$> parseXML x
<*> parseXML x
<*> parseXML x
| kim/amazonka | amazonka-s3/gen/Network/AWS/S3/GetBucketNotificationConfiguration.hs | mpl-2.0 | 5,377 | 0 | 10 | 1,002 | 598 | 354 | 244 | 78 | 1 |
{-# LANGUAGE OverloadedStrings, GADTs, FlexibleInstances #-}
module D3JS.Reify where
import Data.Text (Text)
import qualified Data.Text as T
import D3JS.Type
instance Reifiable Var where
reify t = t
instance Reifiable (Var' r) where
reify (Var' name) = name
instance Reifiable (Chain a b) where
reify (Val name) = name
reify (Val' v) = reify v
reify (Val'' (Var' n)) = n
reify (Concat Nil g) = reify g
reify (Concat f g) = T.concat [reify g,".",reify f] -- method chain flows from left to right, so flips f and g.
-- reify (Func f) = reify f
reify Nil = ""
-- reify (ChainField name) = name
reify (Refine name) = name
reify (Apply args chain) = T.concat [reify chain,"(",T.intercalate "," $ map reify args,")"]
-- instance Reifiable D3Root where
-- reify D3Root = "d3"
instance Reifiable Data1D where
reify (Data1D ps) = surround $ T.intercalate "," $ map show' ps
instance Reifiable Data2D where
reify (Data2D ps) = surround $ T.intercalate "," $ map (\(x,y) -> T.concat ["[",show' x,",",show' y,"]"]) ps
instance Reifiable (JSFunc params r) where
reify (JSFunc name params) = T.concat [name,"(",T.intercalate "," $ map reify params,")"]
instance Reifiable JSParam where
reify (ParamVar name) = name
reify (PText t) = T.concat ["\"",t,"\""]
reify (PDouble d) = show' d
reify (PInt d) = show' d
reify (PFunc (FuncTxt t)) = t
reify (PFunc (FuncExp f)) = T.concat["function(d,i){return ",reify f,";}"]
reify (PFunc' f) = reify f
reify (PArray vs) = T.concat ["[",T.intercalate "," $ map reify vs,"]"]
reify (PChainValue v) = reify v
instance Reifiable (NumFunc r) where
reify (NInt i) = show' i
reify (NDouble d) = show' d
reify (NVar v) = v
reify (Add a b) = T.concat [reify a," + ",reify b]
reify (Mult a b) = T.concat [reify a," * ",reify b]
reify (Subt a b) = T.concat [reify a," - ",reify b]
reify (Mod a b) = T.concat [reify a," % ",reify b]
reify DataParam = "d"
reify DataIndex = "i"
reify DataIndexD = "i"
reify (ChainVal chain) = reify chain
reify (Index i ns) = T.concat [reify ns,"[",reify i,"]"]
reify (Field name obj) = T.concat [reify obj,".",name]
reify (Ternary cond a b) = T.concat ["(", reify cond, ") ? (", reify a, ") : (", reify b, ")"]
reify (ApplyFunc var params) = T.concat [unVar' var,"(",T.intercalate "," $ map reify params,")"]
reify (ApplyFunc' name params) = T.concat [name,"(",T.intercalate "," $ map reify params,")"]
reify (MkObject pairs) =
let f (key,val) = T.concat [key,": ",reify val]
in T.concat ["{",T.intercalate "," $ map f pairs,"}"]
-- Stub: incomplete!!
show' :: (Show a) => a -> Text
show' = T.pack . show
surround s = T.concat ["[",s,"]"]
| nebuta/d3js-haskell | D3JS/Reify.hs | bsd-3-clause | 2,648 | 2 | 12 | 504 | 1,275 | 650 | 625 | 57 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving, CPP, TypeFamilies, FlexibleInstances, FlexibleContexts, DeriveDataTypeable, TypeOperators #-}
import Development.Shake
import qualified Development.Shake.Core as Core
import Control.DeepSeq
import Control.Monad.IO.Class
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
import Data.Typeable
#include "MyOracle.inc"
-- Make the question longer (tests that we check that question deserialization is tested)
instance Binary (Question MyOracle) where
get = do { 0 <- getWord8; return (MOQ ()) }
put (MOQ ()) = putWord8 0
instance Binary (Answer MyOracle) where
get = fmap (MOA . fromIntegral) getWord16le
put (MOA i) = putWord16le (fromIntegral i)
main :: IO ()
main = (Core.shake :: Shake (Question MyOracle :+: CanonicalFilePath) () -> IO ()) $ do
installOracle (MO 1)
"examplefile" *> \x -> do
MOA 1 <- query $ MOQ ()
liftIO $ writeFile "examplefile" "OK3"
want ["examplefile"]
| batterseapower/openshake | tests/deserialization-changes/Shakefile-3.hs | bsd-3-clause | 991 | 0 | 15 | 185 | 285 | 148 | 137 | 22 | 1 |
--------------------------------------------------------------------
-- |
-- Module : Text.RSS1.Utils
-- Copyright : (c) Galois, Inc. 2008
-- License : BSD3
--
-- Maintainer: Sigbjorn Finne <[email protected]>
-- Stability : provisional
-- Portability:
--
--------------------------------------------------------------------
module Text.RSS1.Utils where
import Text.XML.Light as XML
import Text.XML.Light.Proc as XML
import Text.DublinCore.Types
import Data.Maybe (listToMaybe, mapMaybe)
pQNodes :: QName -> XML.Element -> [XML.Element]
pQNodes = XML.findChildren
pNode :: String -> XML.Element -> Maybe XML.Element
pNode x e = listToMaybe (pQNodes (qualName (rss10NS,Nothing) x) e)
pQNode :: QName -> XML.Element -> Maybe XML.Element
pQNode x e = listToMaybe (pQNodes x e)
pLeaf :: String -> XML.Element -> Maybe String
pLeaf x e = strContent `fmap` pQNode (qualName (rss10NS,Nothing) x) e
pQLeaf :: (Maybe String,Maybe String) -> String -> XML.Element -> Maybe String
pQLeaf ns x e = strContent `fmap` pQNode (qualName ns x) e
pAttr :: (Maybe String, Maybe String) -> String -> XML.Element -> Maybe String
pAttr ns x e = lookup (qualName ns x) [ (k,v) | Attr k v <- elAttribs e ]
pMany :: (Maybe String,Maybe String) -> String -> (XML.Element -> Maybe a) -> XML.Element -> [a]
pMany ns p f e = mapMaybe f (pQNodes (qualName ns p) e)
children :: XML.Element -> [XML.Element]
children e = onlyElems (elContent e)
qualName :: (Maybe String, Maybe String) -> String -> QName
qualName (ns,pre) x = QName{qName=x,qURI=ns,qPrefix=pre}
rssPrefix, rss10NS :: Maybe String
rss10NS = Just "http://purl.org/rss/1.0/"
rssPrefix = Nothing
rdfPrefix, rdfNS :: Maybe String
rdfNS = Just "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
rdfPrefix = Just "rdf"
synPrefix, synNS :: Maybe String
synNS = Just "http://purl.org/rss/1.0/modules/syndication/"
synPrefix = Just "sy"
taxPrefix, taxNS :: Maybe String
taxNS = Just "http://purl.org/rss/1.0/modules/taxonomy/"
taxPrefix = Just "taxo"
conPrefix, conNS :: Maybe String
conNS = Just "http://purl.org/rss/1.0/modules/content/"
conPrefix = Just "content"
dcPrefix, dcNS :: Maybe String
dcNS = Just "http://purl.org/dc/elements/1.1/"
dcPrefix = Just "dc"
rdfName :: String -> QName
rdfName x = QName{qName=x,qURI=rdfNS,qPrefix=rdfPrefix}
rssName :: String -> QName
rssName x = QName{qName=x,qURI=rss10NS,qPrefix=rssPrefix}
synName :: String -> QName
synName x = QName{qName=x,qURI=synNS,qPrefix=synPrefix}
known_rss_elts :: [QName]
known_rss_elts = map rssName [ "channel", "item", "image", "textinput" ]
known_syn_elts :: [QName]
known_syn_elts = map synName [ "updateBase", "updateFrequency", "updatePeriod" ]
known_dc_elts :: [QName]
known_dc_elts = map (qualName (dcNS,dcPrefix)) dc_element_names
known_tax_elts :: [QName]
known_tax_elts = map (qualName (taxNS,taxPrefix)) [ "topic", "topics" ]
known_con_elts :: [QName]
known_con_elts = map (qualName (conNS,conPrefix)) [ "items", "item", "format", "encoding" ]
removeKnownElts :: XML.Element -> [XML.Element]
removeKnownElts e =
filter (\ e1 -> not (elName e1 `elem` known_elts)) (children e)
where
known_elts =
concat [ known_rss_elts
, known_syn_elts
, known_dc_elts
, known_con_elts
, known_tax_elts
]
removeKnownAttrs :: XML.Element -> [XML.Attr]
removeKnownAttrs e =
filter (\ a -> not (attrKey a `elem` known_attrs)) (elAttribs e)
where
known_attrs =
map rdfName [ "about" ]
| GaloisInc/feed | Text/RSS1/Utils.hs | bsd-3-clause | 3,511 | 2 | 11 | 594 | 1,145 | 634 | 511 | 71 | 1 |
{- GTK 2.0 Tutorial: Chapter 2: Getting Started
To run with GHCi: ghci GtkChap2a.hs
To compile with GHC: ghc --make GtkChap2a.hs -o chap
-}
import Graphics.UI.Gtk
main :: IO ()
main = do
initGUI
window <- windowNew
windowSetTitle window "Step One"
widgetShowAll window
mainGUI
{- Notes:
1) Watch the upper and lower case occurrences
2) Ctl-z to abort GHCi, not Ctl-c
-}
| k0001/gtk2hs | docs/tutorial/Tutorial_Port/Example_Code/GtkChap2a.hs | gpl-3.0 | 400 | 0 | 7 | 92 | 51 | 24 | 27 | 8 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sq-AL">
<title>Browser View | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | 0xkasun/security-tools | src/org/zaproxy/zap/extension/browserView/resources/help_sq_AL/helpset_sq_AL.hs | apache-2.0 | 974 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
-- | This module generates Netlist 'Decl's for a circuit graph.
module Language.KansasLava.Netlist.Decl where
import Language.KansasLava.Types
import Language.Netlist.AST
import Data.Reify.Graph (Unique)
import Language.KansasLava.Netlist.Utils
-- Entities that need a _next special *extra* signal.
--toAddNextSignal :: [Id]
--toAddNextSignal = [Prim "register"]
-- We have a few exceptions, where we generate some extra signals,
-- but in general, we generate a single signal decl for each
-- entity.
-- | Generate declarations.
genDecl :: (Unique, Entity Unique) -> [Decl]
-- Special cases
{-
genDecl (i,Entity nm outputs _)
| nm `elem` toAddNextSignal
= concat
[ [ NetDecl (next $ sigName n i) (sizedRange nTy) Nothing
, MemDecl (sigName n i) Nothing (sizedRange nTy)
]
| (n,nTy) <- outputs ]
genDecl (i,e@(Entity nm outputs@[_] inputs)) | nm == Prim "BRAM"
= concat
[ [ MemDecl (sigName n i) (memRange aTy) (sizedRange nTy)
, NetDecl (sigName n i) (sizedRange nTy) Nothing
]
| (n,nTy) <- outputs ]
where
aTy = lookupInputType "wAddr" e
genDecl (i,Entity nm outputs _)
| nm `elem` isVirtualEntity
= []
-}
-- General case
genDecl (i,e@(Entity _ outputs _))
= [ case toStdLogicTy nTy of
MatrixTy x (V y)
-> let x' = head [ po2 | po2 <- iterate (*2) 1
, po2 >= x
]
in MemDecl
(sigName n i)
(sizedRange (V x'))
(sizedRange (V y))
(case e of
Entity (Prim "rom")
[("o0",_)]
[("defs",RomTy _,Lits lits)]
-- This is reversed because we defined from (n-1) downto 0
-> Just $ reverse $ map (toTypedExpr (V y))
$ take x'
(lits ++ repeat (RepValue $ replicate y $ Just False))
_ -> Nothing
)
_ -> NetDecl
(sigName n i)
(sizedRange nTy)
(case e of
Entity (Prim "register")
[("o0",ty)]
[ _, ("def",GenericTy,gn), _, _, _] ->
Just (toTypedExpr ty gn)
_ -> Nothing)
| (n,nTy) <- outputs
, toStdLogicTy nTy /= V 0
]
| andygill/kansas-lava | Language/KansasLava/Netlist/Decl.hs | bsd-3-clause | 2,443 | 26 | 24 | 945 | 483 | 262 | 221 | 34 | 4 |
{-# LANGUAGE CPP, GeneralizedNewtypeDeriving #-}
--------------------------------------------------------------------------------
-- | The LLVM Type System.
--
module Llvm.Types where
#include "HsVersions.h"
import GhcPrelude
import Data.Char
import Data.Int
import Numeric
import DynFlags
import FastString
import Outputable
import Unique
-- from NCG
import PprBase
import GHC.Float
-- -----------------------------------------------------------------------------
-- * LLVM Basic Types and Variables
--
-- | A global mutable variable. Maybe defined or external
data LMGlobal = LMGlobal {
getGlobalVar :: LlvmVar, -- ^ Returns the variable of the 'LMGlobal'
getGlobalValue :: Maybe LlvmStatic -- ^ Return the value of the 'LMGlobal'
}
-- | A String in LLVM
type LMString = FastString
-- | A type alias
type LlvmAlias = (LMString, LlvmType)
-- | Llvm Types
data LlvmType
= LMInt Int -- ^ An integer with a given width in bits.
| LMFloat -- ^ 32 bit floating point
| LMDouble -- ^ 64 bit floating point
| LMFloat80 -- ^ 80 bit (x86 only) floating point
| LMFloat128 -- ^ 128 bit floating point
| LMPointer LlvmType -- ^ A pointer to a 'LlvmType'
| LMArray Int LlvmType -- ^ An array of 'LlvmType'
| LMVector Int LlvmType -- ^ A vector of 'LlvmType'
| LMLabel -- ^ A 'LlvmVar' can represent a label (address)
| LMVoid -- ^ Void type
| LMStruct [LlvmType] -- ^ Packed structure type
| LMStructU [LlvmType] -- ^ Unpacked structure type
| LMAlias LlvmAlias -- ^ A type alias
| LMMetadata -- ^ LLVM Metadata
-- | Function type, used to create pointers to functions
| LMFunction LlvmFunctionDecl
deriving (Eq)
instance Outputable LlvmType where
ppr (LMInt size ) = char 'i' <> ppr size
ppr (LMFloat ) = text "float"
ppr (LMDouble ) = text "double"
ppr (LMFloat80 ) = text "x86_fp80"
ppr (LMFloat128 ) = text "fp128"
ppr (LMPointer x ) = ppr x <> char '*'
ppr (LMArray nr tp ) = char '[' <> ppr nr <> text " x " <> ppr tp <> char ']'
ppr (LMVector nr tp ) = char '<' <> ppr nr <> text " x " <> ppr tp <> char '>'
ppr (LMLabel ) = text "label"
ppr (LMVoid ) = text "void"
ppr (LMStruct tys ) = text "<{" <> ppCommaJoin tys <> text "}>"
ppr (LMStructU tys ) = text "{" <> ppCommaJoin tys <> text "}"
ppr (LMMetadata ) = text "metadata"
ppr (LMFunction (LlvmFunctionDecl _ _ _ r varg p _))
= ppr r <+> lparen <> ppParams varg p <> rparen
ppr (LMAlias (s,_)) = char '%' <> ftext s
ppParams :: LlvmParameterListType -> [LlvmParameter] -> SDoc
ppParams varg p
= let varg' = case varg of
VarArgs | null args -> sLit "..."
| otherwise -> sLit ", ..."
_otherwise -> sLit ""
-- by default we don't print param attributes
args = map fst p
in ppCommaJoin args <> ptext varg'
-- | An LLVM section definition. If Nothing then let LLVM decide the section
type LMSection = Maybe LMString
type LMAlign = Maybe Int
data LMConst = Global -- ^ Mutable global variable
| Constant -- ^ Constant global variable
| Alias -- ^ Alias of another variable
deriving (Eq)
-- | LLVM Variables
data LlvmVar
-- | Variables with a global scope.
= LMGlobalVar LMString LlvmType LlvmLinkageType LMSection LMAlign LMConst
-- | Variables local to a function or parameters.
| LMLocalVar Unique LlvmType
-- | Named local variables. Sometimes we need to be able to explicitly name
-- variables (e.g for function arguments).
| LMNLocalVar LMString LlvmType
-- | A constant variable
| LMLitVar LlvmLit
deriving (Eq)
instance Outputable LlvmVar where
ppr (LMLitVar x) = ppr x
ppr (x ) = ppr (getVarType x) <+> ppName x
-- | Llvm Literal Data.
--
-- These can be used inline in expressions.
data LlvmLit
-- | Refers to an integer constant (i64 42).
= LMIntLit Integer LlvmType
-- | Floating point literal
| LMFloatLit Double LlvmType
-- | Literal NULL, only applicable to pointer types
| LMNullLit LlvmType
-- | Vector literal
| LMVectorLit [LlvmLit]
-- | Undefined value, random bit pattern. Useful for optimisations.
| LMUndefLit LlvmType
deriving (Eq)
instance Outputable LlvmLit where
ppr l@(LMVectorLit {}) = ppLit l
ppr l = ppr (getLitType l) <+> ppLit l
-- | Llvm Static Data.
--
-- These represent the possible global level variables and constants.
data LlvmStatic
= LMComment LMString -- ^ A comment in a static section
| LMStaticLit LlvmLit -- ^ A static variant of a literal value
| LMUninitType LlvmType -- ^ For uninitialised data
| LMStaticStr LMString LlvmType -- ^ Defines a static 'LMString'
| LMStaticArray [LlvmStatic] LlvmType -- ^ A static array
| LMStaticStruc [LlvmStatic] LlvmType -- ^ A static structure type
| LMStaticPointer LlvmVar -- ^ A pointer to other data
-- static expressions, could split out but leave
-- for moment for ease of use. Not many of them.
| LMBitc LlvmStatic LlvmType -- ^ Pointer to Pointer conversion
| LMPtoI LlvmStatic LlvmType -- ^ Pointer to Integer conversion
| LMAdd LlvmStatic LlvmStatic -- ^ Constant addition operation
| LMSub LlvmStatic LlvmStatic -- ^ Constant subtraction operation
instance Outputable LlvmStatic where
ppr (LMComment s) = text "; " <> ftext s
ppr (LMStaticLit l ) = ppr l
ppr (LMUninitType t) = ppr t <> text " undef"
ppr (LMStaticStr s t) = ppr t <> text " c\"" <> ftext s <> text "\\00\""
ppr (LMStaticArray d t) = ppr t <> text " [" <> ppCommaJoin d <> char ']'
ppr (LMStaticStruc d t) = ppr t <> text "<{" <> ppCommaJoin d <> text "}>"
ppr (LMStaticPointer v) = ppr v
ppr (LMBitc v t)
= ppr t <> text " bitcast (" <> ppr v <> text " to " <> ppr t <> char ')'
ppr (LMPtoI v t)
= ppr t <> text " ptrtoint (" <> ppr v <> text " to " <> ppr t <> char ')'
ppr (LMAdd s1 s2)
= pprStaticArith s1 s2 (sLit "add") (sLit "fadd") "LMAdd"
ppr (LMSub s1 s2)
= pprStaticArith s1 s2 (sLit "sub") (sLit "fsub") "LMSub"
pprSpecialStatic :: LlvmStatic -> SDoc
pprSpecialStatic (LMBitc v t) =
ppr (pLower t) <> text ", bitcast (" <> ppr v <> text " to " <> ppr t
<> char ')'
pprSpecialStatic stat = ppr stat
pprStaticArith :: LlvmStatic -> LlvmStatic -> LitString -> LitString -> String -> SDoc
pprStaticArith s1 s2 int_op float_op op_name =
let ty1 = getStatType s1
op = if isFloat ty1 then float_op else int_op
in if ty1 == getStatType s2
then ppr ty1 <+> ptext op <+> lparen <> ppr s1 <> comma <> ppr s2 <> rparen
else sdocWithDynFlags $ \dflags ->
error $ op_name ++ " with different types! s1: "
++ showSDoc dflags (ppr s1) ++ ", s2: " ++ showSDoc dflags (ppr s2)
-- -----------------------------------------------------------------------------
-- ** Operations on LLVM Basic Types and Variables
--
-- | Return the variable name or value of the 'LlvmVar'
-- in Llvm IR textual representation (e.g. @\@x@, @%y@ or @42@).
ppName :: LlvmVar -> SDoc
ppName v@(LMGlobalVar {}) = char '@' <> ppPlainName v
ppName v@(LMLocalVar {}) = char '%' <> ppPlainName v
ppName v@(LMNLocalVar {}) = char '%' <> ppPlainName v
ppName v@(LMLitVar {}) = ppPlainName v
-- | Return the variable name or value of the 'LlvmVar'
-- in a plain textual representation (e.g. @x@, @y@ or @42@).
ppPlainName :: LlvmVar -> SDoc
ppPlainName (LMGlobalVar x _ _ _ _ _) = ftext x
ppPlainName (LMLocalVar x LMLabel ) = text (show x)
ppPlainName (LMLocalVar x _ ) = text ('l' : show x)
ppPlainName (LMNLocalVar x _ ) = ftext x
ppPlainName (LMLitVar x ) = ppLit x
-- | Print a literal value. No type.
ppLit :: LlvmLit -> SDoc
ppLit (LMIntLit i (LMInt 32)) = ppr (fromInteger i :: Int32)
ppLit (LMIntLit i (LMInt 64)) = ppr (fromInteger i :: Int64)
ppLit (LMIntLit i _ ) = ppr ((fromInteger i)::Int)
ppLit (LMFloatLit r LMFloat ) = ppFloat $ narrowFp r
ppLit (LMFloatLit r LMDouble) = ppDouble r
ppLit f@(LMFloatLit _ _) = sdocWithDynFlags (\dflags ->
error $ "Can't print this float literal!" ++ showSDoc dflags (ppr f))
ppLit (LMVectorLit ls ) = char '<' <+> ppCommaJoin ls <+> char '>'
ppLit (LMNullLit _ ) = text "null"
-- Trac 11487 was an issue where we passed undef for some arguments
-- that were actually live. By chance the registers holding those
-- arguments usually happened to have the right values anyways, but
-- that was not guaranteed. To find such bugs reliably, we set the
-- flag below when validating, which replaces undef literals (at
-- common types) with values that are likely to cause a crash or test
-- failure.
ppLit (LMUndefLit t ) = sdocWithDynFlags f
where f dflags
| gopt Opt_LlvmFillUndefWithGarbage dflags,
Just lit <- garbageLit t = ppLit lit
| otherwise = text "undef"
garbageLit :: LlvmType -> Maybe LlvmLit
garbageLit t@(LMInt w) = Just (LMIntLit (0xbbbbbbbbbbbbbbb0 `mod` (2^w)) t)
-- Use a value that looks like an untagged pointer, so we are more
-- likely to try to enter it
garbageLit t
| isFloat t = Just (LMFloatLit 12345678.9 t)
garbageLit t@(LMPointer _) = Just (LMNullLit t)
-- Using null isn't totally ideal, since some functions may check for null.
-- But producing another value is inconvenient since it needs a cast,
-- and the knowledge for how to format casts is in PpLlvm.
garbageLit _ = Nothing
-- More cases could be added, but this should do for now.
-- | Return the 'LlvmType' of the 'LlvmVar'
getVarType :: LlvmVar -> LlvmType
getVarType (LMGlobalVar _ y _ _ _ _) = y
getVarType (LMLocalVar _ y ) = y
getVarType (LMNLocalVar _ y ) = y
getVarType (LMLitVar l ) = getLitType l
-- | Return the 'LlvmType' of a 'LlvmLit'
getLitType :: LlvmLit -> LlvmType
getLitType (LMIntLit _ t) = t
getLitType (LMFloatLit _ t) = t
getLitType (LMVectorLit []) = panic "getLitType"
getLitType (LMVectorLit ls) = LMVector (length ls) (getLitType (head ls))
getLitType (LMNullLit t) = t
getLitType (LMUndefLit t) = t
-- | Return the 'LlvmType' of the 'LlvmStatic'
getStatType :: LlvmStatic -> LlvmType
getStatType (LMStaticLit l ) = getLitType l
getStatType (LMUninitType t) = t
getStatType (LMStaticStr _ t) = t
getStatType (LMStaticArray _ t) = t
getStatType (LMStaticStruc _ t) = t
getStatType (LMStaticPointer v) = getVarType v
getStatType (LMBitc _ t) = t
getStatType (LMPtoI _ t) = t
getStatType (LMAdd t _) = getStatType t
getStatType (LMSub t _) = getStatType t
getStatType (LMComment _) = error "Can't call getStatType on LMComment!"
-- | Return the 'LlvmLinkageType' for a 'LlvmVar'
getLink :: LlvmVar -> LlvmLinkageType
getLink (LMGlobalVar _ _ l _ _ _) = l
getLink _ = Internal
-- | Add a pointer indirection to the supplied type. 'LMLabel' and 'LMVoid'
-- cannot be lifted.
pLift :: LlvmType -> LlvmType
pLift LMLabel = error "Labels are unliftable"
pLift LMVoid = error "Voids are unliftable"
pLift LMMetadata = error "Metadatas are unliftable"
pLift x = LMPointer x
-- | Lift a variable to 'LMPointer' type.
pVarLift :: LlvmVar -> LlvmVar
pVarLift (LMGlobalVar s t l x a c) = LMGlobalVar s (pLift t) l x a c
pVarLift (LMLocalVar s t ) = LMLocalVar s (pLift t)
pVarLift (LMNLocalVar s t ) = LMNLocalVar s (pLift t)
pVarLift (LMLitVar _ ) = error $ "Can't lower a literal type!"
-- | Remove the pointer indirection of the supplied type. Only 'LMPointer'
-- constructors can be lowered.
pLower :: LlvmType -> LlvmType
pLower (LMPointer x) = x
pLower x = pprPanic "llvmGen(pLower)"
$ ppr x <+> text " is a unlowerable type, need a pointer"
-- | Lower a variable of 'LMPointer' type.
pVarLower :: LlvmVar -> LlvmVar
pVarLower (LMGlobalVar s t l x a c) = LMGlobalVar s (pLower t) l x a c
pVarLower (LMLocalVar s t ) = LMLocalVar s (pLower t)
pVarLower (LMNLocalVar s t ) = LMNLocalVar s (pLower t)
pVarLower (LMLitVar _ ) = error $ "Can't lower a literal type!"
-- | Test if the given 'LlvmType' is an integer
isInt :: LlvmType -> Bool
isInt (LMInt _) = True
isInt _ = False
-- | Test if the given 'LlvmType' is a floating point type
isFloat :: LlvmType -> Bool
isFloat LMFloat = True
isFloat LMDouble = True
isFloat LMFloat80 = True
isFloat LMFloat128 = True
isFloat _ = False
-- | Test if the given 'LlvmType' is an 'LMPointer' construct
isPointer :: LlvmType -> Bool
isPointer (LMPointer _) = True
isPointer _ = False
-- | Test if the given 'LlvmType' is an 'LMVector' construct
isVector :: LlvmType -> Bool
isVector (LMVector {}) = True
isVector _ = False
-- | Test if a 'LlvmVar' is global.
isGlobal :: LlvmVar -> Bool
isGlobal (LMGlobalVar _ _ _ _ _ _) = True
isGlobal _ = False
-- | Width in bits of an 'LlvmType', returns 0 if not applicable
llvmWidthInBits :: DynFlags -> LlvmType -> Int
llvmWidthInBits _ (LMInt n) = n
llvmWidthInBits _ (LMFloat) = 32
llvmWidthInBits _ (LMDouble) = 64
llvmWidthInBits _ (LMFloat80) = 80
llvmWidthInBits _ (LMFloat128) = 128
-- Could return either a pointer width here or the width of what
-- it points to. We will go with the former for now.
-- PMW: At least judging by the way LLVM outputs constants, pointers
-- should use the former, but arrays the latter.
llvmWidthInBits dflags (LMPointer _) = llvmWidthInBits dflags (llvmWord dflags)
llvmWidthInBits dflags (LMArray n t) = n * llvmWidthInBits dflags t
llvmWidthInBits dflags (LMVector n ty) = n * llvmWidthInBits dflags ty
llvmWidthInBits _ LMLabel = 0
llvmWidthInBits _ LMVoid = 0
llvmWidthInBits dflags (LMStruct tys) = sum $ map (llvmWidthInBits dflags) tys
llvmWidthInBits _ (LMStructU _) =
-- It's not trivial to calculate the bit width of the unpacked structs,
-- since they will be aligned depending on the specified datalayout (
-- http://llvm.org/docs/LangRef.html#data-layout ). One way we could support
-- this could be to make the LlvmCodeGen.Ppr.moduleLayout be a data type
-- that exposes the alignment information. However, currently the only place
-- we use unpacked structs is LLVM intrinsics that return them (e.g.,
-- llvm.sadd.with.overflow.*), so we don't actually need to compute their
-- bit width.
panic "llvmWidthInBits: not implemented for LMStructU"
llvmWidthInBits _ (LMFunction _) = 0
llvmWidthInBits dflags (LMAlias (_,t)) = llvmWidthInBits dflags t
llvmWidthInBits _ LMMetadata = panic "llvmWidthInBits: Meta-data has no runtime representation!"
-- -----------------------------------------------------------------------------
-- ** Shortcut for Common Types
--
i128, i64, i32, i16, i8, i1, i8Ptr :: LlvmType
i128 = LMInt 128
i64 = LMInt 64
i32 = LMInt 32
i16 = LMInt 16
i8 = LMInt 8
i1 = LMInt 1
i8Ptr = pLift i8
-- | The target architectures word size
llvmWord, llvmWordPtr :: DynFlags -> LlvmType
llvmWord dflags = LMInt (wORD_SIZE dflags * 8)
llvmWordPtr dflags = pLift (llvmWord dflags)
-- -----------------------------------------------------------------------------
-- * LLVM Function Types
--
-- | An LLVM Function
data LlvmFunctionDecl = LlvmFunctionDecl {
-- | Unique identifier of the function
decName :: LMString,
-- | LinkageType of the function
funcLinkage :: LlvmLinkageType,
-- | The calling convention of the function
funcCc :: LlvmCallConvention,
-- | Type of the returned value
decReturnType :: LlvmType,
-- | Indicates if this function uses varargs
decVarargs :: LlvmParameterListType,
-- | Parameter types and attributes
decParams :: [LlvmParameter],
-- | Function align value, must be power of 2
funcAlign :: LMAlign
}
deriving (Eq)
instance Outputable LlvmFunctionDecl where
ppr (LlvmFunctionDecl n l c r varg p a)
= let align = case a of
Just a' -> text " align " <> ppr a'
Nothing -> empty
in ppr l <+> ppr c <+> ppr r <+> char '@' <> ftext n <>
lparen <> ppParams varg p <> rparen <> align
type LlvmFunctionDecls = [LlvmFunctionDecl]
type LlvmParameter = (LlvmType, [LlvmParamAttr])
-- | LLVM Parameter Attributes.
--
-- Parameter attributes are used to communicate additional information about
-- the result or parameters of a function
data LlvmParamAttr
-- | This indicates to the code generator that the parameter or return value
-- should be zero-extended to a 32-bit value by the caller (for a parameter)
-- or the callee (for a return value).
= ZeroExt
-- | This indicates to the code generator that the parameter or return value
-- should be sign-extended to a 32-bit value by the caller (for a parameter)
-- or the callee (for a return value).
| SignExt
-- | This indicates that this parameter or return value should be treated in
-- a special target-dependent fashion during while emitting code for a
-- function call or return (usually, by putting it in a register as opposed
-- to memory).
| InReg
-- | This indicates that the pointer parameter should really be passed by
-- value to the function.
| ByVal
-- | This indicates that the pointer parameter specifies the address of a
-- structure that is the return value of the function in the source program.
| SRet
-- | This indicates that the pointer does not alias any global or any other
-- parameter.
| NoAlias
-- | This indicates that the callee does not make any copies of the pointer
-- that outlive the callee itself
| NoCapture
-- | This indicates that the pointer parameter can be excised using the
-- trampoline intrinsics.
| Nest
deriving (Eq)
instance Outputable LlvmParamAttr where
ppr ZeroExt = text "zeroext"
ppr SignExt = text "signext"
ppr InReg = text "inreg"
ppr ByVal = text "byval"
ppr SRet = text "sret"
ppr NoAlias = text "noalias"
ppr NoCapture = text "nocapture"
ppr Nest = text "nest"
-- | Llvm Function Attributes.
--
-- Function attributes are set to communicate additional information about a
-- function. Function attributes are considered to be part of the function,
-- not of the function type, so functions with different parameter attributes
-- can have the same function type. Functions can have multiple attributes.
--
-- Descriptions taken from <http://llvm.org/docs/LangRef.html#fnattrs>
data LlvmFuncAttr
-- | This attribute indicates that the inliner should attempt to inline this
-- function into callers whenever possible, ignoring any active inlining
-- size threshold for this caller.
= AlwaysInline
-- | This attribute indicates that the source code contained a hint that
-- inlining this function is desirable (such as the \"inline\" keyword in
-- C/C++). It is just a hint; it imposes no requirements on the inliner.
| InlineHint
-- | This attribute indicates that the inliner should never inline this
-- function in any situation. This attribute may not be used together
-- with the alwaysinline attribute.
| NoInline
-- | This attribute suggests that optimization passes and code generator
-- passes make choices that keep the code size of this function low, and
-- otherwise do optimizations specifically to reduce code size.
| OptSize
-- | This function attribute indicates that the function never returns
-- normally. This produces undefined behavior at runtime if the function
-- ever does dynamically return.
| NoReturn
-- | This function attribute indicates that the function never returns with
-- an unwind or exceptional control flow. If the function does unwind, its
-- runtime behavior is undefined.
| NoUnwind
-- | This attribute indicates that the function computes its result (or
-- decides to unwind an exception) based strictly on its arguments, without
-- dereferencing any pointer arguments or otherwise accessing any mutable
-- state (e.g. memory, control registers, etc) visible to caller functions.
-- It does not write through any pointer arguments (including byval
-- arguments) and never changes any state visible to callers. This means
-- that it cannot unwind exceptions by calling the C++ exception throwing
-- methods, but could use the unwind instruction.
| ReadNone
-- | This attribute indicates that the function does not write through any
-- pointer arguments (including byval arguments) or otherwise modify any
-- state (e.g. memory, control registers, etc) visible to caller functions.
-- It may dereference pointer arguments and read state that may be set in
-- the caller. A readonly function always returns the same value (or unwinds
-- an exception identically) when called with the same set of arguments and
-- global state. It cannot unwind an exception by calling the C++ exception
-- throwing methods, but may use the unwind instruction.
| ReadOnly
-- | This attribute indicates that the function should emit a stack smashing
-- protector. It is in the form of a \"canary\"—a random value placed on the
-- stack before the local variables that's checked upon return from the
-- function to see if it has been overwritten. A heuristic is used to
-- determine if a function needs stack protectors or not.
--
-- If a function that has an ssp attribute is inlined into a function that
-- doesn't have an ssp attribute, then the resulting function will have an
-- ssp attribute.
| Ssp
-- | This attribute indicates that the function should always emit a stack
-- smashing protector. This overrides the ssp function attribute.
--
-- If a function that has an sspreq attribute is inlined into a function
-- that doesn't have an sspreq attribute or which has an ssp attribute,
-- then the resulting function will have an sspreq attribute.
| SspReq
-- | This attribute indicates that the code generator should not use a red
-- zone, even if the target-specific ABI normally permits it.
| NoRedZone
-- | This attributes disables implicit floating point instructions.
| NoImplicitFloat
-- | This attribute disables prologue / epilogue emission for the function.
-- This can have very system-specific consequences.
| Naked
deriving (Eq)
instance Outputable LlvmFuncAttr where
ppr AlwaysInline = text "alwaysinline"
ppr InlineHint = text "inlinehint"
ppr NoInline = text "noinline"
ppr OptSize = text "optsize"
ppr NoReturn = text "noreturn"
ppr NoUnwind = text "nounwind"
ppr ReadNone = text "readnon"
ppr ReadOnly = text "readonly"
ppr Ssp = text "ssp"
ppr SspReq = text "ssqreq"
ppr NoRedZone = text "noredzone"
ppr NoImplicitFloat = text "noimplicitfloat"
ppr Naked = text "naked"
-- | Different types to call a function.
data LlvmCallType
-- | Normal call, allocate a new stack frame.
= StdCall
-- | Tail call, perform the call in the current stack frame.
| TailCall
deriving (Eq,Show)
-- | Different calling conventions a function can use.
data LlvmCallConvention
-- | The C calling convention.
-- This calling convention (the default if no other calling convention is
-- specified) matches the target C calling conventions. This calling
-- convention supports varargs function calls and tolerates some mismatch in
-- the declared prototype and implemented declaration of the function (as
-- does normal C).
= CC_Ccc
-- | This calling convention attempts to make calls as fast as possible
-- (e.g. by passing things in registers). This calling convention allows
-- the target to use whatever tricks it wants to produce fast code for the
-- target, without having to conform to an externally specified ABI
-- (Application Binary Interface). Implementations of this convention should
-- allow arbitrary tail call optimization to be supported. This calling
-- convention does not support varargs and requires the prototype of al
-- callees to exactly match the prototype of the function definition.
| CC_Fastcc
-- | This calling convention attempts to make code in the caller as efficient
-- as possible under the assumption that the call is not commonly executed.
-- As such, these calls often preserve all registers so that the call does
-- not break any live ranges in the caller side. This calling convention
-- does not support varargs and requires the prototype of all callees to
-- exactly match the prototype of the function definition.
| CC_Coldcc
-- | The GHC-specific 'registerised' calling convention.
| CC_Ghc
-- | Any calling convention may be specified by number, allowing
-- target-specific calling conventions to be used. Target specific calling
-- conventions start at 64.
| CC_Ncc Int
-- | X86 Specific 'StdCall' convention. LLVM includes a specific alias for it
-- rather than just using CC_Ncc.
| CC_X86_Stdcc
deriving (Eq)
instance Outputable LlvmCallConvention where
ppr CC_Ccc = text "ccc"
ppr CC_Fastcc = text "fastcc"
ppr CC_Coldcc = text "coldcc"
ppr CC_Ghc = text "ghccc"
ppr (CC_Ncc i) = text "cc " <> ppr i
ppr CC_X86_Stdcc = text "x86_stdcallcc"
-- | Functions can have a fixed amount of parameters, or a variable amount.
data LlvmParameterListType
-- Fixed amount of arguments.
= FixedArgs
-- Variable amount of arguments.
| VarArgs
deriving (Eq,Show)
-- | Linkage type of a symbol.
--
-- The description of the constructors is copied from the Llvm Assembly Language
-- Reference Manual <http://www.llvm.org/docs/LangRef.html#linkage>, because
-- they correspond to the Llvm linkage types.
data LlvmLinkageType
-- | Global values with internal linkage are only directly accessible by
-- objects in the current module. In particular, linking code into a module
-- with an internal global value may cause the internal to be renamed as
-- necessary to avoid collisions. Because the symbol is internal to the
-- module, all references can be updated. This corresponds to the notion
-- of the @static@ keyword in C.
= Internal
-- | Globals with @linkonce@ linkage are merged with other globals of the
-- same name when linkage occurs. This is typically used to implement
-- inline functions, templates, or other code which must be generated
-- in each translation unit that uses it. Unreferenced linkonce globals are
-- allowed to be discarded.
| LinkOnce
-- | @weak@ linkage is exactly the same as linkonce linkage, except that
-- unreferenced weak globals may not be discarded. This is used for globals
-- that may be emitted in multiple translation units, but that are not
-- guaranteed to be emitted into every translation unit that uses them. One
-- example of this are common globals in C, such as @int X;@ at global
-- scope.
| Weak
-- | @appending@ linkage may only be applied to global variables of pointer
-- to array type. When two global variables with appending linkage are
-- linked together, the two global arrays are appended together. This is
-- the Llvm, typesafe, equivalent of having the system linker append
-- together @sections@ with identical names when .o files are linked.
| Appending
-- | The semantics of this linkage follow the ELF model: the symbol is weak
-- until linked, if not linked, the symbol becomes null instead of being an
-- undefined reference.
| ExternWeak
-- | The symbol participates in linkage and can be used to resolve external
-- symbol references.
| ExternallyVisible
-- | Alias for 'ExternallyVisible' but with explicit textual form in LLVM
-- assembly.
| External
-- | Symbol is private to the module and should not appear in the symbol table
| Private
deriving (Eq)
instance Outputable LlvmLinkageType where
ppr Internal = text "internal"
ppr LinkOnce = text "linkonce"
ppr Weak = text "weak"
ppr Appending = text "appending"
ppr ExternWeak = text "extern_weak"
-- ExternallyVisible does not have a textual representation, it is
-- the linkage type a function resolves to if no other is specified
-- in Llvm.
ppr ExternallyVisible = empty
ppr External = text "external"
ppr Private = text "private"
-- -----------------------------------------------------------------------------
-- * LLVM Operations
--
-- | Llvm binary operators machine operations.
data LlvmMachOp
= LM_MO_Add -- ^ add two integer, floating point or vector values.
| LM_MO_Sub -- ^ subtract two ...
| LM_MO_Mul -- ^ multiply ..
| LM_MO_UDiv -- ^ unsigned integer or vector division.
| LM_MO_SDiv -- ^ signed integer ..
| LM_MO_URem -- ^ unsigned integer or vector remainder (mod)
| LM_MO_SRem -- ^ signed ...
| LM_MO_FAdd -- ^ add two floating point or vector values.
| LM_MO_FSub -- ^ subtract two ...
| LM_MO_FMul -- ^ multiply ...
| LM_MO_FDiv -- ^ divide ...
| LM_MO_FRem -- ^ remainder ...
-- | Left shift
| LM_MO_Shl
-- | Logical shift right
-- Shift right, filling with zero
| LM_MO_LShr
-- | Arithmetic shift right
-- The most significant bits of the result will be equal to the sign bit of
-- the left operand.
| LM_MO_AShr
| LM_MO_And -- ^ AND bitwise logical operation.
| LM_MO_Or -- ^ OR bitwise logical operation.
| LM_MO_Xor -- ^ XOR bitwise logical operation.
deriving (Eq)
instance Outputable LlvmMachOp where
ppr LM_MO_Add = text "add"
ppr LM_MO_Sub = text "sub"
ppr LM_MO_Mul = text "mul"
ppr LM_MO_UDiv = text "udiv"
ppr LM_MO_SDiv = text "sdiv"
ppr LM_MO_URem = text "urem"
ppr LM_MO_SRem = text "srem"
ppr LM_MO_FAdd = text "fadd"
ppr LM_MO_FSub = text "fsub"
ppr LM_MO_FMul = text "fmul"
ppr LM_MO_FDiv = text "fdiv"
ppr LM_MO_FRem = text "frem"
ppr LM_MO_Shl = text "shl"
ppr LM_MO_LShr = text "lshr"
ppr LM_MO_AShr = text "ashr"
ppr LM_MO_And = text "and"
ppr LM_MO_Or = text "or"
ppr LM_MO_Xor = text "xor"
-- | Llvm compare operations.
data LlvmCmpOp
= LM_CMP_Eq -- ^ Equal (Signed and Unsigned)
| LM_CMP_Ne -- ^ Not equal (Signed and Unsigned)
| LM_CMP_Ugt -- ^ Unsigned greater than
| LM_CMP_Uge -- ^ Unsigned greater than or equal
| LM_CMP_Ult -- ^ Unsigned less than
| LM_CMP_Ule -- ^ Unsigned less than or equal
| LM_CMP_Sgt -- ^ Signed greater than
| LM_CMP_Sge -- ^ Signed greater than or equal
| LM_CMP_Slt -- ^ Signed less than
| LM_CMP_Sle -- ^ Signed less than or equal
-- Float comparisons. GHC uses a mix of ordered and unordered float
-- comparisons.
| LM_CMP_Feq -- ^ Float equal
| LM_CMP_Fne -- ^ Float not equal
| LM_CMP_Fgt -- ^ Float greater than
| LM_CMP_Fge -- ^ Float greater than or equal
| LM_CMP_Flt -- ^ Float less than
| LM_CMP_Fle -- ^ Float less than or equal
deriving (Eq)
instance Outputable LlvmCmpOp where
ppr LM_CMP_Eq = text "eq"
ppr LM_CMP_Ne = text "ne"
ppr LM_CMP_Ugt = text "ugt"
ppr LM_CMP_Uge = text "uge"
ppr LM_CMP_Ult = text "ult"
ppr LM_CMP_Ule = text "ule"
ppr LM_CMP_Sgt = text "sgt"
ppr LM_CMP_Sge = text "sge"
ppr LM_CMP_Slt = text "slt"
ppr LM_CMP_Sle = text "sle"
ppr LM_CMP_Feq = text "oeq"
ppr LM_CMP_Fne = text "une"
ppr LM_CMP_Fgt = text "ogt"
ppr LM_CMP_Fge = text "oge"
ppr LM_CMP_Flt = text "olt"
ppr LM_CMP_Fle = text "ole"
-- | Llvm cast operations.
data LlvmCastOp
= LM_Trunc -- ^ Integer truncate
| LM_Zext -- ^ Integer extend (zero fill)
| LM_Sext -- ^ Integer extend (sign fill)
| LM_Fptrunc -- ^ Float truncate
| LM_Fpext -- ^ Float extend
| LM_Fptoui -- ^ Float to unsigned Integer
| LM_Fptosi -- ^ Float to signed Integer
| LM_Uitofp -- ^ Unsigned Integer to Float
| LM_Sitofp -- ^ Signed Int to Float
| LM_Ptrtoint -- ^ Pointer to Integer
| LM_Inttoptr -- ^ Integer to Pointer
| LM_Bitcast -- ^ Cast between types where no bit manipulation is needed
deriving (Eq)
instance Outputable LlvmCastOp where
ppr LM_Trunc = text "trunc"
ppr LM_Zext = text "zext"
ppr LM_Sext = text "sext"
ppr LM_Fptrunc = text "fptrunc"
ppr LM_Fpext = text "fpext"
ppr LM_Fptoui = text "fptoui"
ppr LM_Fptosi = text "fptosi"
ppr LM_Uitofp = text "uitofp"
ppr LM_Sitofp = text "sitofp"
ppr LM_Ptrtoint = text "ptrtoint"
ppr LM_Inttoptr = text "inttoptr"
ppr LM_Bitcast = text "bitcast"
-- -----------------------------------------------------------------------------
-- * Floating point conversion
--
-- | Convert a Haskell Double to an LLVM hex encoded floating point form. In
-- Llvm float literals can be printed in a big-endian hexadecimal format,
-- regardless of underlying architecture.
--
-- See Note [LLVM Float Types].
ppDouble :: Double -> SDoc
ppDouble d
= let bs = doubleToBytes d
hex d' = case showHex d' "" of
[] -> error "dToStr: too few hex digits for float"
[x] -> ['0',x]
[x,y] -> [x,y]
_ -> error "dToStr: too many hex digits for float"
str = map toUpper $ concat $ fixEndian $ map hex bs
in text "0x" <> text str
-- Note [LLVM Float Types]
-- ~~~~~~~~~~~~~~~~~~~~~~~
-- We use 'ppDouble' for both printing Float and Double floating point types. This is
-- as LLVM expects all floating point constants (single & double) to be in IEEE
-- 754 Double precision format. However, for single precision numbers (Float)
-- they should be *representable* in IEEE 754 Single precision format. So the
-- easiest way to do this is to narrow and widen again.
-- (i.e., Double -> Float -> Double). We must be careful doing this that GHC
-- doesn't optimize that away.
-- Note [narrowFp & widenFp]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~
-- NOTE: we use float2Double & co directly as GHC likes to optimize away
-- successive calls of 'realToFrac', defeating the narrowing. (Bug #7600).
-- 'realToFrac' has inconsistent behaviour with optimisation as well that can
-- also cause issues, these methods don't.
narrowFp :: Double -> Float
{-# NOINLINE narrowFp #-}
narrowFp = double2Float
widenFp :: Float -> Double
{-# NOINLINE widenFp #-}
widenFp = float2Double
ppFloat :: Float -> SDoc
ppFloat = ppDouble . widenFp
-- | Reverse or leave byte data alone to fix endianness on this target.
fixEndian :: [a] -> [a]
#if defined(WORDS_BIGENDIAN)
fixEndian = id
#else
fixEndian = reverse
#endif
--------------------------------------------------------------------------------
-- * Misc functions
--------------------------------------------------------------------------------
ppCommaJoin :: (Outputable a) => [a] -> SDoc
ppCommaJoin strs = hsep $ punctuate comma (map ppr strs)
ppSpaceJoin :: (Outputable a) => [a] -> SDoc
ppSpaceJoin strs = hsep (map ppr strs)
| shlevy/ghc | compiler/llvmGen/Llvm/Types.hs | bsd-3-clause | 35,412 | 0 | 16 | 8,302 | 5,867 | 3,137 | 2,730 | 483 | 4 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
module IHaskell.Display.StaticCanvas (Canvas(..)) where
import Data.Text.Lazy.Builder (toLazyText)
import Data.Text.Lazy (unpack)
import Data.Text (pack, Text)
import System.IO.Unsafe
import Control.Concurrent.MVar
import Graphics.Static
import IHaskell.Display
{-# NOINLINE uniqueCounter #-}
uniqueCounter :: MVar Int
uniqueCounter = unsafePerformIO $ newMVar 0
getUniqueName :: IO Text
getUniqueName = do
val <- takeMVar uniqueCounter
let val' = val + 1
putMVar uniqueCounter val'
return $ pack $ "ihaskellStaticCanvasUniqueID" ++ show val
data Canvas = Canvas { width :: Int, height :: Int, canvas :: CanvasFree () }
instance IHaskellDisplay Canvas where
display cnv = do
name <- getUniqueName
let script = buildScript' (width cnv) (height cnv) name (canvas cnv)
return $ Display [html $ unpack $ toLazyText script]
| artuuge/IHaskell | ihaskell-display/ihaskell-static-canvas/src/IHaskell/Display/StaticCanvas.hs | mit | 976 | 0 | 13 | 216 | 273 | 146 | 127 | 24 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE UnboxedSums #-}
{-# OPTIONS_GHC -O2 #-}
module Packed.Bytes.Stream.ST
( ByteStream(..)
, empty
, unpack
, fromBytes
) where
import Data.Primitive (Array,ByteArray(..))
import Data.Semigroup (Semigroup)
import Data.Word (Word8)
import GHC.Exts (RealWorld,State#,Int#,ByteArray#)
import GHC.Int (Int(I#))
import GHC.ST (ST(..))
import Packed.Bytes (Bytes(..))
import System.IO (Handle)
import qualified Data.Primitive as PM
import qualified Data.Semigroup as SG
import qualified Packed.Bytes as B
type Bytes# = (# ByteArray#, Int#, Int# #)
newtype ByteStream s = ByteStream
(State# s -> (# State# s, (# (# #) | (# Bytes# , ByteStream s #) #) #) )
fromBytes :: Bytes -> ByteStream s
fromBytes b = ByteStream
(\s0 -> (# s0, (# | (# unboxBytes b, empty #) #) #))
nextChunk :: ByteStream s -> ST s (Maybe (Bytes,ByteStream s))
nextChunk (ByteStream f) = ST $ \s0 -> case f s0 of
(# s1, r #) -> case r of
(# (# #) | #) -> (# s1, Nothing #)
(# | (# theBytes, theStream #) #) -> (# s1, Just (boxBytes theBytes, theStream) #)
empty :: ByteStream s
empty = ByteStream (\s -> (# s, (# (# #) | #) #) )
boxBytes :: Bytes# -> Bytes
boxBytes (# a, b, c #) = Bytes (ByteArray a) (I# b) (I# c)
unboxBytes :: Bytes -> Bytes#
unboxBytes (Bytes (ByteArray a) (I# b) (I# c)) = (# a,b,c #)
unpack :: ByteStream s -> ST s [Word8]
unpack stream = ST (unpackInternal stream)
unpackInternal :: ByteStream s -> State# s -> (# State# s, [Word8] #)
unpackInternal (ByteStream f) s0 = case f s0 of
(# s1, r #) -> case r of
(# (# #) | #) -> (# s1, [] #)
(# | (# bytes, stream #) #) -> case unpackInternal stream s1 of
(# s2, ws #) -> (# s2, B.unpack (boxBytes bytes) ++ ws #)
| sdiehl/ghc | testsuite/tests/codeGen/should_run/T15038/src/Packed/Bytes/Stream/ST.hs | bsd-3-clause | 1,853 | 0 | 18 | 375 | 698 | 392 | 306 | 48 | 2 |
{-@ LIQUID "--no-termination" @-}
module Foo where
data RBTree a = Leaf
| Node Color !BlackHeight !(RBTree a) a !(RBTree a)
deriving (Show)
data Color = B -- ^ Black
| R -- ^ Red
deriving (Eq,Show)
type BlackHeight = Int
type RBTreeBDel a = (RBTree a, Bool)
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- delete :: Ord a => a -> RBTree a -> RBTree a
-- delete x t = turnB' s
-- where
-- (s,_) = delete' x t
--
-- delete' :: Ord a => a -> RBTree a -> RBTreeBDel a
-- delete' _ Leaf = (Leaf, False)
-- delete' x (Node c h l y r) = case compare x y of
-- LT -> let (l',d) = delete' x l
-- t = Node c h l' y r
-- in if d then unbalancedR c (h-1) l' y r else (t, False)
-- GT -> let (r',d) = delete' x r
-- t = Node c h l y r'
-- in if d then unbalancedL c (h-1) l y r' else (t, False)
-- EQ -> case r of
-- Leaf -> if c == B then blackify l else (l, False)
-- _ -> let ((r',d),m) = deleteMin' r
-- t = Node c h l m r'
-- in if d then unbalancedL c (h-1) l m r' else (t, False)
-- deleteMin :: RBTree a -> RBTree a
-- deleteMin Leaf = Leaf
-- deleteMin t = turnB' s
-- where
-- ((s, _), _) = deleteMin' t
{-@ deleteMin' :: t:RBT a -> (({v: ARBT a | ((IsB t) => (isRB v))}, Bool), a) @-}
deleteMin' :: RBTree a -> (RBTreeBDel a, a)
deleteMin' Leaf = error "deleteMin'"
deleteMin' (Node B _ Leaf x Leaf) = ((Leaf, True), x)
deleteMin' (Node B _ Leaf x r@(Node R _ _ _ _)) = ((turnB r, False), x)
deleteMin' (Node R _ Leaf x r) = ((r, False), x)
deleteMin' (Node c h l x r) = if d then (tD, m) else (tD', m)
where
((l',d),m) = deleteMin' l -- GUESS: black l --> red l' iff d is TRUE
tD = unbalancedR c (h-1) l' x r
tD' = (Node c h l' x r, False)
-- GUESS: black l --> red l' iff d is TRUE
{-@ unbalancedL :: Color -> BlackHeight -> RBT a -> a -> ARBT a -> RBTB a @-}
unbalancedL :: Color -> BlackHeight -> RBTree a -> a -> RBTree a -> RBTreeBDel a
unbalancedL c h l@(Node B _ _ _ _) x r
= (balanceL B h (turnR l) x r, c == B)
unbalancedL B h (Node R lh ll lx lr@(Node B _ _ _ _)) x r
= (Node B lh ll lx (balanceL B h (turnR lr) x r), False)
unbalancedL _ _ _ _ _ = error "unbalancedL"
-- The left tree lacks one Black node
{-@ unbalancedR :: Color -> BlackHeight -> ARBT a -> a -> RBT a -> RBTB a @-}
unbalancedR :: Color -> BlackHeight -> RBTree a -> a -> RBTree a -> RBTreeBDel a
-- Decreasing one Black node in the right
unbalancedR c h l x r@(Node B _ _ _ _)
= (balanceR B h l x (turnR r), c == B)
-- Taking one Red node from the right and adding it to the right as Black
unbalancedR B h l x (Node R rh rl@(Node B _ _ _ _) rx rr)
= (Node B rh (balanceR B h l x (turnR rl)) rx rr, False)
unbalancedR _ _ _ _ _ = error "unbalancedR"
{-@ balanceL :: k:Color -> BlackHeight -> {v:ARBT a | ((Red k) => (IsB v))} -> a -> {v:RBT a | ((Red k) => (IsB v))} -> RBT a @-}
balanceL B h (Node R _ (Node R _ a x b) y c) z d =
Node R (h+1) (Node B h a x b) y (Node B h c z d)
balanceL B h (Node R _ a x (Node R _ b y c)) z d =
Node R (h+1) (Node B h a x b) y (Node B h c z d)
balanceL k h l x r = Node k h l x r
{-@ balanceR :: k:Color -> BlackHeight -> {v:RBT a | ((Red k) => (IsB v))} -> a -> {v:ARBT a | ((Red k) => (IsB v))} -> RBT a @-}
balanceR :: Color -> BlackHeight -> RBTree a -> a -> RBTree a -> RBTree a
balanceR B h a x (Node R _ b y (Node R _ c z d)) =
Node R (h+1) (Node B h a x b) y (Node B h c z d)
balanceR B h a x (Node R _ (Node R _ b y c) z d) =
Node R (h+1) (Node B h a x b) y (Node B h c z d)
balanceR k h l x r = Node k h l x r
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
{-@ insert :: (Ord a) => a -> RBT a -> RBT a @-}
insert :: Ord a => a -> RBTree a -> RBTree a
insert kx t = turnB (insert' kx t)
{-@ turnB :: ARBT a -> RBT a @-}
turnB Leaf = error "turnB"
turnB (Node _ h l x r) = Node B h l x r
{-@ turnR :: RBT a -> ARBT a @-}
turnR Leaf = error "turnR"
turnR (Node _ h l x r) = Node R h l x r
{-@ turnB' :: ARBT a -> RBT a @-}
turnB' Leaf = Leaf
turnB' (Node _ h l x r) = Node B h l x r
{-@ insert' :: (Ord a) => a -> t:RBT a -> {v: ARBT a | ((IsB t) => (isRB v))} @-}
insert' :: Ord a => a -> RBTree a -> RBTree a
insert' kx Leaf = Node R 1 Leaf kx Leaf
insert' kx s@(Node B h l x r) = case compare kx x of
LT -> let zoo = balanceL' h (insert' kx l) x r in zoo
GT -> let zoo = balanceR' h l x (insert' kx r) in zoo
EQ -> s
insert' kx s@(Node R h l x r) = case compare kx x of
LT -> Node R h (insert' kx l) x r
GT -> Node R h l x (insert' kx r)
EQ -> s
{-@ balanceL' :: Int -> ARBT a -> a -> RBT a -> RBT a @-}
balanceL' :: BlackHeight -> RBTree a -> a -> RBTree a -> RBTree a
balanceL' h (Node R _ (Node R _ a x b) y c) z d =
Node R (h+1) (Node B h a x b) y (Node B h c z d)
balanceL' h (Node R _ a x (Node R _ b y c)) z d =
Node R (h+1) (Node B h a x b) y (Node B h c z d)
balanceL' h l x r = Node B h l x r
{-@ balanceR' :: Int -> RBT a -> a -> ARBT a -> RBT a @-}
balanceR' :: BlackHeight -> RBTree a -> a -> RBTree a -> RBTree a
balanceR' h a x (Node R _ b y (Node R _ c z d)) =
Node R (h+1) (Node B h a x b) y (Node B h c z d)
balanceR' h a x (Node R _ (Node R _ b y c) z d) =
Node R (h+1) (Node B h a x b) y (Node B h c z d)
balanceR' h l x r = Node B h l x r
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
{-@ type ARBTB a = (RBT a, Bool) @-}
{-@ type RBTB a = (RBT a, Bool) @-}
{-@ type RBT a = {v: (RBTree a) | (isRB v)} @-}
{- type ARBT a = {v: (RBTree a) | ((isARB v) && ((IsB v) => (isRB v)))} -}
{-@ type ARBT a = {v: (RBTree a) | (isARB v) } @-}
{-@ measure isRB :: RBTree a -> Prop
isRB (Leaf) = true
isRB (Node c h l x r) = ((isRB l) && (isRB r) && ((Red c) => ((IsB l) && (IsB r))))
@-}
{-@ measure isARB :: (RBTree a) -> Prop
isARB (Leaf) = true
isARB (Node c h l x r) = ((isRB l) && (isRB r))
@-}
{-@ measure col :: RBTree a -> Color
col (Node c h l x r) = c
col (Leaf) = B
@-}
{-@ predicate IsB T = not (Red (col T)) @-}
{-@ predicate Red C = C == R @-}
-------------------------------------------------------------------------------
-- Auxiliary Invariants -------------------------------------------------------
-------------------------------------------------------------------------------
{-@ predicate Invs V = ((Inv1 V) && (Inv2 V)) @-}
{-@ predicate Inv1 V = (((isARB V) && (IsB V)) => (isRB V)) @-}
{-@ predicate Inv2 V = ((isRB v) => (isARB v)) @-}
{-@ invariant {v: RBTree a | (Invs v)} @-}
{-@ inv :: RBTree a -> {v:RBTree a | (Invs v)} @-}
inv Leaf = Leaf
inv (Node c h l x r) = Node c h (inv l) x (inv r)
| mightymoose/liquidhaskell | benchmarks/llrbtree-0.1.1/Data/Set/RBTree-mini-color.hs | bsd-3-clause | 7,444 | 0 | 14 | 2,090 | 2,207 | 1,144 | 1,063 | 79 | 5 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- experimental, not expected to work
{- our goal:
config = do
add layout Full
set terminal "urxvt"
add keys [blah blah blah]
-}
{-
ideas:
composability!
"only once" features like avoidStruts, ewmhDesktops
-}
module XMonad.Config.Monad where
import XMonad hiding (terminal, keys)
import qualified XMonad as X
import Control.Monad.Writer
import Data.Monoid
import Data.Accessor
import Data.Accessor.Basic hiding (set)
-- Ugly! To fix this we'll need to change the kind of XConfig.
newtype LayoutList a = LL [Layout a] deriving Monoid
type W = Dual (Endo (XConfig LayoutList))
mkW = Dual . Endo
newtype Config a = C (WriterT W IO a)
deriving (Functor, Monad, MonadWriter W)
-- references:
layout = fromSetGet (\x c -> c { layoutHook = x }) layoutHook
terminal = fromSetGet (\x c -> c { X.terminal = x }) X.terminal
keys = fromSetGet (\x c -> c { X.keys = x }) X.keys
set :: Accessor (XConfig LayoutList) a -> a -> Config ()
set r x = tell (mkW $ r ^= x)
add r x = tell (mkW (r ^: mappend x))
--
example :: Config ()
example = do
add layout $ LL [Layout $ Full] -- make this better
set terminal "urxvt"
| pjones/xmonad-test | vendor/xmonad-contrib/XMonad/Config/Monad.hs | bsd-2-clause | 1,188 | 0 | 10 | 247 | 362 | 203 | 159 | 23 | 1 |
{-|
Module : Web.Facebook.Messenger
Copyright : (c) Felix Paulusma, 2016
License : MIT
Maintainer : [email protected]
Stability : semi-experimental
TODO: Explanation of this entire package (later)
-}
module Web.Facebook.Messenger (
module Web.Facebook.Messenger.Types
) where
import Web.Facebook.Messenger.Types
| Vlix/facebookmessenger | src/Web/Facebook/Messenger.hs | mit | 343 | 0 | 5 | 60 | 25 | 18 | 7 | 3 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{- |
Module : Language.Egison.EvalState
Licence : MIT
This module defines the state during the evaluation.
-}
module Language.Egison.EvalState
( EvalState(..)
, initialEvalState
, MonadEval(..)
, mLabelFuncName
) where
import Control.Monad.Except
import Control.Monad.Trans.State.Strict
import Language.Egison.IExpr
newtype EvalState = EvalState
-- Names of called functions for improved error message
{ funcNameStack :: [Var]
}
initialEvalState :: EvalState
initialEvalState = EvalState { funcNameStack = [] }
class (Applicative m, Monad m) => MonadEval m where
pushFuncName :: Var -> m ()
topFuncName :: m Var
popFuncName :: m ()
getFuncNameStack :: m [Var]
instance Monad m => MonadEval (StateT EvalState m) where
pushFuncName name = do
st <- get
put $ st { funcNameStack = name : funcNameStack st }
return ()
topFuncName = head . funcNameStack <$> get
popFuncName = do
st <- get
put $ st { funcNameStack = tail $ funcNameStack st }
return ()
getFuncNameStack = funcNameStack <$> get
instance (MonadEval m) => MonadEval (ExceptT e m) where
pushFuncName name = lift $ pushFuncName name
topFuncName = lift topFuncName
popFuncName = lift popFuncName
getFuncNameStack = lift getFuncNameStack
mLabelFuncName :: MonadEval m => Maybe Var -> m a -> m a
mLabelFuncName Nothing m = m
mLabelFuncName (Just name) m = do
pushFuncName name
v <- m
popFuncName
return v
| egison/egison | hs-src/Language/Egison/EvalState.hs | mit | 1,515 | 0 | 12 | 338 | 428 | 224 | 204 | 41 | 1 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.Element (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.Element
#else
module Graphics.UI.Gtk.WebKit.DOM.Element
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.Element
#else
import Graphics.UI.Gtk.WebKit.DOM.Element
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/Element.hs | mit | 420 | 0 | 5 | 39 | 33 | 26 | 7 | 4 | 0 |
module GHCJS.Utils where
import GHCJS.Foreign
import GHCJS.Types
foreign import javascript unsafe
"console.log($1)" consoleLog :: JSRef a -> IO ()
foreign import javascript unsafe
"(function() { return this; })()" this :: IO (JSRef a) | CRogers/stack-ide-atom | haskell/src/GHCJS/Utils.hs | mit | 242 | 5 | 7 | 40 | 66 | 35 | 31 | 7 | 0 |
module Main where
import Data.Monoid
import Language.LambdaCalculus
maybeFromEither :: Either x y -> Maybe y
maybeFromEither (Left _) = Nothing
maybeFromEither (Right x) = Just x
-- | Read a lambda calclus example from file
--
openExample :: String -> IO (Maybe Term)
openExample ex = do
contents <- readFile $ "samples/" ++ ex ++ ".lc"
return $ maybeFromEither $ parseTerm contents
| owainlewis/lambda-calculus | src/Main.hs | mit | 413 | 0 | 10 | 92 | 123 | 62 | 61 | 10 | 1 |
{-# LANGUAGE MultiParamTypeClasses, DataKinds, KindSignatures, TypeOperators, FlexibleInstances, OverlappingInstances, TypeSynonymInstances, IncoherentInstances #-}
module Math.Matrix where
import Math.Vec hiding (r,g,b,a,x,y,z,w)
import qualified Math.Vec as V (r,g,b,a,x,y,z,w)
import GHC.TypeLits
type Matrix n m a = Vec n (Vec m a)
-- composition
consx :: Vec n a -> Matrix n m a -> Matrix n (m+1) a
consx v m = vmap (uncurry $ cons) $ vzip v m
snocx :: Matrix n m a -> Vec n a -> Matrix n (m+1) a
snocx m v = vmap (uncurry $ snoc) $ vzip m v
-- indexing
-- shorthand
infixr 5 |->
(|->) :: Matrix m n a -> (Int, Int) -> a
(|->) m (r,c) = (m ! r) ! c
-- row vector
row :: Matrix m n a -> Int -> Vec n a
row mat r = mat ! r
infixr 5 <->
(<->) :: Matrix m n a -> Int -> Vec n a
(<->) = row
-- col vector
col :: Matrix m n a -> Int -> Vec m a
col mat c = vmap (!c) mat
infixr 5 <|>
(<|>) :: Matrix m n a -> Int -> Vec m a
(<|>) = col
dimy :: Matrix m n a -> Int
dimy = dim
dimx :: Matrix m n a -> Int
dimx mat = dim $ mat <-> 0
-- commonly used matrix types
type Mat3 = Matrix 3 3 Double
mat3 :: Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Mat3
mat3 a b c d e f g h i
= (a & b & c & nil)
& (d & e & f & nil)
& (g & h & i & nil)
& nil
type Mat4 = Matrix 4 4 Double
mat4 :: Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Mat4
mat4 a b c d e f g h i j k l m n o p
= (a & b & c & d & nil)
& (e & f & g & h & nil)
& (i & j & k & l & nil)
& (m & n & o & p & nil)
& nil
type Mat3f = Matrix 3 3 Float
mat3f :: Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Mat3f
mat3f a b c d e f g h i
= (a & b & c & nil)
& (d & e & f & nil)
& (g & h & i & nil)
& nil
type Mat4f = Matrix 4 4 Float
mat4f :: Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Mat4f
mat4f a b c d e f g h i j k l m n o p
= (a & b & c & d & nil)
& (e & f & g & h & nil)
& (i & j & k & l & nil)
& (m & n & o & p & nil)
& nil
class HomogeneousMatAccessors (n::Nat) where
tx :: Matrix n n a -> a
ty :: Matrix n n a -> a
tz :: Matrix n n a -> a
sx :: Matrix n n a -> a
sy :: Matrix n n a -> a
sz :: Matrix n n a -> a
instance HomogeneousMatAccessors 3 where
tx mat = mat |-> (0,2)
ty mat = mat |-> (1,2)
tz = error "tz undefined for Mat33!"
sx mat = mat |-> (0,0)
sy mat = mat |-> (1,1)
sz = error "scale z undefined for Mat33!"
instance HomogeneousMatAccessors 4 where
tx mat = mat |-> (0,3)
ty mat = mat |-> (1,3)
tz mat = mat |-> (2,3)
sx mat = mat |-> (0,0)
sy mat = mat |-> (1,1)
sz mat = mat |-> (2,2)
instance Num a => ScalarOps (Matrix n m a) a where
s *** m = vmap (s ***) m
instance Fractional a => ScalarFracOps (Matrix n m a) a where
m /// s = vmap (/// s) m
-- common operations
matmul :: Num a => Matrix n m a -> Matrix m p a -> Matrix n p a
matmul a b = vector $ map rowc [0..(dimy a - 1)] where
rowc r = vector $ map (\c -> dot ar (b <|> c)) [0..(dimx b - 1)] where
ar = a <-> r
vecmat :: Num a => Vec n a -> Matrix n m a -> Vec m a
vecmat v m = vector $ map (\c -> dot v (m <|> c)) [0..(dimx m - 1)]
matvec :: Num a => Matrix n m a -> Vec m a -> Vec n a
matvec m v = vector $ map (\r -> dot (m <-> r) v) [0..(dimy m - 1)]
identity :: Num a => Int -> Matrix n n a
identity n = vector $ map row' [0..(n-1)] where
row' i = vector $ replicate i 0 ++ 1:replicate (n-i-1) 0
tensor :: Num a => Vec n a -> Matrix n n a
tensor v = vector $ map row' [0..(dim v - 1)] where
row' i = vmap (* (v ! i)) v
-- typesafe id constructors
identity4 :: Num a => Matrix 4 4 a
identity4 = identity 4
identity3 :: Num a => Matrix 3 3 a
identity3 = identity 3
transpose :: Matrix n m a -> Matrix m n a
transpose m = vector $ map (m <|>) [0..(dimx m - 1)]
-- Doolittle LU decomposition
lu :: Fractional a => Matrix n n a -> (Matrix n n a, Matrix n n a) -- first is L, second is U
lu m = if dim m == dimy m then doolittle (identity $ dim m) m 0 else error "matrix not square" where
mdim = dim m
doolittle l a n
| n == mdim-1 = (l,a)
| otherwise = doolittle l' a' (n+1) where
l' = matmul l ln' -- ln' is inverse of ln
a' = matmul ln a
ln = vector (map id' [0..n] ++ map lr' [(n+1)..(mdim-1)]) where
lr' i = vector $ replicate n 0 ++ [-(ai' i)] ++ replicate (i-n-1) 0 ++ 1:replicate (mdim-i-1) 0
ln' = vector (map id' [0..n] ++ map lr' [(n+1)..(mdim-1)]) where
lr' i = vector $ replicate n 0 ++ [ai' i] ++ replicate (i-n-1) 0 ++ 1:replicate (mdim-i-1) 0
id' i = vector $ replicate i 0 ++ 1:replicate (mdim-i-1) 0
ai' i = (a |-> (i,n)) / (a |-> (n,n))
det :: Fractional a => Matrix n n a -> a
det m
| dim m == 1 = m |-> (0,0)
| dim m == 2 = let a = m |-> (0,0)
b = m |-> (0,1)
c = m |-> (1,0)
d = m |-> (1,1)
in a*d - b*c
| dim m == 3 = let a = m |-> (0,0)
b = m |-> (0,1)
c = m |-> (0,2)
d = m |-> (1,0)
e = m |-> (1,1)
f = m |-> (1,2)
g = m |-> (2,0)
h = m |-> (2,1)
i = m |-> (2,2)
in a*e*i + b*f*g + c*d*h - c*e*g - b*d*i - a*f*h
| otherwise = tridet u where
(_,u) = lu m
tridet mat = foldl (*) 1 $ map (\i -> mat |-> (i,i)) [0..(dim mat - 1)]
-- solve Ax = B for x using forward substitution, where A is an nxn matrix, B is a 1xn vector, and return value x is a 1xn vector
-- assumes A is a lower triangular matrix
forwardsub :: Fractional a => Matrix n n a -> Vec n a -> Vec n a
forwardsub a b = fs a b 0 where
fs m v n
| n == dim v = v
| otherwise = fs m v' (n+1) where
v' = v // [(n, ((v ! n) - fsum) / m_nn)] where
fsum = sum $ map (\i -> (m |-> (n,i)) * (v ! i)) [0..(n - 1)] -- m_n0 * v_0 + m_n1 * v_1 ... + m_nn-1 * v_n-1
m_nn = m |-> (n,n)
-- solve Ax = B for x using backward substitution, where A is an nxn matrix, B is a 1xn vector, and return value x is a 1xn vector
-- assumes A is an upper triangular matrix
backsub :: Fractional a => Matrix n n a -> Vec n a -> Vec n a
backsub a b = bs a b (dim b - 1) where
bs m v n
| n == -1 = v
| otherwise = bs m v' (n-1) where
v' = v // [(n, ((v ! n) - fsum) / m_nn)] where
fsum = sum $ map (\i -> (m |-> (n,i)) * (v ! i)) [(n + 1)..(dim v - 1)]
m_nn = m |-> (n,n)
-- returns the trace of a matrix
tr :: Num a => Matrix n n a -> a
tr m
| dimx m /= dimy m = error "matrix not square"
| otherwise = sum $ map (\i -> m |-> (i,i)) [0..(dim m - 1)]
inv :: Fractional a => Matrix n n a -> Matrix n n a
inv m
| dimx m /= dimy m = error "matrix not square"
| dim m == 2 = let d = det m
t = tr m
in (1/d) *** (t *** identity 2 - m)
| dim m == 3 = let d = det m
t = tr m
t' = tr (matmul m m)
mm = matmul m m
in (1/d) *** ((0.5 * (t*t - t')) *** identity 3 - t *** m + mm)
| dim m == 4 = let d = det m
t = tr m
m2 = matmul m m
m3 = matmul m m2
t2 = tr m2
t3 = tr m3
a = (1/6) * ((t*t*t) - (3*t*t2) + (2*t3))
b = (1/2) * ((t*t) - t2)
in (1/d) *** (a *** identity 4 - b *** m + t *** m2 - m3)
| otherwise = transpose $ vector $ map col' [0..(dim m - 1)] where
col' i = backsub u $ forwardsub l (idm <|> i) where
(l,u) = lu m
idm = identity $ dim m
-- graphics utilities
xaxis = vec3 1 0 0
yaxis = vec3 0 1 0
zaxis = vec3 0 0 1
rotationmat :: Vec3 -> Double -> Mat4
rotationmat axis angle = make44 $ cos r *** identity3 + sin r *** crossmat + (1 - cos r) *** tensor axis
where r = angle * pi / 180
crossmat = mat3 0 (-z) y
z 0 (-x)
(-y) x 0
where
x = V.x axis
y = V.y axis
z = V.z axis
make44 m = snocx (snoc m (vec3 0 0 0)) (vec4 0 0 0 1)
scalemat :: Double -> Double -> Double -> Mat4
scalemat x y z = mat4 x 0 0 0
0 y 0 0
0 0 z 0
0 0 0 1
translationmat :: Vec3 -> Mat4
translationmat v = mat4 1 0 0 (V.x v)
0 1 0 (V.y v)
0 0 1 (V.z v)
0 0 0 1
-- debugging helpers
instance (Show a) => Show (Matrix n m a) where
show m = concatMap showRow [0..(dimy m - 1)] where
showRow r = concatMap formatRowValueAtColumn [0..(dimx m - 1)] where
formatRowValueAtColumn c
| c == dimx m - 1 && r == dimy m - 1 = show (m |-> (r,c))
| c == dimx m - 1 = show (m |-> (r,c)) ++ "\n"
| otherwise = show (m |-> (r,c)) ++ "\t"
| davidyu/Slowpoke | hs/src/Math/matrix.hs | mit | 9,345 | 0 | 24 | 3,397 | 4,885 | 2,519 | 2,366 | -1 | -1 |
{-# LANGUAGE LambdaCase #-}
import Brainhack.Evaluator (emptyMachine, eval, runBrainState)
import Brainhack.Parser (parse)
import Control.Exception.Safe (SomeException)
import Control.Monad (forM)
import Data.Bifunctor (second)
import Data.List (nub)
import Data.Tuple.Extra ((&&&))
import NicoLang.Parser.Items (NicoToken(NicoToken))
import System.EasyFile (getDirectoryContents)
import System.IO.Silently (capture_)
import Test.Tasty (TestTree)
import Test.Tasty.HUnit ((@?=))
import Text.Printf (printf)
import qualified Data.Text as T
import qualified NicoLangTest.ParserTest as PT
import qualified Test.Tasty as Test (defaultMain, testGroup)
import qualified Test.Tasty.HUnit as Test (testCase, assertFailure)
main :: IO ()
main = do
inOutTests <- getInOutTests
Test.defaultMain $
Test.testGroup "nico-lang test" $
[ PT.test
, inOutTests
]
getInOutTests :: IO TestTree
getInOutTests = do
inOutPairs <- map inOutFiles . testNames . filter (`notElem` [".", ".."]) <$> getDirectoryContents "test/in-out"
inOutPairs' <- sequence . map (twiceMapM readFile) $ inOutPairs
-- `init` removes the line break of the tail
let inOutPairs'' = map (second init) inOutPairs'
resultPairs <- forM inOutPairs'' $ firstMapM $ \source -> do
case parse . NicoToken . T.pack $ source of
Left e -> return . Left $ "Parse error: " ++ show (e :: SomeException)
Right a -> return . Right =<< (capture_ . flip runBrainState emptyMachine $ eval a)
return $ Test.testGroup "in-out matching test" $
flip map resultPairs $ \case
(Left e, outData) -> Test.testCase (show outData) $ Test.assertFailure e
(Right inData, outData) -> Test.testCase (show outData) $ inData @?= outData
where
testNames :: [FilePath] -> [FilePath]
testNames = nub . map (takeWhile (/='.'))
inOutFiles :: FilePath -> (FilePath, FilePath)
inOutFiles = (printf "test/in-out/%s.nico") &&& (printf "test/in-out/%s.out")
twiceMapM :: Monad m => (a -> m b) -> (a, a) -> m (b, b)
twiceMapM f (x, y) = do
x' <- f x
y' <- f y
return (x', y')
firstMapM :: Monad m => (a -> m b) -> (a, x) -> m (b, x)
firstMapM f (x, y) = do
x' <- f x
return (x', y)
| aiya000/nico-lang | test/Spec.hs | mit | 2,199 | 0 | 19 | 419 | 803 | 434 | 369 | 51 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE TypeApplications #-}
{-# OPTIONS_GHC -O0 #-}
{-# OPTIONS_GHC -fomit-interface-pragmas #-}
module ZoomHub.Storage.PostgreSQL.GetRecent
( getRecent,
)
where
import Data.Binary (Word64)
import Squeal.PostgreSQL
( MonadPQ,
Only (Only),
SortExpression (Desc),
getRows,
limit,
orderBy,
param,
runQueryParams,
where_,
(!),
(&),
(./=),
)
import UnliftIO (MonadUnliftIO)
import ZoomHub.Storage.PostgreSQL.Internal
( contentImageRowToContent,
selectContentBy,
)
import ZoomHub.Storage.PostgreSQL.Schema (Schemas)
import ZoomHub.Types.Content (Content (..))
import ZoomHub.Types.ContentState (ContentState (Active))
getRecent :: (MonadUnliftIO m, MonadPQ Schemas m) => Word64 -> m [Content]
getRecent numItems = do
result <-
runQueryParams
( selectContentBy
( \table ->
table
& where_ ((#content ! #state) ./= param @1) -- TODO: Remove dummy clause
& orderBy [#content ! #initialized_at & Desc]
& limit numItems
)
)
(Only Active)
contentRows <- getRows result
return $ contentImageRowToContent <$> contentRows
| zoomhub/zoomhub | src/ZoomHub/Storage/PostgreSQL/GetRecent.hs | mit | 1,281 | 0 | 20 | 306 | 299 | 179 | 120 | 42 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SQLResultSetRowList
(js_item, item, js_getLength, getLength, SQLResultSetRowList,
castToSQLResultSetRowList, gTypeSQLResultSetRowList)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"item\"]($2)" js_item ::
SQLResultSetRowList -> Word -> IO JSVal
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLResultSetRowList.item Mozilla SQLResultSetRowList.item documentation>
item :: (MonadIO m) => SQLResultSetRowList -> Word -> m JSVal
item self index = liftIO (js_item (self) index)
foreign import javascript unsafe "$1[\"length\"]" js_getLength ::
SQLResultSetRowList -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLResultSetRowList.length Mozilla SQLResultSetRowList.length documentation>
getLength :: (MonadIO m) => SQLResultSetRowList -> m Word
getLength self = liftIO (js_getLength (self)) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SQLResultSetRowList.hs | mit | 1,715 | 14 | 8 | 199 | 434 | 269 | 165 | 26 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
import Prelude hiding (Functor, fmap, id)
class (Category c, Category d) => Functor c d t where
fmap :: c a b -> d (t a) (t b)
type Hask = (->)
instance Category Hask where
id x = x
(f . g) x = f (g x)
instance Functor Hask Hask [] where
fmap f [] = []
fmap f (x:xs) = f x : (fmap f xs)
| riwsky/wiwinwlh | src/functors.hs | mit | 379 | 4 | 10 | 92 | 183 | 96 | 87 | 12 | 0 |
module TemplateGen.TemplateContext (
TemplateContext(..)
, mkTemplateContext
) where
import qualified TemplateGen.Master as M
import qualified TemplateGen.PageContext as PC
import qualified TemplateGen.Settings as S
import qualified TemplateGen.Url as U
data TemplateContext = TemplateContext {
pageTitle :: PC.PageContext -> String,
pc :: PC.PageContext,
currentRoute :: Maybe U.Url,
appSettings :: M.Master -> S.Settings,
appCopyrightYear :: S.Settings -> String,
appCopyright :: S.Settings -> String,
appAnalytics :: S.Settings -> Maybe String,
master :: M.Master
}
mkTemplateContext :: S.Settings -> PC.PageContext -> TemplateContext
mkTemplateContext s pc = TemplateContext
PC.title -- pageTitle
pc
Nothing -- currentRoute
(\(M.Master s) -> s) -- appSettings
S.copyrightYear -- appCopyrightYear
S.copyright -- appCopyright
S.analytics -- appAnalytics
(M.Master s) -- master
| seahug/seattlehaskell-org-static | src/lib/TemplateGen/TemplateContext.hs | mit | 952 | 0 | 10 | 181 | 234 | 140 | 94 | 26 | 1 |
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Consensus.Log
-- Copyright : (c) Phil Hargett 2014
-- License : MIT (see LICENSE file)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- General 'Log' and 'State' typeclasses. Collectively, these implement a state machine, and the
-- Raft algorithm essential is one application of the
-- <https://www.cs.cornell.edu/fbs/publications/SMSurvey.pdf replicated state machine model>
-- for implementing a distributed system.
--
-----------------------------------------------------------------------------
module Data.Log (
Index,
Log(..),
defaultCommitEntries,
fetchLatestEntries,
State(..)
) where
-- local imports
-- external imports
import Prelude hiding (log)
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
{-|
A 'Log' of type @l@ is a sequence of entries of type @e@ such that
entries can be appended to the log starting at a particular 'Index' (and potentially
overwrite entries previously appended at the same index), fetched
from a particular 'Index', or committed up to a certain 'Index'. Once committed,
it is undefined whether attempting to fetch entries with an 'Index' < 'lastCommitted'
will succeed or throw an error, as some log implementations may throw away some
committed entries.
Each entry in the 'Log' defines an action that transforms a supplied initial 'State'
into a new 'State'. Commiting a 'Log', given some initial 'State', applies the action contained in
each entry in sequence (starting at a specified 'Index') to some state of type @s@,
producing a new 'State' after committing as many entries as possible.
Each log implementation may choose the monad @m@ in which they operate. Consumers of logs
should always use logs in a functional style: that is, after 'appendEntries' or 'commitEntries',
if the log returned from those functions is not fed into later functions, then results
may be unexpected. While the underlying log implementation may itself be pure, log
methods are wrapped in a monad to support those implementations that may not be--such
as a log whose entries are read from disk.
Implementing 'commitEntries' is optional, as a default implementation is supplied
that will invoke 'commitEntry' and 'applyEntry' as needed. Implementations that wish
to optimize commiting batches of entires may choose to override this method.
-}
class (Monad m,State s m e) => Log l m e s | l -> e,l -> s,l -> m where
{-|
'Index' of last committed entry in the 'Log'.
-}
lastCommitted :: l -> Index
{-|
'Index' of last appended entry (e.g., the end of the 'Log').
-}
lastAppended :: l -> Index
{-|
Append new log entries into the 'Log' after truncating the log
to remove all entries whose 'Index' is greater than or equal
to the specified 'Index', although no entries will be overwritten
if they are already committed.
-}
appendEntries :: l -> Index -> [e] -> m l
{-|
Retrieve a number of entries starting at the specified 'Index'
-}
fetchEntries :: l -> Index -> Int -> m [e]
{-|
For each uncommitted entry whose 'Index' is less than or equal to the
specified index, apply the entry to the supplied 'State' using 'applyEntry',
then mark the entry as committed in the 'Log'. Note that implementers are
free to commit no entries, some entries, or all entries as needed to handle
errors. However, the implementation should eventually commit all entries
if the calling application is well-behaved.
-}
commitEntries :: l -> Index -> s -> m (l,s)
commitEntries = defaultCommitEntries
{-|
Records a single entry in the log as committed; note that
this does not involve any external 'State' to which the entry
must be applied, as that is a separate operation.
-}
commitEntry :: l -> Index -> e -> m l
{-|
Snapshot the current `Log` and `State` to persistant storage
such that in the event of failure, both will be recovered from
this point.
-}
checkpoint :: l -> s -> m (l, s)
{-|
'Log's operate on 'State': that is, when committing, the log applies each
entry to the current 'State', and produces a new 'State'. Application of each
entry operates within a chosen 'Monad', so implementers are free to implement
'State' as needed (e.g., use 'IO', 'STM', etc.).
-}
class (Monad m) => State s m e where
canApplyEntry :: s -> e -> m Bool
applyEntry :: s -> e -> m s
{-|
An 'Index' is a logical offset into a 'Log'.
While the exact interpretation of the 'Index' is up to the 'Log'
implementation, by convention the first 'Index' in a log is @0@.
-}
type Index = Int
{-|
Default implementation of `commitEntries`, which fetches all uncommitted entries
with `fetchEntries`, then commits them one by one with `commitEntry` until either the
result of `canApplyEntry` is false, or all entries are committed.
-}
defaultCommitEntries :: (Monad m,State s m e, Log l m e s) => l -> Index -> s -> m (l,s)
defaultCommitEntries initialLog index initialState = do
let committed = lastCommitted initialLog
count = index - committed
if count > 0
then do
let nextCommitted = committed + 1
uncommitted <- fetchEntries initialLog nextCommitted count
commit initialLog initialState nextCommitted uncommitted
else return (initialLog,initialState)
where
commit oldLog oldState _ [] = do
return (oldLog,oldState)
commit oldLog oldState commitIndex (entry:rest) = do
can <- canApplyEntry oldState entry
if can
then do
newLog <- commitEntry oldLog commitIndex entry
newState <- applyEntry oldState entry
commit newLog newState (commitIndex + 1) rest
else return (oldLog,oldState)
{-|
Return all entries from the 'Log''s 'lastCommitted' time up to and
including the 'lastAppended' time.
-}
fetchLatestEntries :: (Monad m, Log l m e s) => l -> m (Index,[e])
fetchLatestEntries log = do
let commitTime = lastCommitted log
startTime = commitTime + 1
count = lastAppended log - lastCommitted log
entries <- fetchEntries log startTime count
return (commitTime,entries)
| hargettp/raft | src/Data/Log.hs | mit | 6,658 | 0 | 14 | 1,442 | 716 | 390 | 326 | 51 | 4 |
-- -------------------------------------------------------------------------------------
-- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
-- For email, run on linux (perl v5.8.5):
-- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
-- -------------------------------------------------------------------------------------
import System.Environment (getArgs)
import Data.Ord
import Data.List
import Data.Maybe
import Data.Ratio
type Level = Int
type Elfishness = Rational
type Problem = Elfishness
type Result = Maybe Level
maxLevel :: Level
maxLevel = 40
main :: IO ()
main = do
[file] <- getArgs
ip <- readFile file
writeFile ((takeWhile (/= '.') file) ++ ".out" ) (processInput ip)
writeOutput :: [(Int, Result)] -> [String]
writeOutput = map (\(i, r) -> ("Case #" ++ (show i) ++ ": " ++ (writeResult r)))
processInput :: String -> String
processInput = unlines . writeOutput . zip [1..] . map (solveProblem maxLevel). parseProblem . tail . lines
writeResult :: Result -> String
writeResult Nothing = "impossible"
writeResult (Just x) = show x
parseProblem :: [String] -> [Problem]
parseProblem [] = []
parseProblem (s:ss) = (n%d) : parseProblem ss
where n = read . takeWhile (/= '/') $ s
d = read . tail . dropWhile (/= '/') $ s
validElfness :: Elfishness -> Bool
validElfness elf =
let nume = numerator elf
deno = denominator elf
denomax = (2 ^ maxLevel)
in if denomax `mod` deno == 0 then True else False
solveProblem :: Level -> Problem -> Result
solveProblem lvl elf =
let nume = numerator elf
deno = denominator elf
newElf = (2 * nume) % deno
in if validElfness elf == False
then Nothing
else if lvl <= 0
then Nothing
else if nume * 2 >= deno
then Just (maxLevel - lvl + 1 )
else solveProblem (lvl - 1) newElf
| cbrghostrider/Hacking | codeJam/2014/elf/greedyElf.hs | mit | 1,999 | 1 | 13 | 502 | 602 | 324 | 278 | 46 | 4 |
{-# LANGUAGE NoMonomorphismRestriction #-}
import Diagrams.Prelude
import Diagrams.Backend.SVG.CmdLine
c1 = circle 0.5 # lw none # showOrigin
c2 = circle 1 # fc orange
c3 = circle 0.5 # fc steelblue # showOrigin
diagram :: Diagram B
diagram = (c1 ||| c2) === c3
main = mainWith $ frame 0.1 diagram
| jeffreyrosenbluth/NYC-meetup | meetup/Atop5.hs | mit | 304 | 0 | 7 | 57 | 105 | 54 | 51 | 9 | 1 |
{-# LANGUAGE TypeOperators #-}
module Language.LSP.Server
( module Language.LSP.Server.Control
, VFSData(..)
, ServerDefinition(..)
-- * Handlers
, Handlers(..)
, Handler
, transmuteHandlers
, mapHandlers
, notificationHandler
, requestHandler
, ClientMessageHandler(..)
, Options(..)
, defaultOptions
-- * LspT and LspM
, LspT(..)
, LspM
, MonadLsp(..)
, runLspT
, LanguageContextEnv(..)
, type (<~>)(..)
, getClientCapabilities
, getConfig
, getRootPath
, getWorkspaceFolders
, sendRequest
, sendNotification
-- * VFS
, getVirtualFile
, getVirtualFiles
, persistVirtualFile
, getVersionedTextDoc
, reverseFileMap
-- * Diagnostics
, publishDiagnostics
, flushDiagnosticsBySource
-- * Progress
, withProgress
, withIndefiniteProgress
, ProgressAmount(..)
, ProgressCancellable(..)
, ProgressCancelledException
-- * Dynamic registration
, registerCapability
, unregisterCapability
, RegistrationToken
, setupLogger
, reverseSortEdit
) where
import Language.LSP.Server.Control
import Language.LSP.Server.Core
| alanz/haskell-lsp | lsp/src/Language/LSP/Server.hs | mit | 1,114 | 0 | 5 | 224 | 206 | 145 | 61 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
module Shaders where
import Data.FileEmbed
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Search as BSS
import Graphics.Rendering.OpenGL.GL.Shaders.ShaderObjects
passthroughVS, defaultVS, planetVS, planetTCS, planetTES, planetFS, crossGS, vectorGS, defaultFS :: (ShaderType, BS.ByteString)
passthroughVS = (VertexShader, $(embedFile "src/shader/passthrough.vert"))
defaultVS = (VertexShader, $(embedFile "src/shader/default.vert"))
planetVS = (VertexShader, $(embedFile "src/shader/planet.vert"))
planetTCS = (TessControlShader, $(embedFile "src/shader/planet.tctrl"))
planetTES = (TessEvaluationShader, $( [| BL.toStrict $ BSS.replace (BC.pack "#insert noise3D") $(embedFile "src/shader/glsl-noise/src/noise3D.glsl") $(embedFile "src/shader/planet.teval") |] ))
planetFS = (FragmentShader, $(embedFile "src/shader/planet.frag"))
crossGS = (GeometryShader, $(embedFile "src/shader/cross.geom"))
vectorGS = (GeometryShader, $(embedFile "src/shader/vector.geom"))
defaultFS = (FragmentShader, $(embedFile "src/shader/default.frag"))
| hesiod/xenocrat | src/exec/Shaders.hs | gpl-3.0 | 1,181 | 0 | 8 | 103 | 245 | 157 | 88 | 18 | 1 |
{-# language LambdaCase, OverloadedStrings, ScopedTypeVariables #-}
module HMail.Brick.MailBoxView (
handleEvent
, draw
, updateMailBoxView
) where
import HMail.Types
import HMail.ImapMail
import HMail.Header
import HMail.Brick.EventH
import HMail.Brick.Widgets
import HMail.Brick.Util
import HMail.Brick.ViewSwitching
import HMail.Brick.Banner
import Network.HaskellNet.IMAP.Types
import Graphics.Vty.Input.Events
import Brick.Types
import Brick.Widgets.Core
import Brick.Widgets.List
import HMail.Util
import Control.Lens
import Control.Monad
import Control.Monad.Extra
import Control.Monad.Base
import Control.Monad.RWS
import Data.Maybe
import Data.Bool
import qualified Data.Text as T
import qualified Data.Foldable as F
import qualified Data.Vector as V
import qualified Data.Map.Lazy as M
handleEvent :: BrickEv e -> EventH MailBoxView ()
handleEvent = \case
VtyEvent ev -> do
mblst' <- view boxViewList >>= \case
Just lst -> do
lst' <- liftBase $ handleListEvent ev lst
v <- ask
tellView $ IsMailBoxView (set boxViewList (Just lst') v)
pure $ Just lst'
Nothing -> pure Nothing
case ev of
EvKey key mods -> handleKeyEvent mblst' key mods
_ -> pure ()
_ -> pure ()
draw :: MailBoxView -> HMailState -> Widget ResName
draw v st = case v ^. boxViewList of
Just lst ->
-- padTop (Pad 2)
banner genericHelp
<=> renderList renderEntry True lst
Nothing -> loadingWidget
where
renderEntry hasFocus (meta,hdr) =
withAttr
( attrFocused hasFocus
<> attrNew (isNew meta) )
. hBox . map (txt . (<>" ")) . join
$ catMaybes
[ composeId <$> (meta ^? metaUid)
, composeFlags <$> (meta ^? metaFlags)
, composeHeader hdr
, composeSize <$> (meta ^? metaSize) ]
attrFocused = bool mempty $ "focused"
attrNew = bool mempty $ "new"
composeHeader :: Header -> Maybe [T.Text]
composeHeader hdr =
let f name = fromMaybe "" (hdr ^. headerMap . at name)
in Just $ map f entries
composeSize :: Int -> [T.Text]
composeSize s = pure $ "(" <> fmt s <> ")"
composeId :: UID -> [T.Text]
composeId = pure . showT
composeFlags :: [Flag] -> [T.Text]
composeFlags = (pure .) . F.foldMap $ \case
Seen -> ""
Answered -> "r"
Flagged -> "f"
Deleted -> "D"
Draft -> "d"
Recent -> ""
Keyword kw -> "<" <> T.pack kw <> ">"
entries = ["Date","From","Subject"]
isNew :: MailMeta -> Bool
isNew meta = flip any (meta ^. metaFlags) $ \case
Seen -> False
_ -> True
fmt :: Int -> T.Text
fmt n
| n < 0 = "bogus size"
| True = let (n',s) = foldr f (n,"") suffixes in showT n' <> s
where
f s (k,_) = if k < base then (k,s) else (div k base,s)
base = 10^3
suffixes = ["K","M","G","T"]
handleKeyEvent :: Maybe (List ResName (MailMeta,Header))
-> Key -> [Modifier] -> EventH MailBoxView ()
handleKeyEvent mblst key mods = case key of
KChar 'y' -> enterBoxesView
KEnter -> whenJust mblst $ \lst ->
whenJust ( getSelected lst ) $ \(meta,_) -> do
mbox <- view boxViewName
boxes <- use mailBoxes
flip whenJust (enterMailView mbox) $ do
box <- boxes ^. at mbox
uid <- meta ^? metaUid
box ^. mails . at uid -- check that mail exists
pure uid
KChar 'r' -> do
mbox <- view boxViewName
sendCommand $ FetchMetasAndHeaders mbox
_ -> pure ()
updateMailBoxView :: EventH MailBoxView ()
updateMailBoxView = do
name <- view boxViewName
lst <- newList . vec name <$> get
v <- ask
tellView $ IsMailBoxView (set boxViewList (Just lst) v)
where
newList xs = list ResMailBoxList xs 1
vec name st = V.fromList . map extractElem . M.elems
$ st ^. mailBoxes . ix name . mails
extractElem mail = (mail ^. immMeta,mail ^. immHeader)
| xaverdh/hmail | HMail/Brick/MailBoxView.hs | gpl-3.0 | 3,910 | 0 | 22 | 1,024 | 1,384 | 715 | 669 | -1 | -1 |
module Main where
import ClassyPrelude
import Reviewer.Entity
import Reviewer.EntityType
import Reviewer.Database
makeEntity :: EntityType -> Text -> Entity
makeEntity goodOrBad text = Entity {
_entityText = text
, _entityType = goodOrBad
, _entityEncounters = []
}
toEntities :: (MonadIO m, Functor m) => FilePath -> EntityType -> m [Entity]
toEntities f goodOrBad = do
ls <- lines <$> readFile f
return (map (makeEntity goodOrBad) ls)
main :: IO ()
main = do
goodEntities <- toEntities "good.txt" EntityGood
badEntities <- toEntities "bad.txt" EntityBad
writeDatabase "/tmp/output.db" (goodEntities <> badEntities)
| pmiddend/reviewer | src/Reviewer/Importer.hs | gpl-3.0 | 641 | 0 | 11 | 111 | 199 | 103 | 96 | 19 | 1 |
module Language.PySMEIL.Typing
( typeOf
, sizeOf
, sign
, Signedness(..))
where
import Language.PySMEIL.AST
-- VERY simple for now. Shouldn't be hard to do things a little bit better
-- e.g.by unifying integer types of different sizes to the biggest of the two
unify :: DType -> DType -> DType
unify a b
| a == b = a
| a == AnyType && b /= AnyType = b
| a /= AnyType && b == AnyType = a
| otherwise = AnyType
data Signedness = IsSigned | IsUnsigned
class TypeOf a where
typeOf :: a -> DType
instance TypeOf Variable where
typeOf (ParamVar t _) = t
typeOf (ConstVar t _) = t
typeOf (BusVar t _ _) = t
typeOf (NamedVar t _ ) = t
instance TypeOf PrimVal where
typeOf (Num n) = typeOf n
typeOf (Bool b) = typeOf b
typeOf EmptyVal = AnyType
instance TypeOf SMENum where
typeOf (SMEInt _) = IntType 32
typeOf (SMEFloat _) = FloatType 32
instance TypeOf SMEBool where
typeOf SMETrue = BoolType
typeOf SMEFalse = BoolType
instance TypeOf Expr where
typeOf BinOp { left = l
, right = r } = unify (intToAny l) (intToAny r)
where
intToAny (Prim (Num (SMEInt _))) = AnyType
intToAny a = typeOf a
typeOf UnOp { unOpVal = v } = typeOf v
typeOf (Prim p) = typeOf p
typeOf (Paren e) = typeOf e
typeOf (Var v) = typeOf v
typeOf NopExpr = AnyType
sizeOf :: DType -> Int
sizeOf (IntType s) = s
sizeOf (UIntType s) = s
sizeOf _ = 0
sign :: DType -> Signedness
sign (IntType _) = IsSigned
sign (UIntType _) = IsUnsigned
sign BoolType = IsUnsigned
sign (FloatType _) = IsSigned
sign AnyType = IsSigned
| truls/almique | src/Language/PySMEIL/Typing.hs | gpl-3.0 | 1,639 | 0 | 14 | 447 | 613 | 310 | 303 | 50 | 1 |
import Control.Monad
import System.IO
import System.Environment
import ParserEvaluator
flushStr :: String -> IO ()
flushStr str = putStr str >> hFlush stdout
readPrompt :: String -> IO String
readPrompt prompt = flushStr prompt >> getLine
evalAndPrint :: Env -> String -> IO ()
evalAndPrint env expr = evalString env expr >>= putStrLn
evalString :: Env -> String -> IO String
evalString env expr = runIOThrows $ liftM show $ (liftThrows $ readExpr expr) >>= eval env
until_ :: Monad m => (a -> Bool) -> m a -> (a -> m ()) -> m ()
until_ pred prompt action = do
result <- prompt
if pred result
then return ()
else action result >> until_ pred prompt action
runOne :: [String] -> IO ()
runOne args = do
env <- primitiveBindings >>= flip bindVars [("args", List $ map String $ drop 1 args)]
(runIOThrows $ liftM show $ eval env (List [Atom "load", String (args !! 0)]))
>>= hPutStrLn stderr
runRepl :: IO ()
runRepl = do
env <- primitiveBindings
runIOThrows $ liftM show $ eval env (List [Atom "load", String "stdlib.scm"])
until_ (== "quit") (readPrompt "λ>>> ") . evalAndPrint $ env
main :: IO ()
main = do
args <- getArgs
if null args
then runRepl
else runOne $ args
| GallagherCommaJack/scheming-machine | REPL.hs | gpl-3.0 | 1,196 | 8 | 16 | 239 | 525 | 256 | 269 | 34 | 2 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
module Lamdu.Builtins
( eval
) where
import Control.Lens.Operators
import Control.Monad (join, void, when)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Map.Utils (matchKeys)
import qualified Lamdu.Builtins.Anchors as Builtins
import qualified Lamdu.Data.Definition as Def
import Lamdu.Eval.Val (EvalResult, Val(..), EvalError(..))
import Lamdu.Expr.Type (Tag)
import qualified Lamdu.Expr.Type as T
import qualified Lamdu.Expr.Val as V
import Prelude.Compat
flatRecord :: EvalResult pl -> Either EvalError (Map Tag (EvalResult pl))
flatRecord (Left err) = Left err
flatRecord (Right HRecEmpty) = Right Map.empty
flatRecord (Right (HRecExtend (V.RecExtend t v rest))) =
flatRecord rest <&> Map.insert t v
flatRecord _ = error "Param record is not a record"
extractRecordParams ::
(Traversable t, Show (t Tag)) =>
t Tag -> EvalResult pl -> Either EvalError (t (EvalResult pl))
extractRecordParams expectedTags val =
do
paramsMap <- flatRecord val
case matchKeys expectedTags paramsMap of
Nothing ->
"Builtin expected params: " ++ show expectedTags ++ " got: " ++
show (void val) & EvalTypeError & Left
Just x -> Right x
data V2 a = V2 a a deriving (Show, Functor, Foldable, Traversable)
data V3 a = V3 a a a deriving (Show, Functor, Foldable, Traversable)
extractInfixParams :: EvalResult pl -> Either EvalError (V2 (EvalResult pl))
extractInfixParams =
extractRecordParams (V2 Builtins.infixlTag Builtins.infixrTag)
class GuestType t where
toGuestVal :: t -> Val pl
fromGuestVal :: Val pl -> Either EvalError t
toGuest :: GuestType t => t -> EvalResult pl
toGuest = Right . toGuestVal
fromGuest :: GuestType t => EvalResult pl -> Either EvalError t
fromGuest = (>>= fromGuestVal)
instance GuestType Integer where
toGuestVal = HInteger
fromGuestVal (HInteger x) = Right x
fromGuestVal x = error $ "expected int, got " ++ show (void x)
instance GuestType Bool where
toGuestVal b =
record [] & V.Inject (tag b) & HInject
where
tag True = Builtins.trueTag
tag False = Builtins.falseTag
fromGuestVal v =
case v of
HInject (V.Inject boolTag _)
| boolTag == Builtins.trueTag -> Right True
| boolTag == Builtins.falseTag -> Right False
_ -> "Expected bool, got: " ++ show (void v) & EvalTypeError & Left
record :: [(T.Tag, EvalResult pl)] -> EvalResult pl
record [] = Right HRecEmpty
record ((tag, val) : xs) =
record xs & V.RecExtend tag val & HRecExtend & Right
builtin1 :: (GuestType a, GuestType b) => (a -> b) -> EvalResult pl -> EvalResult pl
builtin1 f val = fromGuest val <&> f >>= toGuest
builtin2Infix ::
( GuestType a
, GuestType b
, GuestType c ) =>
(a -> b -> c) -> EvalResult pl -> EvalResult pl
builtin2Infix f thunkId =
do
V2 x y <- extractInfixParams thunkId
f <$> fromGuest x <*> fromGuest y >>= toGuest
eq :: EvalResult t -> EvalResult t -> Either EvalError Bool
eq x y = eqVal <$> x <*> y & join
eqVal :: Val t -> Val t -> Either EvalError Bool
eqVal HFunc {} _ = EvalTodoError "Eq of func" & Left
eqVal HAbsurd {} _ = EvalTodoError "Eq of absurd" & Left
eqVal HCase {} _ = EvalTodoError "Eq of case" & Left
eqVal HBuiltin {} _ = EvalTodoError "Eq of builtin" & Left
eqVal (HInteger x) (HInteger y) = x == y & Right
eqVal (HRecExtend x) (HRecExtend y) =
do
fx <- HRecExtend x & Right & flatRecord
fy <- HRecExtend y & Right & flatRecord
when (Map.keysSet fx /= Map.keysSet fy) $
"Comparing different record types: " ++
show (Map.keys fx) ++ " vs. " ++
show (Map.keys fy)
& EvalTypeError & Left
Map.intersectionWith eq fx fy
& Map.elems & sequence <&> and
eqVal HRecEmpty HRecEmpty = Right True
eqVal (HInject (V.Inject xf xv)) (HInject (V.Inject yf yv))
| xf == yf = eq xv yv
| otherwise = Right False
eqVal _ _ = Right False -- assume type checking ruled out errorenous equalities already
builtinEqH :: GuestType t => (Bool -> t) -> EvalResult pl -> EvalResult pl
builtinEqH f val =
do
V2 x y <- extractInfixParams val
eq x y <&> f >>= toGuest
builtinEq :: EvalResult pl -> EvalResult pl
builtinEq = builtinEqH id
builtinNotEq :: EvalResult pl -> EvalResult pl
builtinNotEq = builtinEqH not
intArg :: (Integer -> a) -> Integer -> a
intArg = id
eval :: Def.FFIName -> EvalResult pl -> EvalResult pl
eval name =
case name of
Def.FFIName ["Prelude"] "==" -> builtinEq
Def.FFIName ["Prelude"] "/=" -> builtinNotEq
Def.FFIName ["Prelude"] "<" -> builtin2Infix $ intArg (<)
Def.FFIName ["Prelude"] "<=" -> builtin2Infix $ intArg (<=)
Def.FFIName ["Prelude"] ">" -> builtin2Infix $ intArg (>)
Def.FFIName ["Prelude"] ">=" -> builtin2Infix $ intArg (>=)
Def.FFIName ["Prelude"] "*" -> builtin2Infix $ intArg (*)
Def.FFIName ["Prelude"] "+" -> builtin2Infix $ intArg (+)
Def.FFIName ["Prelude"] "-" -> builtin2Infix $ intArg (-)
Def.FFIName ["Prelude"] "div" -> builtin2Infix $ intArg div
Def.FFIName ["Prelude"] "mod" -> builtin2Infix $ intArg mod
Def.FFIName ["Prelude"] "negate" -> builtin1 $ intArg negate
Def.FFIName ["Prelude"] "sqrt" -> builtin1 $ intArg ((floor :: Double -> Integer) . sqrt . fromIntegral)
_ -> error $ show name ++ " not yet supported"
| rvion/lamdu | Lamdu/Builtins.hs | gpl-3.0 | 5,693 | 0 | 17 | 1,436 | 2,012 | 1,007 | 1,005 | 126 | 14 |
{-# 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.PubSub.Projects.Subscriptions.Pull
-- 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)
--
-- Pulls messages from the server. Returns an empty list if there are no
-- messages available in the backlog. The server may return \`UNAVAILABLE\`
-- if there are too many concurrent pull requests pending for the given
-- subscription.
--
-- /See:/ <https://cloud.google.com/pubsub/docs Google Cloud Pub/Sub API Reference> for @pubsub.projects.subscriptions.pull@.
module Network.Google.Resource.PubSub.Projects.Subscriptions.Pull
(
-- * REST Resource
ProjectsSubscriptionsPullResource
-- * Creating a Request
, projectsSubscriptionsPull
, ProjectsSubscriptionsPull
-- * Request Lenses
, pspXgafv
, pspUploadProtocol
, pspPp
, pspAccessToken
, pspUploadType
, pspPayload
, pspBearerToken
, pspSubscription
, pspCallback
) where
import Network.Google.Prelude
import Network.Google.PubSub.Types
-- | A resource alias for @pubsub.projects.subscriptions.pull@ method which the
-- 'ProjectsSubscriptionsPull' request conforms to.
type ProjectsSubscriptionsPullResource =
"v1" :>
CaptureMode "subscription" "pull" Text :>
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] PullRequest :>
Post '[JSON] PullResponse
-- | Pulls messages from the server. Returns an empty list if there are no
-- messages available in the backlog. The server may return \`UNAVAILABLE\`
-- if there are too many concurrent pull requests pending for the given
-- subscription.
--
-- /See:/ 'projectsSubscriptionsPull' smart constructor.
data ProjectsSubscriptionsPull = ProjectsSubscriptionsPull'
{ _pspXgafv :: !(Maybe Xgafv)
, _pspUploadProtocol :: !(Maybe Text)
, _pspPp :: !Bool
, _pspAccessToken :: !(Maybe Text)
, _pspUploadType :: !(Maybe Text)
, _pspPayload :: !PullRequest
, _pspBearerToken :: !(Maybe Text)
, _pspSubscription :: !Text
, _pspCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ProjectsSubscriptionsPull' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pspXgafv'
--
-- * 'pspUploadProtocol'
--
-- * 'pspPp'
--
-- * 'pspAccessToken'
--
-- * 'pspUploadType'
--
-- * 'pspPayload'
--
-- * 'pspBearerToken'
--
-- * 'pspSubscription'
--
-- * 'pspCallback'
projectsSubscriptionsPull
:: PullRequest -- ^ 'pspPayload'
-> Text -- ^ 'pspSubscription'
-> ProjectsSubscriptionsPull
projectsSubscriptionsPull pPspPayload_ pPspSubscription_ =
ProjectsSubscriptionsPull'
{ _pspXgafv = Nothing
, _pspUploadProtocol = Nothing
, _pspPp = True
, _pspAccessToken = Nothing
, _pspUploadType = Nothing
, _pspPayload = pPspPayload_
, _pspBearerToken = Nothing
, _pspSubscription = pPspSubscription_
, _pspCallback = Nothing
}
-- | V1 error format.
pspXgafv :: Lens' ProjectsSubscriptionsPull (Maybe Xgafv)
pspXgafv = lens _pspXgafv (\ s a -> s{_pspXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pspUploadProtocol :: Lens' ProjectsSubscriptionsPull (Maybe Text)
pspUploadProtocol
= lens _pspUploadProtocol
(\ s a -> s{_pspUploadProtocol = a})
-- | Pretty-print response.
pspPp :: Lens' ProjectsSubscriptionsPull Bool
pspPp = lens _pspPp (\ s a -> s{_pspPp = a})
-- | OAuth access token.
pspAccessToken :: Lens' ProjectsSubscriptionsPull (Maybe Text)
pspAccessToken
= lens _pspAccessToken
(\ s a -> s{_pspAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pspUploadType :: Lens' ProjectsSubscriptionsPull (Maybe Text)
pspUploadType
= lens _pspUploadType
(\ s a -> s{_pspUploadType = a})
-- | Multipart request metadata.
pspPayload :: Lens' ProjectsSubscriptionsPull PullRequest
pspPayload
= lens _pspPayload (\ s a -> s{_pspPayload = a})
-- | OAuth bearer token.
pspBearerToken :: Lens' ProjectsSubscriptionsPull (Maybe Text)
pspBearerToken
= lens _pspBearerToken
(\ s a -> s{_pspBearerToken = a})
-- | The subscription from which messages should be pulled. Format is
-- \`projects\/{project}\/subscriptions\/{sub}\`.
pspSubscription :: Lens' ProjectsSubscriptionsPull Text
pspSubscription
= lens _pspSubscription
(\ s a -> s{_pspSubscription = a})
-- | JSONP
pspCallback :: Lens' ProjectsSubscriptionsPull (Maybe Text)
pspCallback
= lens _pspCallback (\ s a -> s{_pspCallback = a})
instance GoogleRequest ProjectsSubscriptionsPull
where
type Rs ProjectsSubscriptionsPull = PullResponse
type Scopes ProjectsSubscriptionsPull =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/pubsub"]
requestClient ProjectsSubscriptionsPull'{..}
= go _pspSubscription _pspXgafv _pspUploadProtocol
(Just _pspPp)
_pspAccessToken
_pspUploadType
_pspBearerToken
_pspCallback
(Just AltJSON)
_pspPayload
pubSubService
where go
= buildClient
(Proxy :: Proxy ProjectsSubscriptionsPullResource)
mempty
| rueshyna/gogol | gogol-pubsub/gen/Network/Google/Resource/PubSub/Projects/Subscriptions/Pull.hs | mpl-2.0 | 6,411 | 0 | 18 | 1,508 | 941 | 549 | 392 | 134 | 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.CloudSearch.Stats.Index.Datasources.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 indexed item statistics for a single data source. **Note:** This
-- API requires a standard end user account to execute.
--
-- /See:/ <https://developers.google.com/cloud-search/docs/guides/ Cloud Search API Reference> for @cloudsearch.stats.index.datasources.get@.
module Network.Google.Resource.CloudSearch.Stats.Index.Datasources.Get
(
-- * REST Resource
StatsIndexDatasourcesGetResource
-- * Creating a Request
, statsIndexDatasourcesGet
, StatsIndexDatasourcesGet
-- * Request Lenses
, sidgFromDateMonth
, sidgXgafv
, sidgUploadProtocol
, sidgFromDateDay
, sidgAccessToken
, sidgUploadType
, sidgFromDateYear
, sidgName
, sidgToDateDay
, sidgToDateYear
, sidgToDateMonth
, sidgCallback
) where
import Network.Google.CloudSearch.Types
import Network.Google.Prelude
-- | A resource alias for @cloudsearch.stats.index.datasources.get@ method which the
-- 'StatsIndexDatasourcesGet' request conforms to.
type StatsIndexDatasourcesGetResource =
"v1" :>
"stats" :>
"index" :>
Capture "name" Text :>
QueryParam "fromDate.month" (Textual Int32) :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "fromDate.day" (Textual Int32) :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "fromDate.year" (Textual Int32) :>
QueryParam "toDate.day" (Textual Int32) :>
QueryParam "toDate.year" (Textual Int32) :>
QueryParam "toDate.month" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] GetDataSourceIndexStatsResponse
-- | Gets indexed item statistics for a single data source. **Note:** This
-- API requires a standard end user account to execute.
--
-- /See:/ 'statsIndexDatasourcesGet' smart constructor.
data StatsIndexDatasourcesGet =
StatsIndexDatasourcesGet'
{ _sidgFromDateMonth :: !(Maybe (Textual Int32))
, _sidgXgafv :: !(Maybe Xgafv)
, _sidgUploadProtocol :: !(Maybe Text)
, _sidgFromDateDay :: !(Maybe (Textual Int32))
, _sidgAccessToken :: !(Maybe Text)
, _sidgUploadType :: !(Maybe Text)
, _sidgFromDateYear :: !(Maybe (Textual Int32))
, _sidgName :: !Text
, _sidgToDateDay :: !(Maybe (Textual Int32))
, _sidgToDateYear :: !(Maybe (Textual Int32))
, _sidgToDateMonth :: !(Maybe (Textual Int32))
, _sidgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'StatsIndexDatasourcesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sidgFromDateMonth'
--
-- * 'sidgXgafv'
--
-- * 'sidgUploadProtocol'
--
-- * 'sidgFromDateDay'
--
-- * 'sidgAccessToken'
--
-- * 'sidgUploadType'
--
-- * 'sidgFromDateYear'
--
-- * 'sidgName'
--
-- * 'sidgToDateDay'
--
-- * 'sidgToDateYear'
--
-- * 'sidgToDateMonth'
--
-- * 'sidgCallback'
statsIndexDatasourcesGet
:: Text -- ^ 'sidgName'
-> StatsIndexDatasourcesGet
statsIndexDatasourcesGet pSidgName_ =
StatsIndexDatasourcesGet'
{ _sidgFromDateMonth = Nothing
, _sidgXgafv = Nothing
, _sidgUploadProtocol = Nothing
, _sidgFromDateDay = Nothing
, _sidgAccessToken = Nothing
, _sidgUploadType = Nothing
, _sidgFromDateYear = Nothing
, _sidgName = pSidgName_
, _sidgToDateDay = Nothing
, _sidgToDateYear = Nothing
, _sidgToDateMonth = Nothing
, _sidgCallback = Nothing
}
-- | Month of date. Must be from 1 to 12.
sidgFromDateMonth :: Lens' StatsIndexDatasourcesGet (Maybe Int32)
sidgFromDateMonth
= lens _sidgFromDateMonth
(\ s a -> s{_sidgFromDateMonth = a})
. mapping _Coerce
-- | V1 error format.
sidgXgafv :: Lens' StatsIndexDatasourcesGet (Maybe Xgafv)
sidgXgafv
= lens _sidgXgafv (\ s a -> s{_sidgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
sidgUploadProtocol :: Lens' StatsIndexDatasourcesGet (Maybe Text)
sidgUploadProtocol
= lens _sidgUploadProtocol
(\ s a -> s{_sidgUploadProtocol = a})
-- | Day of month. Must be from 1 to 31 and valid for the year and month.
sidgFromDateDay :: Lens' StatsIndexDatasourcesGet (Maybe Int32)
sidgFromDateDay
= lens _sidgFromDateDay
(\ s a -> s{_sidgFromDateDay = a})
. mapping _Coerce
-- | OAuth access token.
sidgAccessToken :: Lens' StatsIndexDatasourcesGet (Maybe Text)
sidgAccessToken
= lens _sidgAccessToken
(\ s a -> s{_sidgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
sidgUploadType :: Lens' StatsIndexDatasourcesGet (Maybe Text)
sidgUploadType
= lens _sidgUploadType
(\ s a -> s{_sidgUploadType = a})
-- | Year of date. Must be from 1 to 9999.
sidgFromDateYear :: Lens' StatsIndexDatasourcesGet (Maybe Int32)
sidgFromDateYear
= lens _sidgFromDateYear
(\ s a -> s{_sidgFromDateYear = a})
. mapping _Coerce
-- | The resource id of the data source to retrieve statistics for, in the
-- following format: \"datasources\/{source_id}\"
sidgName :: Lens' StatsIndexDatasourcesGet Text
sidgName = lens _sidgName (\ s a -> s{_sidgName = a})
-- | Day of month. Must be from 1 to 31 and valid for the year and month.
sidgToDateDay :: Lens' StatsIndexDatasourcesGet (Maybe Int32)
sidgToDateDay
= lens _sidgToDateDay
(\ s a -> s{_sidgToDateDay = a})
. mapping _Coerce
-- | Year of date. Must be from 1 to 9999.
sidgToDateYear :: Lens' StatsIndexDatasourcesGet (Maybe Int32)
sidgToDateYear
= lens _sidgToDateYear
(\ s a -> s{_sidgToDateYear = a})
. mapping _Coerce
-- | Month of date. Must be from 1 to 12.
sidgToDateMonth :: Lens' StatsIndexDatasourcesGet (Maybe Int32)
sidgToDateMonth
= lens _sidgToDateMonth
(\ s a -> s{_sidgToDateMonth = a})
. mapping _Coerce
-- | JSONP
sidgCallback :: Lens' StatsIndexDatasourcesGet (Maybe Text)
sidgCallback
= lens _sidgCallback (\ s a -> s{_sidgCallback = a})
instance GoogleRequest StatsIndexDatasourcesGet where
type Rs StatsIndexDatasourcesGet =
GetDataSourceIndexStatsResponse
type Scopes StatsIndexDatasourcesGet =
'["https://www.googleapis.com/auth/cloud_search",
"https://www.googleapis.com/auth/cloud_search.stats",
"https://www.googleapis.com/auth/cloud_search.stats.indexing"]
requestClient StatsIndexDatasourcesGet'{..}
= go _sidgName _sidgFromDateMonth _sidgXgafv
_sidgUploadProtocol
_sidgFromDateDay
_sidgAccessToken
_sidgUploadType
_sidgFromDateYear
_sidgToDateDay
_sidgToDateYear
_sidgToDateMonth
_sidgCallback
(Just AltJSON)
cloudSearchService
where go
= buildClient
(Proxy :: Proxy StatsIndexDatasourcesGetResource)
mempty
| brendanhay/gogol | gogol-cloudsearch/gen/Network/Google/Resource/CloudSearch/Stats/Index/Datasources/Get.hs | mpl-2.0 | 8,049 | 0 | 23 | 1,955 | 1,307 | 742 | 565 | 179 | 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.FusionTables.Column.Update
-- 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)
--
-- Updates the name or type of an existing column.
--
-- /See:/ <https://developers.google.com/fusiontables Fusion Tables API Reference> for @fusiontables.column.update@.
module Network.Google.Resource.FusionTables.Column.Update
(
-- * REST Resource
ColumnUpdateResource
-- * Creating a Request
, columnUpdate
, ColumnUpdate
-- * Request Lenses
, cuPayload
, cuTableId
, cuColumnId
) where
import Network.Google.FusionTables.Types
import Network.Google.Prelude
-- | A resource alias for @fusiontables.column.update@ method which the
-- 'ColumnUpdate' request conforms to.
type ColumnUpdateResource =
"fusiontables" :>
"v2" :>
"tables" :>
Capture "tableId" Text :>
"columns" :>
Capture "columnId" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Column :> Put '[JSON] Column
-- | Updates the name or type of an existing column.
--
-- /See:/ 'columnUpdate' smart constructor.
data ColumnUpdate =
ColumnUpdate'
{ _cuPayload :: !Column
, _cuTableId :: !Text
, _cuColumnId :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ColumnUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cuPayload'
--
-- * 'cuTableId'
--
-- * 'cuColumnId'
columnUpdate
:: Column -- ^ 'cuPayload'
-> Text -- ^ 'cuTableId'
-> Text -- ^ 'cuColumnId'
-> ColumnUpdate
columnUpdate pCuPayload_ pCuTableId_ pCuColumnId_ =
ColumnUpdate'
{ _cuPayload = pCuPayload_
, _cuTableId = pCuTableId_
, _cuColumnId = pCuColumnId_
}
-- | Multipart request metadata.
cuPayload :: Lens' ColumnUpdate Column
cuPayload
= lens _cuPayload (\ s a -> s{_cuPayload = a})
-- | Table for which the column is being updated.
cuTableId :: Lens' ColumnUpdate Text
cuTableId
= lens _cuTableId (\ s a -> s{_cuTableId = a})
-- | Name or identifier for the column that is being updated.
cuColumnId :: Lens' ColumnUpdate Text
cuColumnId
= lens _cuColumnId (\ s a -> s{_cuColumnId = a})
instance GoogleRequest ColumnUpdate where
type Rs ColumnUpdate = Column
type Scopes ColumnUpdate =
'["https://www.googleapis.com/auth/fusiontables"]
requestClient ColumnUpdate'{..}
= go _cuTableId _cuColumnId (Just AltJSON) _cuPayload
fusionTablesService
where go
= buildClient (Proxy :: Proxy ColumnUpdateResource)
mempty
| brendanhay/gogol | gogol-fusiontables/gen/Network/Google/Resource/FusionTables/Column/Update.hs | mpl-2.0 | 3,363 | 0 | 15 | 791 | 461 | 275 | 186 | 72 | 1 |
{-
Copyright (C) 2011, 2012 Jeroen Ketema
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
-- This module defines a "dynamic" reduction type.
--
-- Using make_dynamic, any reduction of length at most omega can be converted
-- into a reduction of the type defined here.
module DynamicReduction (
DynamicSigma(DynamicFun),
DynamicVar(DynamicVar),
DynamicSystem,
DynamicReduction,
dynamicSystem,
makeDynamic
) where
import SignatureAndVariables
import Term
import RuleAndSystem
import SystemOfNotation
import Reduction
import Omega
import Prelude
-- A "dynamic" signature: the arity is encoded in the function symbol, where
-- the actual function symbol is represented by a string.
data DynamicSigma = DynamicFun String Int
instance Show DynamicSigma where
show (DynamicFun f _) = f
instance Eq DynamicSigma where
(DynamicFun f a) == (DynamicFun g b) = (f == g) && (a == b)
instance Signature DynamicSigma where
arity (DynamicFun _ a) = a
-- A "dynamic" variable set: variables are represented by strings.
data DynamicVar = DynamicVar String
instance Show DynamicVar where
show (DynamicVar x) = x
instance Eq DynamicVar where
(DynamicVar x) == (DynamicVar y) = x == y
instance Variables DynamicVar
-- A "dynamic" rewrite system: the rules are simply not known.
--
-- Remark that not knowing the rules still makes sense in the context of the
-- confluence and compression algorithms, as these use the rules embedded in
-- the reductions they are applied to.
type DynamicSystem = System DynamicSigma DynamicVar
dynamicSystem :: DynamicSystem
dynamicSystem = SystemCons rs
where rs = error "Rules cannot be queried in dynamic systems"
-- A "dynamic" reduction.
type DynamicReduction= CReduction DynamicSigma DynamicVar DynamicSystem
-- The following converts arbitrary reductions of length at most omega to
-- "dynamic" reductions. The main function is makeDynamic.
dynamicTerm :: (Show s, Show v, Signature s, Variables v)
=> Term s v -> Term DynamicSigma DynamicVar
dynamicTerm (Function f xs) = Function f' xs'
where f' = DynamicFun (show f) (arity f)
xs' = fmap dynamicTerm xs
dynamicTerm (Variable x) = Variable x'
where x' = DynamicVar (show x)
dynamicTerms :: (Show s, Show v, RewriteSystem s v r)
=> CReduction s v r -> [Term DynamicSigma DynamicVar]
dynamicTerms (CRCons (RCons ts _) _) = map dynamicTerm (getFrom ts ordZero)
dynamicStep :: (Show s, Show v, Signature s, Variables v)
=> Step s v -> Step DynamicSigma DynamicVar
dynamicStep (ps, Rule l r) = (ps, Rule l' r')
where l' = dynamicTerm l
r' = dynamicTerm r
dynamicSteps :: (Show s, Show v, RewriteSystem s v r)
=> CReduction s v r -> [Step DynamicSigma DynamicVar]
dynamicSteps (CRCons (RCons _ ss) _) = map dynamicStep (getFrom ss ordZero)
dynamicModulus :: RewriteSystem s v r
=> CReduction s v r -> Modulus Omega
dynamicModulus (CRCons _ phi) = constructModulus phi'
where phi' depth = ord2Int (phi ordZero depth)
makeDynamic :: (Show s, Show v, RewriteSystem s v r)
=> CReduction s v r -> DynamicReduction
makeDynamic reduction
| atMostLengthOmega reduction = CRCons (RCons ts ss) phi
| otherwise = error "Reduction too long"
where ts = constructSequence terms
ss = constructSequence steps
phi = dynamicModulus reduction
terms = dynamicTerms reduction
steps = dynamicSteps reduction
| jeroenk/iTRSsVisualised | DynamicReduction.hs | agpl-3.0 | 4,067 | 0 | 9 | 842 | 896 | 463 | 433 | 68 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Address (tests) where
import ProxyPool.Mining (validateAddress)
import Test.Tasty
import Test.Tasty.Hspec
tests :: TestTree
tests = testGroup "Address" [ testCase "validateAddress" validateAddressSpec ]
validateAddressSpec :: Spec
validateAddressSpec = describe "Correct validation of addresses" $ do
it "Sample valid Bitcoin addresses" $ do
mapM_ (\addr -> validateAddress 0 addr `shouldBe` True) [ "1MLxjL47W49UMhiLQ6ieSwf7txgDYzDBc6", "1JRYNuPNsWdQ1vx3BmL8wYNZvvV2psV3VZ", "1MYiq7UGv5VVKSDNMQ17U7w17rm1S6Yrn9", "17Lisb7ZGGLBjdWTPqnYZA1DqqKn3bMhoG", "1CiqaDs1X6Eg5cqJZLu2cyt1jnxx2CHZpW", "1DctiX2wAtwik2rYo18eoi2P5FdoJ1bq6M" ]
it "Sample valid Dogecoin addresses" $ do
mapM_ (\addr -> validateAddress 30 addr `shouldBe` True) [ "DBsxLKzmxZgArKzSLoqoGzvg7vFgRqnXXX", "D8gq3EiwxkysSfKMXv3eoCMZTJvvSkt1UR", "DD3AhTdraFq3Ew4TxMHoVRTrak9xc96GSv" , "DL6FFLtPTXGLtNrBwQSouDXu6KnPB2qVjA" , "DPCJG1rS4Pet9AjzycDDcx7BS7enwL87CU" , "DJH9oLV7Bx4vL8R8SoKa4crAuqvU1JUTfh" , "DQPY4ArDgqeL5ucGRbyr7bjgBgkDLFSAYa" , "D7S7ooAKRZ4WcJAKmh3C4zVZHMdHDy47BD" , "DHfnc9Sd3ShEkHtmryGNbHo7jY5XBRegbU" , "DBWXFnm9F96VZnZPBdrEddJGmRiop9GVCh" ]
it "Sample invalid Bitcoin addresses" $ do
validateAddress 0 "ablahhdha" `shouldBe` False
validateAddress 0 "1`wefswei923!!" `shouldBe` False
validateAddress 0 "1MLxjL47W49UMhiLQ6ieSwf7txgDYzDBc7" `shouldBe` False
validateAddress 0 "1mLxjL47W49UMhiLQ6ieSwf7txgDYzDBc6" `shouldBe` False
| dogestreet/proxypool | tests/Address.hs | agpl-3.0 | 1,512 | 0 | 15 | 189 | 259 | 141 | 118 | 18 | 1 |
module View where
import Model
import Logic
data ViewResource = ViewResource { descr :: String
,shortd :: String
} deriving (Show)
data ViewState = ViewState String (State ViewResource) String deriving (Show)
--showRoomExit :: String -> (Maybe RoomId) -> String
showRoomExit _ Nothing = ""
showRoomExit dname (Just e) = dname
--showRoomExitsDir :: String -> Exits -> String
showRoomExitsDir d e
| d == "north" = showRoomExit d (north e) ++ (showRoomExitsDir "south" e)
| d == "south" = showRoomExit d (south e) ++ (showRoomExitsDir "east" e)
| d == "east" = showRoomExit d (east e) ++ (showRoomExitsDir "west" e)
| d == "west" = showRoomExit d (west e)
--showRoomExits :: Room r -> String
showRoomExits r = "Exits are " ++ (showRoomExitsDir "north" ( exits r ) ) ++ "\n"
--showExits :: State r -> String
showExits s = showRoomExits $ room s
showPreSuffix s
| s == "" = ""
| otherwise = s ++ "\n"
--showFullState :: ViewState -> String
showFullState (ViewState pre s post) = (showPreSuffix pre) ++ "You are " ++ (descr $ resource r) ++ "\n" ++ (showPreSuffix post)
where r = room s
--showShortState :: ViewState -> String
showShortState (ViewState pre s post) = (showPreSuffix pre) ++ "You are " ++ (shortd $ resource r) ++ "\n" ++ (showPreSuffix post)
where r = room s
--showState :: ViewState -> String
showState v@(ViewState _ s _) = if ( visited $ room s ) then (showShortState v) else (showFullState v)
--showItems :: State r -> String
showItems s = "Looking around you see " ++ (foldl (\a i -> (a ++ "a " ++ (show i) ++ " ")) "" $ curItems s)
--showHelp :: ViewState -> String
showHelp s = "Commands are: north, south, east, west, exits, look, quit, help"
--doGo :: Direction -> State ViewResource -> ViewState
doGo d s = ViewState pre (go d s) ""
where pre = if ( curDirExit d s ) == Nothing then "You can't go that way." else ""
--doCmd :: String -> ViewState -> ViewState
doCmd c v@(ViewState _ s _) = case c of "north" -> doGo North s
"south" -> doGo South s
"east" -> doGo East s
"west" -> doGo West s
"exits" -> ViewState "" s (showExits s)
"look" -> ViewState "" s (showItems s)
"quit" -> ViewState "" (quit s) "Quitters never prosper"
"help" -> ViewState "" s (showHelp v)
c -> ViewState ("I don't know how to " ++ c ++ ".") s ""
--gameRecur :: ViewState -> IO()
gameRecur v@(ViewState _ s _) = do
putStrLn $ showState v
let v'@(ViewState _ s' _) = ViewState "" (Model.setCurRoomVisited s) ""
if (Model.status s') == Model.GameOver then
return ()
else
do
cmd <- getLine
gameRecur ( (doCmd cmd) v' )
vResources = [ ViewResource { descr = "in a small dark room. No windows and only a single door."
,shortd = "in the small dark room."
}
,ViewResource { descr ="in the cold barren tundra. A small nearby shack to the south the only sign of civilization."
,shortd ="outside."
}
]
vRooms = iRooms vResources
| LoggerMN/hsAdventure | src/View.hs | lgpl-3.0 | 3,542 | 0 | 15 | 1,243 | 960 | 488 | 472 | 50 | 9 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Hecate.Backend.JSON
( JSON
, run
, initialize
, finalize
, AppState
) where
import Control.Monad (when)
import Control.Monad.Catch (MonadThrow (..))
import qualified Control.Monad.Except as Except
import Control.Monad.IO.Class (MonadIO (..))
import Control.Monad.Reader (MonadReader, ReaderT, ask, runReaderT)
import Control.Monad.State (MonadState, StateT, gets, modify, runStateT)
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Encode.Pretty as AesonPretty
import qualified Data.List as List
import Hecate.Backend.JSON.AppState (AppState, appStateDirty)
import qualified Hecate.Backend.JSON.AppState as AppState
import Hecate.Data (Config, configDataDirectory, configDataFile, entryKeyOrder)
import Hecate.Interfaces
-- * JSON
newtype JSON a = JSON { unJSON :: ReaderT Config (StateT AppState IO) a }
deriving ( Functor
, Applicative
, Monad
, MonadIO
, MonadReader Config
, MonadState AppState
, MonadEncrypt
, MonadInteraction
, MonadAppError
)
instance MonadThrow JSON where
throwM = liftIO . throwM
runJSON :: JSON a -> AppState -> Config -> IO (a, AppState)
runJSON m state cfg = runStateT (runReaderT (unJSON m) cfg) state
writeState :: (MonadAppError m, MonadInteraction m) => AppState -> Config -> m ()
writeState state cfg = when (appStateDirty state) $ do
let dataFile = configDataFile cfg
entries = AppState.selectAll state
aesonCfg = AesonPretty.defConfig{AesonPretty.confCompare = AesonPretty.keyOrder entryKeyOrder}
dataBS = AesonPretty.encodePretty' aesonCfg (List.sort entries)
writeFileFromLazyByteString dataFile dataBS
run :: JSON a -> AppState -> Config -> IO a
run m state cfg = do
(res, state') <- runJSON m state cfg
writeState state' cfg
return res
createState :: (MonadAppError m, MonadInteraction m) => Config -> m AppState
createState cfg = do
let dataDir = configDataDirectory cfg
dataFile = configDataFile cfg
dataDirExists <- doesDirectoryExist dataDir
Except.unless dataDirExists (createDirectory dataDir)
dataBS <- readFileAsLazyByteString dataFile
maybe (aesonError "could not decode") (pure . AppState.mkAppState) (Aeson.decode dataBS)
initialize :: (MonadAppError m, MonadInteraction m) => Config -> m (Config, AppState)
initialize cfg = do
state <- createState cfg
return (cfg, state)
finalize :: (MonadAppError m, MonadInteraction m) => (Config, AppState) -> m ()
finalize _ = pure ()
-- * Instances
instance MonadConfigReader JSON where
askConfig = ask
instance MonadStore JSON where
put e = modify $ AppState.put e
delete e = modify $ AppState.delete e
query q = gets (AppState.query q)
selectAll = gets AppState.selectAll
getCount = gets AppState.getCount
getCountOfKeyId kid = gets (AppState.getCountOfKeyId kid)
createTable = undefined
migrate _ _ = undefined
currentSchemaVersion = undefined
| henrytill/hecate | src/Hecate/Backend/JSON.hs | apache-2.0 | 3,297 | 0 | 14 | 862 | 909 | 488 | 421 | 72 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module IFind.UI (
runUI
) where
import Control.Applicative
import Data.Either
import Data.IORef
import Graphics.Vty hiding (pad)
import Graphics.Vty.Widgets.All
import System.Exit (exitSuccess)
import Text.Printf
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Text.Regex.PCRE as RE
import qualified Text.Regex.PCRE.String as RES
import IFind.Config
import IFind.FS
import IFind.Opts
import Util.List
-- This type isn't pretty, but we have to specify the type of the
-- complete interface. Initially you can let the compiler tell you
-- what it is.
type T = (Box (Box (HFixed FormattedText) (VFixed Edit))
(List T.Text FormattedText))
data SearchApp =
SearchApp { -- widgets
uiWidget :: Widget T
, statusWidget :: Widget FormattedText
, editSearchWidget :: Widget Edit
, searchResultsWidget :: Widget (List T.Text FormattedText)
, activateHandlers :: Handlers SearchApp
-- search state
, matchingFilePaths:: IORef [TextFilePath]
, allFilePaths:: [TextFilePath]
, ignoreCase:: IORef Bool
}
focusedItemAttr:: IFindConfig -> Attr
focusedItemAttr conf = fgc `on` bgc
where
bgc = focusedItemBackgroundColor . uiColors $ conf
fgc = focusedItemForegroundColor . uiColors $ conf
searchCountAttr:: IFindConfig -> Attr
searchCountAttr conf = fgc `on` bgc
where
bgc = searchCountBackgroundColor . uiColors $ conf
fgc = searchCountForegroundColor . uiColors $ conf
-- | runs UI, returns matching file paths
runUI :: IFindOpts -> IFindConfig -> IO [TextFilePath]
runUI opts conf = do
(ui, fg) <- newSearchApp opts conf
c <- newCollection
_ <- addToCollection c (uiWidget ui) fg
runUi c $ defaultContext { focusAttr = focusedItemAttr conf }
readIORef $ matchingFilePaths ui
newSearchApp :: IFindOpts -> IFindConfig -> IO (SearchApp, Widget FocusGroup)
newSearchApp opts conf = do
editSearchWidget' <- editWidget
searchResultsWidget' <- newTextList [] 1
statusWidget' <- plainText "*>" >>= withNormalAttribute (searchCountAttr conf)
activateHandlers' <- newHandlers
_ <- setEditText editSearchWidget' $ T.pack (searchRe opts)
uiWidget' <- ( (hFixed 8 statusWidget') <++> (vFixed 1 editSearchWidget') )
<-->
(return searchResultsWidget')
allFilePaths' <- findAllFilePaths opts conf
matchingFilePathsRef <- newIORef allFilePaths'
ignoreCaseRef <- newIORef $ caseInsensitive opts
let sApp = SearchApp { uiWidget = uiWidget'
, statusWidget = statusWidget'
, editSearchWidget = editSearchWidget'
, searchResultsWidget = searchResultsWidget'
, activateHandlers = activateHandlers'
, matchingFilePaths = matchingFilePathsRef
, allFilePaths = allFilePaths'
, ignoreCase = ignoreCaseRef
}
editSearchWidget' `onActivate` \_ -> do
shutdownUi
editSearchWidget' `onChange` \_ -> do
updateSearchResults sApp
return ()
editSearchWidget' `onKeyPressed` \_ key mods -> do
case (key, mods) of
(KChar 'u', [MCtrl]) -> do
ic <- readIORef ignoreCaseRef
writeIORef ignoreCaseRef (not ic)
updateSearchResults sApp
return True
(_, _) ->
return False
searchResultsWidget' `onKeyPressed` \w key mods ->
case (key, mods) of
(KChar 'p', [MCtrl]) -> scrollUp w >> return True
(KChar 'n', [MCtrl]) -> scrollDown w >> return True
(KChar 'k', []) -> scrollUp w >> return True
(KChar 'j', []) -> scrollDown w >> return True
(_, _) -> return False
searchResultsWidget' `onItemActivated` \_ -> do
selectedItem <- getSelected searchResultsWidget'
case selectedItem of
Just (_, (t, _)) -> do
writeIORef matchingFilePathsRef [t]
shutdownUi
Nothing ->
return ()
fg <- newFocusGroup
fg `onKeyPressed` \_ key _ -> do
case key of
KEsc -> do
shutdownUi
exitSuccess
_ -> return False
_ <- addToFocusGroup fg editSearchWidget'
_ <- addToFocusGroup fg searchResultsWidget'
_ <- updateSearchResults sApp
return (sApp, fg)
updateSearchResults:: SearchApp -> IO ()
updateSearchResults sApp = do
clearList $ searchResultsWidget sApp
searchEditTxt <- getEditText $ editSearchWidget sApp
ignoreCase' <- readIORef $ ignoreCase sApp
stfp <- searchTxtToFilterPredicate ignoreCase' searchEditTxt
case stfp of
Left es -> do
writeIORef (matchingFilePaths sApp) []
addToResultsList sApp $ fmap (T.pack) es
Right filterPredicate -> do
let matchingFps = filter (filterPredicate) $ allFilePaths sApp
writeIORef (matchingFilePaths sApp) matchingFps
addToResultsList sApp $ take 64 matchingFps
updateStatusText sApp
addToResultsList:: SearchApp -> [T.Text] -> IO ()
addToResultsList sApp xs =
mapM_ (\x -> do
xw <- textWidget nullFormatter x
addToList (searchResultsWidget sApp) x xw) xs
updateStatusText:: SearchApp -> IO ()
updateStatusText sApp = do
matchingFps <- readIORef (matchingFilePaths sApp)
let numResults = length matchingFps
searchEditTxt <- getEditText $ editSearchWidget sApp
ignoreCase' <- readIORef $ ignoreCase sApp
let statusChr = if ignoreCase' then '*' else ']'
if T.null searchEditTxt
then setText (statusWidget sApp) $ T.pack $ "Search: "
else setText (statusWidget sApp) $ T.pack $ printf "[%5d%c " numResults statusChr
-- | searchTxt can be of the form "foo!bar!baz",
-- this behaves similar to 'grep foo | grep -v bar | grep -v baz'
-- Return either Left regex compilation errors or Right file path testing predicate
searchTxtToFilterPredicate:: Bool -> T.Text -> IO (Either [String] (TextFilePath -> Bool))
searchTxtToFilterPredicate reIgnoreCase searchEditTxt =
if T.null searchEditTxt
then return $ Right (\_ -> True)
else compileRegex
where
compileRegex = do cRes <- compileRes
case partitionEithers cRes
of ([], (includeRe:excludeRes)) ->
return $ Right $ \fp ->
let bsFp = TE.encodeUtf8 fp
in (RE.matchTest includeRe bsFp) &&
(not . anyOf (fmap (RE.matchTest) excludeRes) $ bsFp)
(errs, _) -> return $ Left $ map (snd) errs
mkRe:: T.Text -> IO (Either (RES.MatchOffset, String) RES.Regex)
mkRe t = RES.compile reCompOpt reExecOpt (T.unpack t)
reCompOpt =(if (reIgnoreCase) then RES.compCaseless else RES.compBlank)
reExecOpt = RES.execBlank
compileRes:: IO [Either (RES.MatchOffset, String) RE.Regex]
compileRes = mapM (mkRe) $ T.splitOn "!" searchEditTxt
| andreyk0/ifind | IFind/UI.hs | apache-2.0 | 6,997 | 0 | 24 | 1,839 | 1,962 | 1,000 | 962 | 155 | 8 |
module Checker where
import Data.Maybe
import EdictDB
type Conjugation = String
conjugate :: Word -> Conjugation -> Maybe Word
conjugate _ [] = Nothing
conjugate ([],_) _ = Nothing
conjugate w c
| not (validC c) = Just w
| c == "Te" = teForm $ Just w
| c == "Imperitive" = imperitive $ Just w
| c == "TeIru" = teIru $ Just w
| c == "Past" = pastTense $ Just w
| c == "Tai" = taiForm $ Just w
| c == "Negative" = negative $ Just w
| c == "NegTai" = negative . taiForm $ Just w
| c == "NegPastTai" = pastTense . negative . taiForm $ Just w
| c == "Causitive" = causitive $ Just w
| c == "CausPass" = passive . causitive $ Just w
| c == "Passive" = passive $ Just w
| c == "Polite" = polite w
| c == "PoliteNeg" = politeNeg w
| c == "PolitePast" = politePast w
| c == "PNegPast" = politeNegPast w
| c == "PoVo" = politeVolitional w
| c == "Stem" = stem $ Just w
| otherwise = Nothing
teForm :: Maybe Word -> Maybe Word
teForm Nothing = Nothing
teForm x
| hasIorERu x = Just (init y ++ "て", 'e') --This needs to check for preceding い or え
| last y == 'く' = Just (init y ++ "いて", 'e')
| last y == 'ぐ' = Just (init y ++ "いで", 'e')
| last y == 'う' = Just (init y ++ "って", 'e')
| last y == 'つ' = Just (init y ++ "って", 'e')
| last y == 'る' = Just (init y ++ "って", 'e')
| last y == 'ぬ' = Just (init y ++ "んで", 'e')
| last y == 'む' = Just (init y ++ "んで", 'e')
| last y == 'ぶ' = Just (init y ++ "んで", 'e')
| last y == 'す' = Just (init y ++ "して", 'e')
| otherwise = Nothing
where z = fromJust x
y = fst z
hasIorERu :: Maybe Word -> Bool
hasIorERu Nothing = False
hasIorERu x = beginsWith x 'i' && beginsWith x 'e' && snd y == 'r'
where y = fromJust x
beginsWith :: Maybe Word -> Char -> Bool --probably a bad name for this function, rename later
beginsWith Nothing _ = False
beginsWith x y
| y == 'a' = beginsWithA z
| y == 'i' = beginsWithI z
| y == 'u' = beginsWithU z
| y == 'e' = beginsWithE z
| y == 'o' = beginsWithO z
| otherwise = False --maybe not the best solution, possibly throw an error here
where z = fromJust x
beginsWithA :: Word -> Bool
beginsWithA x
| z == 'あ' = True
| z == 'か' = True
| z == 'が' = True
| z == 'さ' = True
| z == 'ざ' = True
| z == 'た' = True
| z == 'だ' = True
| z == 'な' = True
| z == 'は' = True
| z == 'ば' = True
| z == 'ぱ' = True
| z == 'ま' = True
| z == 'ら' = True
| z == 'わ' = True
| z == 'や' = True
| otherwise = False
where y = take 2 $ reverse . fst $ x
z = y !! 2
beginsWithI :: Word -> Bool
beginsWithI x
| z == 'い' = True
| z == 'き' = True
| z == 'ぎ' = True
| z == 'し' = True
| z == 'じ' = True
| z == 'ち' = True
| z == 'ぢ' = True
| z == 'に' = True
| z == 'ひ' = True
| z == 'び' = True
| z == 'ぴ' = True
| z == 'み' = True
| z == 'り' = True
| otherwise = False
where y = take 2 $ reverse . fst $ x
z = y !! 2
beginsWithU :: Word -> Bool
beginsWithU x
| z == 'う' = True
| z == 'く' = True
| z == 'ぐ' = True
| z == 'す' = True
| z == 'ず' = True
| z == 'つ' = True
| z == 'づ' = True
| z == 'ぬ' = True
| z == 'ふ' = True
| z == 'ぶ' = True
| z == 'ぷ' = True
| z == 'む' = True
| z == 'る' = True
| z == 'ゆ' = True
| otherwise = False
where y = take 2 $ reverse . fst $ x
z = y !! 2
beginsWithE :: Word -> Bool
beginsWithE x
| z == 'え' = True
| z == 'け' = True
| z == 'げ' = True
| z == 'せ' = True
| z == 'ぜ' = True
| z == 'て' = True
| z == 'で' = True
| z == 'ね' = True
| z == 'へ' = True
| z == 'べ' = True
| z == 'ぺ' = True
| z == 'め' = True
| z == 'れ' = True
| otherwise = False
where y = take 2 $ reverse . fst $ x
z = y !! 2
beginsWithO :: Word -> Bool
beginsWithO x
| z == 'お' = True
| z == 'こ' = True
| z == 'ご' = True
| z == 'そ' = True
| z == 'ぞ' = True
| z == 'と' = True
| z == 'ど' = True
| z == 'の' = True
| z == 'ほ' = True
| z == 'ぼ' = True
| z == 'ぽ' = True
| z == 'も' = True
| z == 'ろ' = True
| z == 'よ' = True
| otherwise = False
where y = take 2 $ reverse . fst $ x
z = y !! 2
teIru :: Maybe Word -> Maybe Word
teIru Nothing = Nothing
teIru x
| isNothing (teForm x) = Nothing
| otherwise = Just (y ++ "いる", 'r')
where y = fst . fromJust . teForm $ x
pastTense :: Maybe Word -> Maybe Word
pastTense Nothing = Nothing
pastTense x
| snd z == 'r' = Just (init (fst z) ++ "た", 'r')
| snd z == 'u' && last y == 'て' = Just (init y ++ "た", 'u')
| snd z == 'u' && last y == 'で' = Just (init y ++ "だ", 'u')
| snd z == 'i' = Just (init (fst z) ++ "かった", 'i')
| snd z == 'd' = Just (init (fst z) ++ "だった", 'd')
| otherwise = Nothing
where z = fromJust x
y = fst . fromJust . teForm $ x
taiForm :: Maybe Word -> Maybe Word
taiForm Nothing = Nothing
taiForm x
| snd z == 'r' = Just (init (fst z) ++ "たい", 'i')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "いたい", 'i')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "きたい", 'i')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "ぎたい", 'i')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "したい", 'i')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "ちたい", 'i')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "にたい", 'i')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "みたい", 'i')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "びたい", 'i')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "りたい", 'i')
| snd z == 'n' = Just (init (fst z) ++ "したい", 'i')
| otherwise = Nothing
where z = fromJust x
y = last (fst z)
negative :: Maybe Word -> Maybe Word
negative Nothing = Nothing
negative x
| snd z == 'i' = Just (init (fst z) ++ "くない", 'i')
| snd z == 'r' = Just (init (fst z) ++ "ない", 'i')
| snd z == 'd' = Just (init (fst z) ++ "じゃない", 'i')
| snd z == 'n' = Just (init (fst z) ++ "しない", 'i')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "わない", 'i')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "かない", 'i')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "がない", 'i')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "さない", 'i')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "たない", 'i')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "なない", 'i')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "まない", 'i')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "ばない", 'i')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "らない", 'i')
| otherwise = Nothing
where z = fromJust x
y = last (fst z)
imperitive :: Maybe Word -> Maybe Word
imperitive Nothing = Nothing
imperitive x
| snd z == 'n' = Just (fst z ++ "しろ", 'r')
| snd z == 'r' = Just (init (fst z) ++ "れ",'r')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "え", 'u')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "け", 'u')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "げ", 'u')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "せ", 'u')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "て", 'u')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "ね", 'u')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "め", 'u')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "べ", 'u')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "れ", 'u')
where z = fromJust x
y = last (fst z)
negativeImperitive :: Maybe Word -> Maybe Word
negativeImperitive Nothing = Nothing
negativeImperitive x
| snd z == 'n' = Just (fst z ++ "するな", 'n')
| snd z == 'r' || snd z == 'u' = Just (fst z ++ "な", 'n')
| otherwise = Nothing
where z = fromJust x
volitional :: Maybe Word -> Maybe Word
volitional Nothing = Nothing
volitional x
| snd z == 'n' = Just (fst z ++ "しよう", 'u')
| snd z == 'r' = Just (init (fst z) ++ "よう",'r')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "おう", 'u')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "こう", 'u')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "ごう", 'u')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "そう", 'u')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "とう", 'u')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "のう", 'u')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "もう", 'u')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "ぼう", 'u')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "ろう", 'u')
| snd z == 'i' = Just (init (fst z) ++ "かろう", 'u')
| snd z == 'a' = Just (init (fst z) ++ "だろう", 'u')
| otherwise = Nothing
where z = fromJust x
y = last (fst z)
potential :: Maybe Word -> Maybe Word
potential Nothing = Nothing
potential x
| snd z == 'd' = Just (fst z ++ "できる", 'r')
| snd z == 'r' = Just (init (fst z) ++ "られる",'r')
| snd z == 'n' = Just (init (fst z) ++ "せられる",'r')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "える", 'u')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "ける", 'u')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "げる", 'u')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "せる", 'u')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "てる", 'u')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "ねる", 'u')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "める", 'u')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "べる", 'u')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "れる", 'u')
| snd z == 'i' = Just (init (fst z) ++ "あり得る", 'u')
| otherwise = Nothing
where z = fromJust x
y = last (fst z)
conditional :: Maybe Word -> Maybe Word
conditional Nothing = Nothing
conditional x = Just (fst z ++ "ら", snd y)
where z = fromJust . pastTense $ x
y = fromJust x
passive :: Maybe Word -> Maybe Word
passive Nothing = Nothing
passive x
| snd z == 'n' = Just (fst z ++ "される", 'r')
| snd z == 'r' = Just (init (fst z) ++ "られる",'r')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "われる", 'u')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "かれる", 'u')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "がれる", 'u')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "される", 'u')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "たれる", 'u')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "なれる", 'u')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "まれる", 'u')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "ばれる", 'u')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "られる", 'u')
| otherwise = Nothing
where z = fromJust x
y = last (fst z)
causitive :: Maybe Word -> Maybe Word
causitive Nothing = Nothing
causitive x
| snd z == 'n' = Just (fst z ++ "させる", 'r')
| snd z == 'r' = Just (init (fst z) ++ "させる",'r')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "わせる", 'u')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "かせる", 'u')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "がせる", 'u')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "させる", 'u')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "たせる", 'u')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "なせる", 'u')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "ませる", 'u')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "ばせる", 'u')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "らせる", 'u')
| otherwise = Nothing
where z = fromJust x
y = last (fst z)
causitivePassive :: Maybe Word -> Maybe Word
causitivePassive Nothing = Nothing
causitivePassive x = passive . causitive $ x
provisionalConditional :: Maybe Word -> Maybe Word
provisionalConditional Nothing = Nothing
provisionalConditional x
| snd z == 'n' = Just (fst z ++ "すれば", 'u')
| snd z == 'r' = Just (init (fst z) ++ "れば",'r')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "えば", 'u')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "けば", 'u')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "げば", 'u')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "せば", 'u')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "てば", 'u')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "ねば", 'u')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "めば", 'u')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "べば", 'u')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "れば", 'u')
| snd z == 'i' = Just (init (fst z) ++ "ければ", 'u')
| snd z == 'a' = Just (init (fst z) ++ "であれば", 'u')
where z = fromJust x
y = last (fst z)
stem :: Maybe Word -> Maybe Word
stem Nothing = Nothing
stem x
| snd z == 'r' = Just (init (fst z), 'r')
| snd z == 'u' && y == 'う' = Just (init (fst z) ++ "い", 'u')
| snd z == 'u' && y == 'く' = Just (init (fst z) ++ "き", 'u')
| snd z == 'u' && y == 'ぐ' = Just (init (fst z) ++ "ぎ", 'u')
| snd z == 'u' && y == 'す' = Just (init (fst z) ++ "し", 'u')
| snd z == 'u' && y == 'つ' = Just (init (fst z) ++ "ち", 'u')
| snd z == 'u' && y == 'ぬ' = Just (init (fst z) ++ "に", 'u')
| snd z == 'u' && y == 'む' = Just (init (fst z) ++ "み", 'u')
| snd z == 'u' && y == 'ぶ' = Just (init (fst z) ++ "び", 'u')
| snd z == 'u' && y == 'る' = Just (init (fst z) ++ "り", 'u')
| fst z == "する" = Just ("し", 's')
| fst z == "くる" = Just ("き", 'k')
| otherwise = Nothing
where z = fromJust x
y = last (fst z)
polite :: Word -> Maybe Word
polite x
| snd x == 'n' = Just (fst x ++ "します", 'e')
| snd x == 'r' = Just (init (fst x) ++ "ます", 'e')
| snd x == 'u' && y == 'う' = Just (init (fst x) ++ "います", 'e')
| snd x == 'u' && y == 'く' = Just (init (fst x) ++ "きます", 'e')
| snd x == 'u' && y == 'ぐ' = Just (init (fst x) ++ "ぎます", 'e')
| snd x == 'u' && y == 'す' = Just (init (fst x) ++ "します", 'e')
| snd x == 'u' && y == 'つ' = Just (init (fst x) ++ "ちます", 'e')
| snd x == 'u' && y == 'ぬ' = Just (init (fst x) ++ "にます", 'e')
| snd x == 'u' && y == 'む' = Just (init (fst x) ++ "みます", 'e')
| snd x == 'u' && y == 'ぶ' = Just (init (fst x) ++ "びます", 'e')
| snd x == 'u' && y == 'る' = Just (init (fst x) ++ "ります", 'e')
| otherwise = Nothing
where y = last (fst x)
politeNeg :: Word -> Maybe Word
politeNeg x
| isNothing (polite x) = Nothing
| otherwise = Just (init y ++ "せん", 'e')
where y = fst . fromJust . polite $ x
politeNegPast :: Word -> Maybe Word
politeNegPast x
| isNothing (politeNeg x) = Nothing
| otherwise = Just (y ++ "でした", 'e')
where y = fst . fromJust . politeNeg $ x
politePast :: Word -> Maybe Word
politePast x
| isNothing (polite x) = Nothing
| otherwise = Just (y ++ "した", 'e')
where y = fst . fromJust . polite $ x
politeVolitional :: Word -> Maybe Word
politeVolitional x
| isNothing (polite x) = Nothing
| otherwise = Just (init y ++ "しょう", 'e')
where y = fst . fromJust . polite $ x
validC :: Conjugation -> Bool
validC [] = False
validC x
| x == "Te" = True
| x == "Imperitive" = True
| x == "Past" = True
| x == "TeIru" = True
| x == "Negative" = True
| x == "Tai" = True
| x == "NegTai" = True
| x == "NegPastTai" = True
| x == "Potential" = True
| x == "Causitive" = True
| x == "Passive" = True
| x == "CausPass" = True
| x == "Polite" = True
| x == "PoliteNeg" = True
| x == "PolitePast" = True
| x == "PNegPast" = True
| x == "PoVo" = True
| x == "Stem" = True
| otherwise = False
addType :: String -> Maybe Word
addType x
| take 2 (reverse x) == "する" = Just (init (init x),'n')
| last x == 'う' = Just (x,'u')
| last x == 'く' = Just (x,'u')
| last x == 'ぐ' = Just (x,'u')
| last x == 'す' = Just (x,'u')
| last x == 'つ' = Just (x,'u')
| last x == 'づ' = Just (x,'u')
| last x == 'ぬ' = Just (x,'u')
| last x == 'ぶ' = Just (x,'u')
| last x == 'む' = Just (x,'u')
| last x == 'だ' = Just (x, 'd')
| otherwise = dbLookup x
| MarkMcCaskey/Refcon | Checker.hs | apache-2.0 | 17,577 | 0 | 11 | 5,484 | 9,399 | 4,465 | 4,934 | 414 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Text.HTML.SanitizeXSS
import Text.HTML.SanitizeXSS.Css
import Data.Text (Text)
import Data.Text as T
import Test.Hspec.Monadic
import Test.Hspec.HUnit ()
import Test.HUnit (assert, (@?=), Assertion)
test :: (Text -> Text) -> Text -> Text -> Assertion
test f actual expected = do
let result = f actual
result @?= expected
sanitized = test sanitize
main = hspecX $ do
describe "html sanitizing" $ do
it "big test" $ do
let testHTML = " <a href='http://safe.com'>safe</a><a href='unsafe://hack.com'>anchor</a> <img src='evil://evil.com' /> <unsafe></foo> <bar /> <br></br> <b>Unbalanced</div><img src='http://safe.com'>"
test sanitizeBalance testHTML " <a href=\"http://safe.com\">safe</a><a>anchor</a> <img /> <br /> <b>Unbalanced<div></div><img src=\"http://safe.com\"></b>"
sanitized testHTML " <a href=\"http://safe.com\">safe</a><a>anchor</a> <img /> <br /> <b>Unbalanced</div><img src=\"http://safe.com\">"
it "relativeURI" $ do
let testRelativeURI = "<a href=\"foo\">bar</a>"
sanitized testRelativeURI testRelativeURI
it "protocol hack" $
sanitized "<script src=//ha.ckers.org/.j></script>" ""
it "object hack" $
sanitized "<object classid=clsid:ae24fdae-03c6-11d1-8b76-0080c744f389><param name=url value=javascript:alert('XSS')></object>" ""
it "embed hack" $
sanitized "<embed src=\"data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==\" type=\"image/svg+xml\" AllowScriptAccess=\"always\"></embed>" ""
it "ucase image hack" $
sanitized "<IMG src=javascript:alert('XSS') />" "<img />"
describe "allowedCssAttributeValue" $ do
it "allows hex" $ do
assert $ allowedCssAttributeValue "#abc"
assert $ allowedCssAttributeValue "#123"
assert $ not $ allowedCssAttributeValue "abc"
assert $ not $ allowedCssAttributeValue "123abc"
it "allows rgb" $ do
assert $ allowedCssAttributeValue "rgb(1,3,3)"
assert $ not $ allowedCssAttributeValue "rgb()"
it "allows units" $ do
assert $ allowedCssAttributeValue "10 px"
assert $ not $ allowedCssAttributeValue "10 abc"
describe "css sanitizing" $ do
it "removes style when empty" $
sanitized "<p style=''></p>" "<p></p>"
it "allows any non-url value for white-listed properties" $ do
let whiteCss = "<p style=\"letter-spacing:foo-bar;text-align:10million\"></p>"
sanitized whiteCss whiteCss
it "rejects any url value" $ do
let whiteCss = "<p style=\"letter-spacing:foo url();text-align:url(http://example.com)\"></p>"
sanitized whiteCss "<p style=\"letter-spacing:foo \"></p>"
it "rejects properties not on the white list" $ do
let blackCss = "<p style=\"anything:foo-bar;other-stuff:10million\"></p>"
sanitized blackCss "<p></p>"
it "rejects invalid units for grey-listed css" $ do
let greyCss = "<p style=\"background:foo-bar;border:10million\"></p>"
sanitized greyCss "<p></p>"
it "allows valid units for grey-listed css" $ do
let grey2Css = "<p style=\"background:1;border-foo:10px\"></p>"
sanitized grey2Css grey2Css
| silkapp/haskell-xss-sanitize | test/main.hs | bsd-2-clause | 3,468 | 0 | 16 | 588 | 567 | 254 | 313 | 60 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QHttp_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:31
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Network.QHttp_h where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Network_h
import Qtc.ClassTypes.Network
import Foreign.Marshal.Array
instance QunSetUserMethod (QHttp ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHttp_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QHttp_unSetUserMethod" qtc_QHttp_unSetUserMethod :: Ptr (TQHttp a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QHttpSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHttp_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QHttp ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHttp_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QHttpSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHttp_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QHttp ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHttp_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QHttpSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QHttp_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QHttp ()) (QHttp x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QHttp setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QHttp_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QHttp_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQHttp x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHttp_setUserMethod" qtc_QHttp_setUserMethod :: Ptr (TQHttp a) -> CInt -> Ptr (Ptr (TQHttp x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QHttp :: (Ptr (TQHttp x0) -> IO ()) -> IO (FunPtr (Ptr (TQHttp x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QHttp_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QHttpSc a) (QHttp x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QHttp setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QHttp_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QHttp_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQHttp x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QHttp ()) (QHttp x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QHttp setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QHttp_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QHttp_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQHttp x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHttp_setUserMethodVariant" qtc_QHttp_setUserMethodVariant :: Ptr (TQHttp a) -> CInt -> Ptr (Ptr (TQHttp x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QHttp :: (Ptr (TQHttp x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQHttp x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QHttp_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QHttpSc a) (QHttp x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QHttp setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QHttp_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QHttp_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQHttp x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QHttp ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QHttp_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QHttp_unSetHandler" qtc_QHttp_unSetHandler :: Ptr (TQHttp a) -> CWString -> IO (CBool)
instance QunSetHandler (QHttpSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QHttp_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QHttp ()) (QHttp x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHttp1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHttp1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHttp_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHttp x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qHttpFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHttp_setHandler1" qtc_QHttp_setHandler1 :: Ptr (TQHttp a) -> CWString -> Ptr (Ptr (TQHttp x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHttp1 :: (Ptr (TQHttp x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQHttp x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QHttp1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHttpSc a) (QHttp x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHttp1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHttp1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHttp_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHttp x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qHttpFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QHttp ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHttp_event cobj_x0 cobj_x1
foreign import ccall "qtc_QHttp_event" qtc_QHttp_event :: Ptr (TQHttp a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QHttpSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHttp_event cobj_x0 cobj_x1
instance QsetHandler (QHttp ()) (QHttp x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHttp2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHttp2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHttp_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHttp x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qHttpFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QHttp_setHandler2" qtc_QHttp_setHandler2 :: Ptr (TQHttp a) -> CWString -> Ptr (Ptr (TQHttp x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QHttp2 :: (Ptr (TQHttp x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQHttp x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QHttp2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QHttpSc a) (QHttp x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QHttp2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QHttp2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QHttp_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQHttp x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qHttpFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QeventFilter_h (QHttp ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHttp_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QHttp_eventFilter" qtc_QHttp_eventFilter :: Ptr (TQHttp a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QHttpSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHttp_eventFilter cobj_x0 cobj_x1 cobj_x2
| keera-studios/hsQt | Qtc/Network/QHttp_h.hs | bsd-2-clause | 16,093 | 0 | 18 | 3,806 | 5,490 | 2,616 | 2,874 | -1 | -1 |
{-# LANGUAGE CPP #-}
module CLaSH.GHC.Compat.Outputable
( showPpr, showSDoc, showPprDebug )
where
#if __GLASGOW_HASKELL__ >= 707
import qualified DynFlags (unsafeGlobalDynFlags)
#elif __GLASGOW_HASKELL__ >= 706
import qualified DynFlags (tracingDynFlags)
#endif
import qualified Outputable (Outputable (..), SDoc, showPpr, showSDoc, showSDocDebug)
showSDoc :: Outputable.SDoc -> String
#if __GLASGOW_HASKELL__ >= 707
showSDoc = Outputable.showSDoc DynFlags.unsafeGlobalDynFlags
#endif
showPprDebug :: Outputable.Outputable a => a -> String
showPprDebug = Outputable.showSDocDebug DynFlags.unsafeGlobalDynFlags . Outputable.ppr
showPpr :: (Outputable.Outputable a) => a -> String
#if __GLASGOW_HASKELL__ >= 707
showPpr = Outputable.showPpr DynFlags.unsafeGlobalDynFlags
#elif __GLASGOW_HASKELL__ >= 706
showPpr = Outputable.showPpr DynFlags.tracingDynFlags
#else
showPpr = Outputable.showPpr
#endif
| christiaanb/clash-compiler | clash-ghc/src-ghc/CLaSH/GHC/Compat/Outputable.hs | bsd-2-clause | 908 | 0 | 7 | 105 | 153 | 92 | 61 | 9 | 1 |
import Intel.ArBB
import Intel.ArBB.Util.Image
import qualified Intel.ArbbVM as VM
import qualified Data.Vector.Storable as V
import qualified Prelude as P
import Prelude as P hiding (map,zipWith)
import Data.Word
import System.IO
import System.Time
import Text.Printf
import System.Environment
import Foreign hiding (new)
{-
| -1 0 1 |
Gx = | -2 0 2 |
| -1 0 1 |
| -1 -2 -1 |
Gy = | 0 0 0 |
| 1 2 1 |
-}
-- Haskell lists and list comprehensions used as a tool
s1, s2 :: [(Exp ISize,Exp ISize)]
s1 = [(1,1),(0,1),(-1,1),(1,-1),(0,-1),(-1,-1)]
s2 = [(1,1),(1,0),(1,-1),(-1,1),(-1,0),(-1,-1)]
coeffs :: [Exp Float]
coeffs = [-1,-2,-1,1,2,1]
gx' :: Exp Float -> Exp Float
gx' x = foldl (+) 0
$ P.zipWith (*) [getNeighbor2D x a b
| (a,b) <- s1] coeffs
gy' :: Exp Float -> Exp Float
gy' x = foldl (+) 0
$ P.zipWith (*) [getNeighbor2D x a b
| (a,b) <- s2] coeffs
gx :: Exp (DVector Dim2 Float) -> Exp (DVector Dim2 Float)
gx = mapStencil (Stencil [-1,0,1
,-2,0,2
,-1,0,1] (Z:.3:.3))
gy :: Exp (DVector Dim2 Float) -> Exp (DVector Dim2 Float)
gy = mapStencil (Stencil [ 1, 2, 1
, 0, 0, 0
,-1,-2,-1] (Z:.3:.3))
test :: Exp (DVector Dim2 Float) ->
(Exp (DVector Dim2 Float), Exp (DVector Dim2 Float))
test v = (gx v,gy v)
--convertToWord8 :: Exp Float -> Exp Word8
--convertToWord8 x = toWord8 $ (clamp x) * 255
--clamp :: Exp Float -> Exp Float
-- Should be clamp, right ?
--clamp x = max 0 (min x 1)
-- 8 bit per pixel greyscale image will be processed.
--kernel :: Exp Word8 -> Exp Word8
--kernel x = convertToWord8 $ body x
-- where
-- body x = sqrt (x' * x' + y' * y')
-- where
-- x' = gx x
-- y' = gy x
magnitude :: Exp Float -> Exp Float -> Exp Float
magnitude x y = sqrt (x * x + y * y)
runMag :: Exp (DVector Dim2 Float) -> Exp (DVector Dim2 Float) ->
Exp (DVector Dim2 Float)
runMag v1 v2 = zipWith magnitude v1 v2
--sobel :: Exp (DVector Dim2 Word8)
-- -> Exp (DVector Dim2 Word8)
--sobel image = map kernel image
testSobel nIters infile outfile =
withArBB $
do
-- f <- capture sobel
test <- capture test
runMag <- capture runMag
convertGray <- capture toGray
convertF <- capture grayToFloat
convertG <- capture floatToGray
img <- liftIO$ loadBMP_RGB infile
let (Dim [3,r,c]) = toDim$ dVectorShape img
imgColor <- copyIn img
imgGray <- new (Z:.c:.r) 0
imgFloat <- new (Z:.c:.r) 0
imgF1 <- new (Z:.c:.r) 0
imgF2 <- new (Z:.c:.r) 0
execute convertGray imgColor imgGray
execute convertF imgGray imgFloat
-- warmup
execute test imgFloat (imgF1 :- imgF2)
finish
t1 <- liftIO getClockTime
execute test imgFloat (imgF1 :- imgF2)
finish
t2 <- liftIO getClockTime
-- Warmup
--execute runMag (imgF1 :- imgF2) (imgFloat)
--finish
--t1 <- liftIO getClockTime
--loop nIters $
-- do
execute runMag (imgF1 :- imgF2) (imgFloat)
-- finish
--t2 <- liftIO getClockTime
execute convertG imgFloat imgGray
finish
r <- copyOut imgGray
liftIO $ saveBMP_Gray outfile r
liftIO $ printf "%f\n" (diffms (diffClockTimes t2 t1))
mb a = 1024*1024*a
main =
do
VM.setHeapSize (mb 1024) (mb (8192*2))
args <- getArgs
case args of
[a,b] ->
let iters = read a :: Int
in
do
-- putStrLn $ "running " ++ show iters ++ " times"
testSobel iters b "sobout.bmp"
_ -> error "incorrects args"
loop 0 action = return ()
loop n action =
do
action
loop (n-1) action
diffms :: TimeDiff -> Float
diffms diff | tdYear diff == 0 &&
tdMonth diff == 0 &&
tdDay diff == 0 &&
tdMin diff == 0 &&
tdHour diff == 0 = (fromIntegral ps) * 1E-9 +
(fromIntegral sec) * 1000
where
ps = tdPicosec diff
sec = tdSec diff
| svenssonjoel/EmbArBB | Samples/Bench/sobel.hs | bsd-3-clause | 4,578 | 2 | 17 | 1,760 | 1,464 | 768 | 696 | 95 | 2 |
module Text.Highlighter.Lexers.Vim (lexer) where
import Text.Regex.PCRE.Light
import Text.Highlighter.Types
lexer :: Lexer
lexer = Lexer
{ lName = "VimL"
, lAliases = ["vim"]
, lExtensions = [".vim", ".vimrc"]
, lMimetypes = ["text/x-vim"]
, lStart = root'
, lFlags = [multiline]
}
root' :: TokenMatcher
root' =
[ tok "^\\s*\".*" (Arbitrary "Comment")
, tok "(?<=\\s)\"[^\\-:.%#=*].*" (Arbitrary "Comment")
, tok "[ \\t]+" (Arbitrary "Text")
, tok "/(\\\\\\\\|\\\\/|[^\\n/])*/" (Arbitrary "Literal" :. Arbitrary "String" :. Arbitrary "Regex")
, tok "\"(\\\\\\\\|\\\\\"|[^\\n\"])*\"" (Arbitrary "Literal" :. Arbitrary "String" :. Arbitrary "Double")
, tok "'(\\\\\\\\|\\\\'|[^\\n'])*'" (Arbitrary "Literal" :. Arbitrary "String" :. Arbitrary "Single")
, tok "-?\\d+" (Arbitrary "Literal" :. Arbitrary "Number")
, tok "#[0-9a-f]{6}" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Hex")
, tok "^:" (Arbitrary "Punctuation")
, tok "[()<>+=!|,\126-]" (Arbitrary "Punctuation")
, tok "\\b(let|if|else|endif|elseif|fun|function|endfunction)\\b" (Arbitrary "Keyword")
, tok "\\b(NONE|bold|italic|underline|dark|light)\\b" (Arbitrary "Name" :. Arbitrary "Builtin")
, tok "\\b\\w+\\b" (Arbitrary "Name" :. Arbitrary "Other")
, tok "." (Arbitrary "Text")
]
| chemist/highlighter | src/Text/Highlighter/Lexers/Vim.hs | bsd-3-clause | 1,348 | 0 | 10 | 242 | 372 | 196 | 176 | 27 | 1 |
module NumberKata where
import DeleteNth
import HappyNumbers
import LastDigitOfLargeNumber
import PascalsTriangle
import PerimeterOfSquaresInRectangle
import ProductOfConsecutiveFibs
import WeightForWeight
testKata :: IO ()
testKata = print "Hey! Another super-useless function!"
| Eugleo/Code-Wars | src/NumberKata.hs | bsd-3-clause | 282 | 0 | 6 | 30 | 43 | 26 | 17 | 10 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Item
( Item(..)
, itemSymbol
, itemDescription
) where
import Control.Lens
import Misc
data Item = Item
{ _itemSymbol :: Symbol
, _itemDescription :: String
} deriving (Read, Show, Eq)
makeLenses ''Item
| dagit/7drl2017 | src/Item.hs | bsd-3-clause | 258 | 0 | 8 | 52 | 72 | 43 | 29 | 12 | 0 |
module Graphics.Vty.Widgets.Builder.Handlers.DirBrowser
( handlers
)
where
import Control.Applicative
import Graphics.Vty.Widgets.Builder.Types
import Graphics.Vty.Widgets.Builder.GenLib
import qualified Graphics.Vty.Widgets.Builder.Validation as V
import qualified Graphics.Vty.Widgets.Builder.SrcHelpers as S
handlers :: [WidgetElementHandler]
handlers = [handleDirBrowser]
handleDirBrowser :: WidgetElementHandler
handleDirBrowser =
WidgetElementHandler genSrc doValidation "dirBrowser"
where
doValidation s = V.optional s "skin"
genSrc nam skin = do
let Just skinName = skin <|> Just "defaultBrowserSkin"
browserName <- newEntry "browser"
fgName <- newEntry "focusGroup"
bData <- newEntry "browserData"
append $ S.bind bData "newDirBrowser" [S.expr $ S.mkName skinName]
append $ S.mkLet [ (nam, S.call "dirBrowserWidget" [S.expr browserName])
, (browserName, S.call "fst" [S.expr bData])
, (fgName, S.call "snd" [S.expr bData])
]
mergeFocus nam fgName
return $ declareWidget nam (S.mkTyp "DirBrowserWidgetType" [])
`withField` (browserName, S.parseType "DirBrowser")
| jtdaugherty/vty-ui-builder | src/Graphics/Vty/Widgets/Builder/Handlers/DirBrowser.hs | bsd-3-clause | 1,325 | 0 | 16 | 368 | 331 | 178 | 153 | 25 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Spell.LazyText
where
import qualified Data.Text.Lazy as TL
import Data.Text.Lazy (Text)
import Data.Monoid
import Data.List.Ordered (nubSort)
import Data.Ord
import Data.List
import Control.Monad
type Dict = ( TL.Text -> Bool, TL.Text -> Int )
singles :: [ TL.Text ]
singles = map TL.singleton ['a'..'z']
edits :: TL.Text -> [ TL.Text ]
edits w = deletes <> nubSort (transposes <> replaces) <> inserts
where
splits = zip (TL.inits w) (TL.tails w)
deletes = [ a <> (TL.drop 1 b) | (a,b) <- splits, TL.length b > 0 ]
transposes = [ a <> c <> (TL.drop 2 b) | (a,b) <- splits, TL.length b > 1,
let c = TL.pack [ TL.index b 1, TL.index b 0 ] ]
replaces = [ a <> c <> (TL.drop 1 b) | (a,b) <- splits, TL.length b > 1,
c <- singles ]
inserts = [ a <> c <> b | (a,b) <- splits, c <- singles ]
orElse :: [a] -> [a] -> [a]
orElse [] bs = bs
orElse as _ = as
-- | Correct a word. 'isMember' and 'frequency' are functions to
-- determine if a word is in the dictionary and to lookup its
-- frequency, respectively.
correct :: Dict -> TL.Text -> TL.Text
correct (isMember,frequency) w0 =
let ed0 = [ w0 ]
ed1 = edits w0
ed2 = [ e2 | e1 <- ed1, e2 <- edits e1 ]
kn0 = filter isMember ed0
kn1 = filter isMember ed1
kn2 = filter isMember ed2
candidates = kn0 `orElse` (kn1 `orElse` (kn2 `orElse` [w0]))
in maximumBy (comparing frequency) candidates
-- helper function to ensure that ghc doesn't optimize calls
-- to 'correct'
foo n w0 | n > 0 = w0 <> ""
| otherwise = w0
-- test correcting a word multiple times (for timing)
testRep :: Dict -> Int -> TL.Text -> IO ()
testRep dictfns n w0 = do
replicateM_ n $ do
print $ correct dictfns (foo n w0)
| erantapaa/test-spelling | src/Spell/LazyText.hs | bsd-3-clause | 1,820 | 0 | 15 | 476 | 719 | 387 | 332 | 40 | 1 |
{-# LANGUAGE RankNTypes, ScopedTypeVariables #-}
module Network.LambdaBridge.Bridge where
import Data.Word as W
import System.Random
import Data.Default
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Concurrent.Chan
import Numeric
import Data.Word
import Data.Binary
import Data.Binary.Get as Get
import Data.Binary.Put as Put
import qualified Data.ByteString.Lazy as LBS
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Time.Clock
import Control.Exception as Exc
import Control.Monad
import Control.Concurrent.Chan
import Control.Concurrent.STM
import Control.Concurrent.STM.TVar
import System.IO.Unsafe (unsafeInterleaveIO)
-- | A 'Bridge' is a bidirectional connection to a specific remote API.
-- There are many different types of Bridges in the lambda-bridge API.
data Bridge msg = Bridge
{ toBridge :: msg -> IO () -- ^ write to a bridge; may block; called many times.
, fromBridge :: IO msg -- ^ read from a bridge; may block, called many times.
-- The expectation is that *eventually* after some
-- time and/or computation
-- someone will read from the bridge, and the
-- reading does not depend on any external interaction or events.
}
--------------------------------------------------------------------------
-- | A 'Bridge (of) Byte' is for talking one byte at a time, where the
-- byte may or may not get there, and may get garbled.
--
-- An example of a 'Bridge (of) Byte' is a RS-232 link.
newtype Byte = Byte W.Word8 deriving (Eq,Ord)
instance Show Byte where
show (Byte w) = "0x" ++ showHex w ""
--------------------------------------------------------------------------
-- | A 'Bridge (of) Bytes' is for talking one byte at a time, where the
-- byte may or may not get there, and may get garbled. The Bytes are
-- sent in order. We provide Bytes because the underlying transportation
-- mechansim *may* choose to send many bytes at the same time.
-- Sending a empty sequence Bytes returns without communications,
-- and it is not possible to receive a empty sequence of bytes.
--
-- An example of a 'Bridge (of) Bytes' is a RS-232 link.
newtype Bytes = Bytes BS.ByteString deriving (Eq,Ord)
instance Show Bytes where
show (Bytes ws) = "Bytes " ++ show [Byte w | w <- BS.unpack ws ]
--------------------------------------------------------------------------
-- | A 'Bridge (of) Frame' is small set of bytes, where a Frame may
-- or may not get to the destination, but if received, will
-- not be garbled or fragmented (via CRC or equiv).
-- There is typically an implementation specific maximum size of a Frame.
-- An example of a 'Bridge (of) Frame' is UDP.
newtype Frame = Frame BS.ByteString
instance Show Frame where
show (Frame wds) = "Frame " ++ show [ Byte w | w <- BS.unpack wds ]
instance Binary Frame where
put (Frame bs) = put bs
get = liftM Frame get
-- | A way of turning a Frame into its contents, using the 'Binary' class.
-- This may throw an async exception.
fromFrame :: (Binary a) => Frame -> a
fromFrame (Frame fs) = decode (LBS.fromChunks [fs])
-- | A way of turning something into a Frame, using the 'Binary' class.
toFrame :: (Binary a) => a -> Frame
toFrame a = Frame $ BS.concat $ LBS.toChunks $ encode a
--------------------------------------------------------------------------
-- | 'debugBridge' outputs to the stderr debugging messages
-- about what datum is getting send where.
debugBridge :: (Show msg) => String -> Bridge msg -> IO (Bridge msg)
debugBridge name bridge = do
sendCounter <- newMVar 0
recvCounter <- newMVar 0
return $ Bridge
{ toBridge = \ a -> do
count <- takeMVar sendCounter
putMVar sendCounter (succ count)
putStrLn $ name ++ ":toBridge<" ++ show count ++ "> (" ++ show a ++ ")"
() <- toBridge bridge a
putStrLn $ name ++ ":toBridge<" ++ show count ++ "> success"
, fromBridge = do
count <- takeMVar recvCounter
putMVar recvCounter (succ count)
putStrLn $ name ++ ":fromBridge<" ++ show count ++ ">"
a <- fromBridge bridge `Exc.catch` \ (e :: SomeException) -> do { print e ; throw e }
putStrLn $ name ++ ":fromBridge<" ++ show count ++ "> (" ++ show a ++ ")"
return a
}
-- | ''Realistic'' is the configuration for ''realisticBridge''.
data Realistic a = Realistic
{ loseU :: Float -- ^ lose an 'a'
, dupU :: Float -- ^ dup an 'a'
, execptionU :: Float -- ^ throw exception instead
, pauseU :: Float -- ^ what is the pause between things
, mangleU :: Float -- ^ mangle an 'a'
, mangler :: Float -> a -> a -- ^ how to mangle, based on a number between 0 and 1
}
-- | default instance of 'realistic', which is completely reliable.
instance Default (Realistic a) where
def = Realistic 0 0 0 0 0 (\ g a -> a)
connectBridges :: (Show msg) => Bridge msg -> Realistic msg -> Realistic msg -> Bridge msg -> IO ()
connectBridges lhs lhsOut rhsOut rhs = do
let you :: Float -> IO Bool
you f = do
r <- randomIO
return $ f > r
let optMangle f mangle a = do
b <- you f
if b then do
r <- randomIO
return $ mangle r a
else return a
let unrely :: MVar UTCTime -> Realistic msg -> msg -> (msg -> IO ()) -> IO ()
unrely tmVar opts a k = do
tm0 <- takeMVar tmVar -- old char time
tm1 <- getCurrentTime -- current time
let pause = pauseU opts - realToFrac (tm1 `diffUTCTime` tm0)
if pause <= 0 then return () else do
threadDelay (floor (pause * 1000 * 1000))
return ()
b <- you (loseU opts)
if b then return () else do -- ignore if you "lose" the message.
a <- optMangle (mangleU opts) (mangler opts) a
b <- you (dupU opts)
if b then do -- send twice, please
k a
k a
else do
k a
tm <- getCurrentTime
putMVar tmVar tm
return ()
tm <- getCurrentTime
tmVar1 <- newMVar tm
tmVar2 <- newMVar tm
forkIO $ forever $ do
msg <- fromBridge lhs
unrely tmVar1 lhsOut msg $ toBridge rhs
forever $ do
msg <- fromBridge rhs
unrely tmVar2 rhsOut msg $ toBridge lhs
| andygill/lambda-bridge | Network/LambdaBridge/Bridge.hs | bsd-3-clause | 6,133 | 46 | 18 | 1,385 | 1,480 | 780 | 700 | 110 | 5 |
import qualified Network.HTTP.Types as HTTP
import qualified Network.HTTP.Conduit as HTTP
import Aws
import qualified Aws.S3 as S3
import qualified Aws.SimpleDb as Sdb
import qualified Aws.Sqs as Sqs
import qualified Aws.Ses as Ses
| jgm/aws | ghci.hs | bsd-3-clause | 292 | 0 | 4 | 92 | 54 | 40 | 14 | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.