code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
module Reader (reader, toPandoc) where
import qualified Data.Text as T
import Text.Pandoc.Class (runIOorExplode)
import Text.Pandoc.Definition (Pandoc)
import Text.Pandoc.Options
import Text.Pandoc.Readers.Markdown (readMarkdown)
reader :: ReaderOptions
reader = def
{ readerStandalone = True
, readerExtensions = disableExtension Ext_pandoc_title_block
. disableExtension Ext_yaml_metadata_block
. disableExtension Ext_table_captions
$ pandocExtensions
}
toPandoc :: String -> IO Pandoc
toPandoc = runIOorExplode . readMarkdown reader . T.pack
|
Thhethssmuz/ppp
|
src/Reader.hs
|
Haskell
|
mit
| 617
|
-- Copyright 2020-2021 Google LLC
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE CPP #-}
{-# LANGUAGE NegativeLiterals #-}
{-# LANGUAGE TypeOperators #-}
module DoubleNegation where
-- HLint doesn't parse the thing we're trying to test here, so shut it up.
#if !defined(__HLINT__)
import Data.Fin.Int (Fin)
import Data.Word (Word8)
import Data.Type.Equality ((:~:)(Refl))
import Data.SInt (SInt)
-- Turns out you can have both syntactic negation and a negative literal in the
-- same pattern/expression. We should not have a bug when doing that.
x0 :: Int -> String
x0 x = case x of
-1 -> "-1"
- -2 -> "2...?"
_ -> "_"
-- Make sure we in fact get proof for +2 out of matching on @- -2@.
x1 :: SInt n -> Maybe (n :~: 2)
x1 x = case x of
- -2 -> Just Refl
_ -> Nothing
x2 :: Word8
x2 = - -8
x3 :: Fin 5
x3 = - -4
x4 :: SInt 2 -> SInt 2
x4 x = case x of
- -2 -> x
_ -> x
#endif
|
google/hs-dependent-literals
|
dependent-literals-plugin/tests/DoubleNegation.hs
|
Haskell
|
apache-2.0
| 1,424
|
-- layout can still have explicit semicolons
f x = let a = 1
; b = 2
c = 3
in x
|
metaborg/jsglr
|
org.spoofax.jsglr/tests-offside/terms/doaitse/layout5.hs
|
Haskell
|
apache-2.0
| 106
|
{-| Implementation of the job queue.
-}
{-
Copyright (C) 2010, 2012 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.JQueue
( queuedOpCodeFromMetaOpCode
, queuedJobFromOpCodes
, changeOpCodePriority
, changeJobPriority
, cancelQueuedJob
, failQueuedJob
, fromClockTime
, noTimestamp
, currentTimestamp
, advanceTimestamp
, reasonTrailTimestamp
, setReceivedTimestamp
, extendJobReasonTrail
, getJobDependencies
, opStatusFinalized
, extractOpSummary
, calcJobStatus
, jobStarted
, jobFinalized
, jobArchivable
, calcJobPriority
, jobFileName
, liveJobFile
, archivedJobFile
, determineJobDirectories
, getJobIDs
, sortJobIDs
, loadJobFromDisk
, noSuchJob
, readSerialFromDisk
, allocateJobIds
, allocateJobId
, writeJobToDisk
, replicateManyJobs
, writeAndReplicateJob
, isQueueOpen
, startJobs
, cancelJob
, tellJobPriority
, notifyJob
, waitUntilJobExited
, queueDirPermissions
, archiveJobs
-- re-export
, Timestamp
, InputOpCode(..)
, QueuedOpCode(..)
, QueuedJob(..)
) where
import Control.Applicative (liftA2, (<|>))
import Control.Arrow (first, second)
import Control.Concurrent (forkIO, threadDelay)
import Control.Exception
import Control.Lens (over)
import Control.Monad
import Control.Monad.Fix
import Control.Monad.IO.Class
import Control.Monad.Trans (lift)
import Control.Monad.Trans.Maybe
import Data.List
import Data.Maybe
import Data.Ord (comparing)
-- workaround what seems to be a bug in ghc 7.4's TH shadowing code
import Prelude hiding (id, log)
import System.Directory
import System.FilePath
import System.IO.Error (isDoesNotExistError)
import System.Posix.Files
import System.Posix.Signals (sigHUP, sigTERM, sigUSR1, sigKILL, signalProcess)
import System.Posix.Types (ProcessID)
import System.Time
import qualified Text.JSON
import Text.JSON.Types
import Ganeti.BasicTypes
import qualified Ganeti.Config as Config
import qualified Ganeti.Constants as C
import Ganeti.Errors (ErrorResult, ResultG)
import Ganeti.JQueue.Lens (qoInputL, validOpCodeL)
import Ganeti.JQueue.Objects
import Ganeti.JSON (fromJResult, fromObjWithDefault)
import Ganeti.Logging
import Ganeti.Luxi
import Ganeti.Objects (ConfigData, Node)
import Ganeti.OpCodes
import Ganeti.OpCodes.Lens (metaParamsL, opReasonL)
import Ganeti.Path
import Ganeti.Query.Exec as Exec
import Ganeti.Rpc (executeRpcCall, ERpcError, logRpcErrors,
RpcCallJobqueueUpdate(..), RpcCallJobqueueRename(..))
import Ganeti.Runtime (GanetiDaemon(..), GanetiGroup(..), MiscGroup(..))
import Ganeti.Types
import Ganeti.Utils
import Ganeti.Utils.Atomic
import Ganeti.Utils.Livelock (Livelock, isDead)
import Ganeti.Utils.MVarLock
import Ganeti.VCluster (makeVirtualPath)
-- * Data types
-- | Missing timestamp type.
noTimestamp :: Timestamp
noTimestamp = (-1, -1)
-- | Obtain a Timestamp from a given clock time
fromClockTime :: ClockTime -> Timestamp
fromClockTime (TOD ctime pico) =
(fromIntegral ctime, fromIntegral $ pico `div` 1000000)
-- | Get the current time in the job-queue timestamp format.
currentTimestamp :: IO Timestamp
currentTimestamp = fromClockTime `liftM` getClockTime
-- | From a given timestamp, obtain the timestamp of the
-- time that is the given number of seconds later.
advanceTimestamp :: Int -> Timestamp -> Timestamp
advanceTimestamp = first . (+)
-- | From an InputOpCode obtain the MetaOpCode, if any.
toMetaOpCode :: InputOpCode -> [MetaOpCode]
toMetaOpCode (ValidOpCode mopc) = [mopc]
toMetaOpCode _ = []
-- | Invalid opcode summary.
invalidOp :: String
invalidOp = "INVALID_OP"
-- | Tries to extract the opcode summary from an 'InputOpCode'. This
-- duplicates some functionality from the 'opSummary' function in
-- "Ganeti.OpCodes".
extractOpSummary :: InputOpCode -> String
extractOpSummary (ValidOpCode metaop) = opSummary $ metaOpCode metaop
extractOpSummary (InvalidOpCode (JSObject o)) =
case fromObjWithDefault (fromJSObject o) "OP_ID" ("OP_" ++ invalidOp) of
Just s -> drop 3 s -- drop the OP_ prefix
Nothing -> invalidOp
extractOpSummary _ = invalidOp
-- | Convenience function to obtain a QueuedOpCode from a MetaOpCode
queuedOpCodeFromMetaOpCode :: MetaOpCode -> QueuedOpCode
queuedOpCodeFromMetaOpCode op =
QueuedOpCode { qoInput = ValidOpCode op
, qoStatus = OP_STATUS_QUEUED
, qoPriority = opSubmitPriorityToRaw . opPriority . metaParams
$ op
, qoLog = []
, qoResult = JSNull
, qoStartTimestamp = Nothing
, qoEndTimestamp = Nothing
, qoExecTimestamp = Nothing
}
-- | From a job-id and a list of op-codes create a job. This is
-- the pure part of job creation, as allocating a new job id
-- lives in IO.
queuedJobFromOpCodes :: (Monad m) => JobId -> [MetaOpCode] -> m QueuedJob
queuedJobFromOpCodes jobid ops = do
ops' <- mapM (`resolveDependencies` jobid) ops
return QueuedJob { qjId = jobid
, qjOps = map queuedOpCodeFromMetaOpCode ops'
, qjReceivedTimestamp = Nothing
, qjStartTimestamp = Nothing
, qjEndTimestamp = Nothing
, qjLivelock = Nothing
, qjProcessId = Nothing
}
-- | Attach a received timestamp to a Queued Job.
setReceivedTimestamp :: Timestamp -> QueuedJob -> QueuedJob
setReceivedTimestamp ts job = job { qjReceivedTimestamp = Just ts }
-- | Build a timestamp in the format expected by the reason trail (nanoseconds)
-- starting from a JQueue Timestamp.
reasonTrailTimestamp :: Timestamp -> Integer
reasonTrailTimestamp (sec, micro) =
let sec' = toInteger sec
micro' = toInteger micro
in sec' * 1000000000 + micro' * 1000
-- | Append an element to the reason trail of an input opcode.
extendInputOpCodeReasonTrail :: JobId -> Timestamp -> Int -> InputOpCode
-> InputOpCode
extendInputOpCodeReasonTrail _ _ _ op@(InvalidOpCode _) = op
extendInputOpCodeReasonTrail jid ts i (ValidOpCode vOp) =
let metaP = metaParams vOp
op = metaOpCode vOp
trail = opReason metaP
reasonSrc = opReasonSrcID op
reasonText = "job=" ++ show (fromJobId jid) ++ ";index=" ++ show i
reason = (reasonSrc, reasonText, reasonTrailTimestamp ts)
trail' = trail ++ [reason]
in ValidOpCode $ vOp { metaParams = metaP { opReason = trail' } }
-- | Append an element to the reason trail of a queued opcode.
extendOpCodeReasonTrail :: JobId -> Timestamp -> Int -> QueuedOpCode
-> QueuedOpCode
extendOpCodeReasonTrail jid ts i op =
let inOp = qoInput op
in op { qoInput = extendInputOpCodeReasonTrail jid ts i inOp }
-- | Append an element to the reason trail of all the OpCodes of a queued job.
extendJobReasonTrail :: QueuedJob -> QueuedJob
extendJobReasonTrail job =
let jobId = qjId job
mTimestamp = qjReceivedTimestamp job
-- This function is going to be called on QueuedJobs that already contain
-- a timestamp. But for safety reasons we cannot assume mTimestamp will
-- be (Just timestamp), so we use the value 0 in the extremely unlikely
-- case this is not true.
timestamp = fromMaybe (0, 0) mTimestamp
in job
{ qjOps =
zipWith (extendOpCodeReasonTrail jobId timestamp) [0..] $
qjOps job
}
-- | From a queued job obtain the list of jobs it depends on.
getJobDependencies :: QueuedJob -> [JobId]
getJobDependencies job = do
op <- qjOps job
mopc <- toMetaOpCode $ qoInput op
dep <- fromMaybe [] . opDepends $ metaParams mopc
getJobIdFromDependency dep
-- | Change the priority of a QueuedOpCode, if it is not already
-- finalized.
changeOpCodePriority :: Int -> QueuedOpCode -> QueuedOpCode
changeOpCodePriority prio op =
if qoStatus op > OP_STATUS_RUNNING
then op
else op { qoPriority = prio }
-- | Set the state of a QueuedOpCode to canceled.
cancelOpCode :: Timestamp -> QueuedOpCode -> QueuedOpCode
cancelOpCode now op =
op { qoStatus = OP_STATUS_CANCELED, qoEndTimestamp = Just now }
-- | Change the priority of a job, i.e., change the priority of the
-- non-finalized opcodes.
changeJobPriority :: Int -> QueuedJob -> QueuedJob
changeJobPriority prio job =
job { qjOps = map (changeOpCodePriority prio) $ qjOps job }
-- | Transform a QueuedJob that has not been started into its canceled form.
cancelQueuedJob :: Timestamp -> QueuedJob -> QueuedJob
cancelQueuedJob now job =
let ops' = map (cancelOpCode now) $ qjOps job
in job { qjOps = ops', qjEndTimestamp = Just now }
-- | Set the state of a QueuedOpCode to failed
-- and set the Op result using the given reason message.
failOpCode :: ReasonElem -> Timestamp -> QueuedOpCode -> QueuedOpCode
failOpCode reason@(_, msg, _) now op =
over (qoInputL . validOpCodeL . metaParamsL . opReasonL) (++ [reason])
op { qoStatus = OP_STATUS_ERROR
, qoResult = Text.JSON.JSString . Text.JSON.toJSString $ msg
, qoEndTimestamp = Just now }
-- | Transform a QueuedJob that has not been started into its failed form.
failQueuedJob :: ReasonElem -> Timestamp -> QueuedJob -> QueuedJob
failQueuedJob reason now job =
let ops' = map (failOpCode reason now) $ qjOps job
in job { qjOps = ops', qjEndTimestamp = Just now }
-- | Job file prefix.
jobFilePrefix :: String
jobFilePrefix = "job-"
-- | Computes the filename for a given job ID.
jobFileName :: JobId -> FilePath
jobFileName jid = jobFilePrefix ++ show (fromJobId jid)
-- | Parses a job ID from a file name.
parseJobFileId :: (Monad m) => FilePath -> m JobId
parseJobFileId path =
case stripPrefix jobFilePrefix path of
Nothing -> fail $ "Job file '" ++ path ++
"' doesn't have the correct prefix"
Just suffix -> makeJobIdS suffix
-- | Computes the full path to a live job.
liveJobFile :: FilePath -> JobId -> FilePath
liveJobFile rootdir jid = rootdir </> jobFileName jid
-- | Computes the full path to an archives job. BROKEN.
archivedJobFile :: FilePath -> JobId -> FilePath
archivedJobFile rootdir jid =
let subdir = show (fromJobId jid `div` C.jstoreJobsPerArchiveDirectory)
in rootdir </> jobQueueArchiveSubDir </> subdir </> jobFileName jid
-- | Map from opcode status to job status.
opStatusToJob :: OpStatus -> JobStatus
opStatusToJob OP_STATUS_QUEUED = JOB_STATUS_QUEUED
opStatusToJob OP_STATUS_WAITING = JOB_STATUS_WAITING
opStatusToJob OP_STATUS_SUCCESS = JOB_STATUS_SUCCESS
opStatusToJob OP_STATUS_RUNNING = JOB_STATUS_RUNNING
opStatusToJob OP_STATUS_CANCELING = JOB_STATUS_CANCELING
opStatusToJob OP_STATUS_CANCELED = JOB_STATUS_CANCELED
opStatusToJob OP_STATUS_ERROR = JOB_STATUS_ERROR
-- | Computes a queued job's status.
calcJobStatus :: QueuedJob -> JobStatus
calcJobStatus QueuedJob { qjOps = ops } =
extractOpSt (map qoStatus ops) JOB_STATUS_QUEUED True
where
terminalStatus OP_STATUS_ERROR = True
terminalStatus OP_STATUS_CANCELING = True
terminalStatus OP_STATUS_CANCELED = True
terminalStatus _ = False
softStatus OP_STATUS_SUCCESS = True
softStatus OP_STATUS_QUEUED = True
softStatus _ = False
extractOpSt [] _ True = JOB_STATUS_SUCCESS
extractOpSt [] d False = d
extractOpSt (x:xs) d old_all
| terminalStatus x = opStatusToJob x -- abort recursion
| softStatus x = extractOpSt xs d new_all -- continue unchanged
| otherwise = extractOpSt xs (opStatusToJob x) new_all
where new_all = x == OP_STATUS_SUCCESS && old_all
-- | Determine if a job has started
jobStarted :: QueuedJob -> Bool
jobStarted = (> JOB_STATUS_QUEUED) . calcJobStatus
-- | Determine if a job is finalised.
jobFinalized :: QueuedJob -> Bool
jobFinalized = (> JOB_STATUS_RUNNING) . calcJobStatus
-- | Determine if a job is finalized and its timestamp is before
-- a given time.
jobArchivable :: Timestamp -> QueuedJob -> Bool
jobArchivable ts = liftA2 (&&) jobFinalized
$ maybe False (< ts)
. liftA2 (<|>) qjEndTimestamp qjStartTimestamp
-- | Determine whether an opcode status is finalized.
opStatusFinalized :: OpStatus -> Bool
opStatusFinalized = (> OP_STATUS_RUNNING)
-- | Compute a job's priority.
calcJobPriority :: QueuedJob -> Int
calcJobPriority QueuedJob { qjOps = ops } =
helper . map qoPriority $ filter (not . opStatusFinalized . qoStatus) ops
where helper [] = C.opPrioDefault
helper ps = minimum ps
-- | Log but ignore an 'IOError'.
ignoreIOError :: a -> Bool -> String -> IOError -> IO a
ignoreIOError a ignore_noent msg e = do
unless (isDoesNotExistError e && ignore_noent) .
logWarning $ msg ++ ": " ++ show e
return a
-- | Compute the list of existing archive directories. Note that I/O
-- exceptions are swallowed and ignored.
allArchiveDirs :: FilePath -> IO [FilePath]
allArchiveDirs rootdir = do
let adir = rootdir </> jobQueueArchiveSubDir
contents <- getDirectoryContents adir `Control.Exception.catch`
ignoreIOError [] False
("Failed to list queue directory " ++ adir)
let fpaths = map (adir </>) $ filter (not . ("." `isPrefixOf`)) contents
filterM (\path ->
liftM isDirectory (getFileStatus (adir </> path))
`Control.Exception.catch`
ignoreIOError False True
("Failed to stat archive path " ++ path)) fpaths
-- | Build list of directories containing job files. Note: compared to
-- the Python version, this doesn't ignore a potential lost+found
-- file.
determineJobDirectories :: FilePath -> Bool -> IO [FilePath]
determineJobDirectories rootdir archived = do
other <- if archived
then allArchiveDirs rootdir
else return []
return $ rootdir:other
-- | Computes the list of all jobs in the given directories.
getJobIDs :: [FilePath] -> IO (GenericResult IOError [JobId])
getJobIDs = runResultT . liftM concat . mapM getDirJobIDs
-- | Sorts the a list of job IDs.
sortJobIDs :: [JobId] -> [JobId]
sortJobIDs = sortBy (comparing fromJobId)
-- | Computes the list of jobs in a given directory.
getDirJobIDs :: FilePath -> ResultT IOError IO [JobId]
getDirJobIDs path =
withErrorLogAt WARNING ("Failed to list job directory " ++ path) .
liftM (mapMaybe parseJobFileId) $ liftIO (getDirectoryContents path)
-- | Reads the job data from disk.
readJobDataFromDisk :: FilePath -> Bool -> JobId -> IO (Maybe (String, Bool))
readJobDataFromDisk rootdir archived jid = do
let live_path = liveJobFile rootdir jid
archived_path = archivedJobFile rootdir jid
all_paths = if archived
then [(live_path, False), (archived_path, True)]
else [(live_path, False)]
foldM (\state (path, isarchived) ->
liftM (\r -> Just (r, isarchived)) (readFile path)
`Control.Exception.catch`
ignoreIOError state True
("Failed to read job file " ++ path)) Nothing all_paths
-- | Failed to load job error.
noSuchJob :: Result (QueuedJob, Bool)
noSuchJob = Bad "Can't load job file"
-- | Loads a job from disk.
loadJobFromDisk :: FilePath -> Bool -> JobId -> IO (Result (QueuedJob, Bool))
loadJobFromDisk rootdir archived jid = do
raw <- readJobDataFromDisk rootdir archived jid
-- note: we need some stricness below, otherwise the wrapping in a
-- Result will create too much lazyness, and not close the file
-- descriptors for the individual jobs
return $! case raw of
Nothing -> noSuchJob
Just (str, arch) ->
liftM (\qj -> (qj, arch)) .
fromJResult "Parsing job file" $ Text.JSON.decode str
-- | Write a job to disk.
writeJobToDisk :: FilePath -> QueuedJob -> IO (Result ())
writeJobToDisk rootdir job = do
let filename = liveJobFile rootdir . qjId $ job
content = Text.JSON.encode . Text.JSON.showJSON $ job
tryAndLogIOError (atomicWriteFile filename content)
("Failed to write " ++ filename) Ok
-- | Replicate a job to all master candidates.
replicateJob :: FilePath -> [Node] -> QueuedJob -> IO [(Node, ERpcError ())]
replicateJob rootdir mastercandidates job = do
let filename = liveJobFile rootdir . qjId $ job
content = Text.JSON.encode . Text.JSON.showJSON $ job
filename' <- makeVirtualPath filename
callresult <- executeRpcCall mastercandidates
$ RpcCallJobqueueUpdate filename' content
let result = map (second (() <$)) callresult
_ <- logRpcErrors result
return result
-- | Replicate many jobs to all master candidates.
replicateManyJobs :: FilePath -> [Node] -> [QueuedJob] -> IO ()
replicateManyJobs rootdir mastercandidates =
mapM_ (replicateJob rootdir mastercandidates)
-- | Writes a job to a file and replicates it to master candidates.
writeAndReplicateJob :: (Error e)
=> ConfigData -> FilePath -> QueuedJob
-> ResultT e IO [(Node, ERpcError ())]
writeAndReplicateJob cfg rootdir job = do
mkResultT $ writeJobToDisk rootdir job
liftIO $ replicateJob rootdir (Config.getMasterCandidates cfg) job
-- | Read the job serial number from disk.
readSerialFromDisk :: IO (Result JobId)
readSerialFromDisk = do
filename <- jobQueueSerialFile
tryAndLogIOError (readFile filename) "Failed to read serial file"
(makeJobIdS . rStripSpace)
-- | Allocate new job ids.
-- To avoid races while accessing the serial file, the threads synchronize
-- over a lock, as usual provided by a Lock.
allocateJobIds :: [Node] -> Lock -> Int -> IO (Result [JobId])
allocateJobIds mastercandidates lock n =
if n <= 0
then if n == 0
then return $ Ok []
else return . Bad
$ "Can only allocate non-negative number of job ids"
else withLock lock $ do
rjobid <- readSerialFromDisk
case rjobid of
Bad s -> return . Bad $ s
Ok jid -> do
let current = fromJobId jid
serial_content = show (current + n) ++ "\n"
serial <- jobQueueSerialFile
write_result <- try $ atomicWriteFile serial serial_content
:: IO (Either IOError ())
case write_result of
Left e -> do
let msg = "Failed to write serial file: " ++ show e
logError msg
return . Bad $ msg
Right () -> do
serial' <- makeVirtualPath serial
_ <- executeRpcCall mastercandidates
$ RpcCallJobqueueUpdate serial' serial_content
return $ mapM makeJobId [(current+1)..(current+n)]
-- | Allocate one new job id.
allocateJobId :: [Node] -> Lock -> IO (Result JobId)
allocateJobId mastercandidates lock = do
jids <- allocateJobIds mastercandidates lock 1
return (jids >>= monadicThe "Failed to allocate precisely one Job ID")
-- | Decide if job queue is open
isQueueOpen :: IO Bool
isQueueOpen = liftM not (jobQueueDrainFile >>= doesFileExist)
-- | Start enqueued jobs by executing the Python code.
startJobs :: Livelock -- ^ Luxi's livelock path
-> Lock -- ^ lock for forking new processes
-> [QueuedJob] -- ^ the list of jobs to start
-> IO [ErrorResult QueuedJob]
startJobs luxiLivelock forkLock jobs = do
qdir <- queueDir
let updateJob job llfile =
void . mkResultT . writeJobToDisk qdir
$ job { qjLivelock = Just llfile }
let runJob job = withLock forkLock $ do
(llfile, _) <- Exec.forkJobProcess job luxiLivelock
(updateJob job)
return $ job { qjLivelock = Just llfile }
mapM (runResultT . runJob) jobs
-- | Try to prove that a queued job is dead. This function needs to know
-- the livelock of the caller (i.e., luxid) to avoid considering a job dead
-- that is in the process of forking off.
isQueuedJobDead :: MonadIO m => Livelock -> QueuedJob -> m Bool
isQueuedJobDead ownlivelock =
maybe (return False) (liftIO . isDead)
. mfilter (/= ownlivelock)
. qjLivelock
-- | Waits for a job's process to exit
waitUntilJobExited :: Livelock -- ^ LuxiD's own livelock
-> QueuedJob -- ^ the job to wait for
-> Int -- ^ timeout in milliseconds
-> ResultG (Bool, String)
waitUntilJobExited ownlivelock job tmout = do
let sleepDelay = 100 :: Int -- ms
jName = ("Job " ++) . show . fromJobId . qjId $ job
logDebug $ "Waiting for " ++ jName ++ " to exit"
start <- liftIO getClockTime
let tmoutPicosec :: Integer
tmoutPicosec = fromIntegral $ tmout * 1000 * 1000 * 1000
wait = noTimeDiff { tdPicosec = tmoutPicosec }
deadline = addToClockTime wait start
liftIO . fix $ \loop -> do
-- fail if the job is in the startup phase or has no livelock
dead <- maybe (fail $ jName ++ " has not yet started up")
(liftIO . isDead) . mfilter (/= ownlivelock) . qjLivelock $ job
curtime <- getClockTime
let elapsed = timeDiffToString $ System.Time.diffClockTimes
curtime start
case dead of
True -> return (True, jName ++ " process exited after " ++ elapsed)
_ | curtime < deadline -> threadDelay (sleepDelay * 1000) >> loop
_ -> fail $ jName ++ " still running after " ++ elapsed
-- | Waits for a job ordered to cancel to react, and returns whether it was
-- canceled, and a user-intended description of the reason.
waitForJobCancelation :: JobId -> Int -> ResultG (Bool, String)
waitForJobCancelation jid tmout = do
qDir <- liftIO queueDir
let jobfile = liveJobFile qDir jid
load = liftM fst <$> loadJobFromDisk qDir False jid
finalizedR = genericResult (const False) jobFinalized
jobR <- liftIO $ watchFileBy jobfile tmout finalizedR load
case calcJobStatus <$> jobR of
Ok s | s == JOB_STATUS_CANCELED ->
return (True, "Job successfully cancelled")
| finalizedR jobR ->
return (False, "Job exited before it could have been canceled,\
\ status " ++ show s)
| otherwise ->
return (False, "Job could not be canceled, status "
++ show s)
Bad e -> failError $ "Can't read job status: " ++ e
-- | Try to cancel a job that has already been handed over to execution,
-- by terminating the process.
cancelJob :: Bool -- ^ if True, use sigKILL instead of sigTERM
-> Livelock -- ^ Luxi's livelock path
-> JobId -- ^ the job to cancel
-> IO (ErrorResult (Bool, String))
cancelJob kill luxiLivelock jid = runResultT $ do
-- we can't terminate the job if it's just being started, so
-- retry several times in such a case
result <- runMaybeT . msum . flip map [0..5 :: Int] $ \tryNo -> do
-- if we're retrying, sleep for some time
when (tryNo > 0) . liftIO . threadDelay $ 100000 * (2 ^ tryNo)
-- first check if the job is alive so that we don't kill some other
-- process by accident
qDir <- liftIO queueDir
(job, _) <- lift . mkResultT $ loadJobFromDisk qDir True jid
let jName = ("Job " ++) . show . fromJobId . qjId $ job
dead <- isQueuedJobDead luxiLivelock job
case qjProcessId job of
_ | dead ->
return (True, jName ++ " has been already dead")
Just pid -> do
liftIO $ signalProcess (if kill then sigKILL else sigTERM) pid
if not kill then
if calcJobStatus job > JOB_STATUS_WAITING
then return (False, "Job no longer waiting, can't cancel\
\ (informed it anyway)")
else lift $ waitForJobCancelation jid C.luxiCancelJobTimeout
else return (True, "SIGKILL send to the process")
_ -> do
logDebug $ jName ++ " in its startup phase, retrying"
mzero
return $ fromMaybe (False, "Timeout: job still in its startup phase") result
-- | Inform a job that it is requested to change its priority. This is done
-- by writing the new priority to a file and sending SIGUSR1.
tellJobPriority :: Livelock -- ^ Luxi's livelock path
-> JobId -- ^ the job to inform
-> Int -- ^ the new priority
-> IO (ErrorResult (Bool, String))
tellJobPriority luxiLivelock jid prio = runResultT $ do
let jidS = show $ fromJobId jid
jName = "Job " ++ jidS
mDir <- liftIO luxidMessageDir
let prioFile = mDir </> jidS ++ ".prio"
liftIO . atomicWriteFile prioFile $ show prio
qDir <- liftIO queueDir
(job, _) <- mkResultT $ loadJobFromDisk qDir True jid
dead <- isQueuedJobDead luxiLivelock job
case qjProcessId job of
_ | dead -> do
liftIO $ removeFile prioFile
return (False, jName ++ " is dead")
Just pid -> do
liftIO $ signalProcess sigUSR1 pid
return (True, jName ++ " with pid " ++ show pid ++ " signaled")
_ -> return (False, jName ++ "'s pid unknown")
-- | Notify a job that something relevant happened, e.g., a lock became
-- available. We do this by sending sigHUP to the process.
notifyJob :: ProcessID -> IO (ErrorResult ())
notifyJob pid = runResultT $ do
logDebug $ "Signalling process " ++ show pid
liftIO $ signalProcess sigHUP pid
-- | Permissions for the archive directories.
queueDirPermissions :: FilePermissions
queueDirPermissions = FilePermissions { fpOwner = Just GanetiMasterd
, fpGroup = Just $ ExtraGroup DaemonsGroup
, fpPermissions = 0o0750
}
-- | Try, at most until the given endtime, to archive some of the given
-- jobs, if they are older than the specified cut-off time; also replicate
-- archival of the additional jobs. Return the pair of the number of jobs
-- archived, and the number of jobs remaining int he queue, asuming the
-- given numbers about the not considered jobs.
archiveSomeJobsUntil :: ([JobId] -> IO ()) -- ^ replication function
-> FilePath -- ^ queue root directory
-> ClockTime -- ^ Endtime
-> Timestamp -- ^ cut-off time for archiving jobs
-> Int -- ^ number of jobs alread archived
-> [JobId] -- ^ Additional jobs to replicate
-> [JobId] -- ^ List of job-ids still to consider
-> IO (Int, Int)
archiveSomeJobsUntil replicateFn _ _ _ arch torepl [] = do
unless (null torepl) . (>> return ())
. forkIO $ replicateFn torepl
return (arch, 0)
archiveSomeJobsUntil replicateFn qDir endt cutt arch torepl (jid:jids) = do
let archiveMore = archiveSomeJobsUntil replicateFn qDir endt cutt
continue = archiveMore arch torepl jids
jidname = show $ fromJobId jid
time <- getClockTime
if time >= endt
then do
_ <- forkIO $ replicateFn torepl
return (arch, length (jid:jids))
else do
logDebug $ "Inspecting job " ++ jidname ++ " for archival"
loadResult <- loadJobFromDisk qDir False jid
case loadResult of
Bad _ -> continue
Ok (job, _) ->
if jobArchivable cutt job
then do
let live = liveJobFile qDir jid
archive = archivedJobFile qDir jid
renameResult <- safeRenameFile queueDirPermissions
live archive
case renameResult of
Bad s -> do
logWarning $ "Renaming " ++ live ++ " to " ++ archive
++ " failed unexpectedly: " ++ s
continue
Ok () -> do
let torepl' = jid:torepl
if length torepl' >= 10
then do
_ <- forkIO $ replicateFn torepl'
archiveMore (arch + 1) [] jids
else archiveMore (arch + 1) torepl' jids
else continue
-- | Archive jobs older than the given time, but do not exceed the timeout for
-- carrying out this task.
archiveJobs :: ConfigData -- ^ cluster configuration
-> Int -- ^ time the job has to be in the past in order
-- to be archived
-> Int -- ^ timeout
-> [JobId] -- ^ jobs to consider
-> IO (Int, Int)
archiveJobs cfg age timeout jids = do
now <- getClockTime
qDir <- queueDir
let endtime = addToClockTime (noTimeDiff { tdSec = timeout }) now
cuttime = if age < 0 then noTimestamp
else advanceTimestamp (- age) (fromClockTime now)
mcs = Config.getMasterCandidates cfg
replicateFn jobs = do
let olds = map (liveJobFile qDir) jobs
news = map (archivedJobFile qDir) jobs
_ <- executeRpcCall mcs . RpcCallJobqueueRename $ zip olds news
return ()
archiveSomeJobsUntil replicateFn qDir endtime cuttime 0 [] jids
|
mbakke/ganeti
|
src/Ganeti/JQueue.hs
|
Haskell
|
bsd-2-clause
| 30,285
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGraphicsEllipseItem_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:27
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QGraphicsEllipseItem_h where
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QGraphicsItem
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QGraphicsEllipseItem ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QGraphicsEllipseItem_unSetUserMethod" qtc_QGraphicsEllipseItem_unSetUserMethod :: Ptr (TQGraphicsEllipseItem a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QGraphicsEllipseItemSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QGraphicsEllipseItem ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QGraphicsEllipseItemSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QGraphicsEllipseItem ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QGraphicsEllipseItemSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGraphicsEllipseItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGraphicsEllipseItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsEllipseItem_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setUserMethod" qtc_QGraphicsEllipseItem_setUserMethod :: Ptr (TQGraphicsEllipseItem a) -> CInt -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsEllipseItem :: (Ptr (TQGraphicsEllipseItem x0) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsEllipseItem_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGraphicsEllipseItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGraphicsEllipseItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsEllipseItem_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGraphicsEllipseItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGraphicsEllipseItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsEllipseItem_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setUserMethodVariant" qtc_QGraphicsEllipseItem_setUserMethodVariant :: Ptr (TQGraphicsEllipseItem a) -> CInt -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsEllipseItem :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsEllipseItem_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGraphicsEllipseItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGraphicsEllipseItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsEllipseItem_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGraphicsEllipseItem_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QGraphicsEllipseItem_unSetHandler" qtc_QGraphicsEllipseItem_unSetHandler :: Ptr (TQGraphicsEllipseItem a) -> CWString -> IO (CBool)
instance QunSetHandler (QGraphicsEllipseItemSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGraphicsEllipseItem_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> IO (QRectF t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQRectF t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler1" qtc_QGraphicsEllipseItem_setHandler1 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQRectF t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem1 :: (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQRectF t0))) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQRectF t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> IO (QRectF t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQRectF t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqqboundingRect_h (QGraphicsEllipseItem ()) (()) where
qqboundingRect_h x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_boundingRect cobj_x0
foreign import ccall "qtc_QGraphicsEllipseItem_boundingRect" qtc_QGraphicsEllipseItem_boundingRect :: Ptr (TQGraphicsEllipseItem a) -> IO (Ptr (TQRectF ()))
instance QqqboundingRect_h (QGraphicsEllipseItemSc a) (()) where
qqboundingRect_h x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_boundingRect cobj_x0
instance QqboundingRect_h (QGraphicsEllipseItem ()) (()) where
qboundingRect_h x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
foreign import ccall "qtc_QGraphicsEllipseItem_boundingRect_qth" qtc_QGraphicsEllipseItem_boundingRect_qth :: Ptr (TQGraphicsEllipseItem a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QqboundingRect_h (QGraphicsEllipseItemSc a) (()) where
qboundingRect_h x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QPointF t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPointF t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsEllipseItem_setHandler2" qtc_QGraphicsEllipseItem_setHandler2 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem2 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPointF t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QPointF t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPointF t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 Qqcontains_h (QGraphicsEllipseItem ()) ((PointF)) where
qcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsEllipseItem_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y
foreign import ccall "qtc_QGraphicsEllipseItem_contains_qth" qtc_QGraphicsEllipseItem_contains_qth :: Ptr (TQGraphicsEllipseItem a) -> CDouble -> CDouble -> IO CBool
instance Qqcontains_h (QGraphicsEllipseItemSc a) ((PointF)) where
qcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsEllipseItem_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y
instance Qqqcontains_h (QGraphicsEllipseItem ()) ((QPointF t1)) where
qqcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_contains cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_contains" qtc_QGraphicsEllipseItem_contains :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQPointF t1) -> IO CBool
instance Qqqcontains_h (QGraphicsEllipseItemSc a) ((QPointF t1)) where
qqcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_contains cobj_x0 cobj_x1
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsEllipseItem_setHandler3" qtc_QGraphicsEllipseItem_setHandler3 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem3 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr 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_QGraphicsEllipseItem_setHandler4" qtc_QGraphicsEllipseItem_setHandler4 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem4 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr 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 QisObscuredBy_h (QGraphicsEllipseItem ()) ((QGraphicsItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_isObscuredBy cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_isObscuredBy" qtc_QGraphicsEllipseItem_isObscuredBy :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QisObscuredBy_h (QGraphicsEllipseItemSc a) ((QGraphicsItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_isObscuredBy cobj_x0 cobj_x1
instance QisObscuredBy_h (QGraphicsEllipseItem ()) ((QGraphicsTextItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_isObscuredBy_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_isObscuredBy_graphicstextitem" qtc_QGraphicsEllipseItem_isObscuredBy_graphicstextitem :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QisObscuredBy_h (QGraphicsEllipseItemSc a) ((QGraphicsTextItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_isObscuredBy_graphicstextitem cobj_x0 cobj_x1
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> IO (QPainterPath t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQPainterPath t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler5" qtc_QGraphicsEllipseItem_setHandler5 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQPainterPath t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem5 :: (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQPainterPath t0))) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQPainterPath t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> IO (QPainterPath t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQPainterPath t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QopaqueArea_h (QGraphicsEllipseItem ()) (()) where
opaqueArea_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_opaqueArea cobj_x0
foreign import ccall "qtc_QGraphicsEllipseItem_opaqueArea" qtc_QGraphicsEllipseItem_opaqueArea :: Ptr (TQGraphicsEllipseItem a) -> IO (Ptr (TQPainterPath ()))
instance QopaqueArea_h (QGraphicsEllipseItemSc a) (()) where
opaqueArea_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_opaqueArea cobj_x0
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- qObjectFromPtr x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
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_QGraphicsEllipseItem_setHandler6" qtc_QGraphicsEllipseItem_setHandler6 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem6 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- qObjectFromPtr x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
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 Qpaint_h (QGraphicsEllipseItem ()) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where
paint_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGraphicsEllipseItem_paint1 cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QGraphicsEllipseItem_paint1" qtc_QGraphicsEllipseItem_paint1 :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionGraphicsItem t2) -> Ptr (TQWidget t3) -> IO ()
instance Qpaint_h (QGraphicsEllipseItemSc a) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where
paint_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGraphicsEllipseItem_paint1 cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance Qshape_h (QGraphicsEllipseItem ()) (()) where
shape_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_shape cobj_x0
foreign import ccall "qtc_QGraphicsEllipseItem_shape" qtc_QGraphicsEllipseItem_shape :: Ptr (TQGraphicsEllipseItem a) -> IO (Ptr (TQPainterPath ()))
instance Qshape_h (QGraphicsEllipseItemSc a) (()) where
shape_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_shape cobj_x0
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler7" qtc_QGraphicsEllipseItem_setHandler7 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem7 :: (Ptr (TQGraphicsEllipseItem x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qqtype_h (QGraphicsEllipseItem ()) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_type cobj_x0
foreign import ccall "qtc_QGraphicsEllipseItem_type" qtc_QGraphicsEllipseItem_type :: Ptr (TQGraphicsEllipseItem a) -> IO CInt
instance Qqtype_h (QGraphicsEllipseItemSc a) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_type cobj_x0
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> CInt -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1int = fromCInt x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler8" qtc_QGraphicsEllipseItem_setHandler8 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem8 :: (Ptr (TQGraphicsEllipseItem x0) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> CInt -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1int = fromCInt x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qadvance_h (QGraphicsEllipseItem ()) ((Int)) where
advance_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_advance cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGraphicsEllipseItem_advance" qtc_QGraphicsEllipseItem_advance :: Ptr (TQGraphicsEllipseItem a) -> CInt -> IO ()
instance Qadvance_h (QGraphicsEllipseItemSc a) ((Int)) where
advance_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_advance cobj_x0 (toCInt x1)
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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_QGraphicsEllipseItem_setHandler9" qtc_QGraphicsEllipseItem_setHandler9 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem9 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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 QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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_QGraphicsEllipseItem_setHandler10" qtc_QGraphicsEllipseItem_setHandler10 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem10 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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 QcollidesWithItem_h (QGraphicsEllipseItem ()) ((QGraphicsItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithItem" qtc_QGraphicsEllipseItem_collidesWithItem :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QcollidesWithItem_h (QGraphicsEllipseItemSc a) ((QGraphicsItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem cobj_x0 cobj_x1
instance QcollidesWithItem_h (QGraphicsEllipseItem ()) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithItem1" qtc_QGraphicsEllipseItem_collidesWithItem1 :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsItem t1) -> CLong -> IO CBool
instance QcollidesWithItem_h (QGraphicsEllipseItemSc a) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcollidesWithItem_h (QGraphicsEllipseItem ()) ((QGraphicsTextItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithItem_graphicstextitem" qtc_QGraphicsEllipseItem_collidesWithItem_graphicstextitem :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QcollidesWithItem_h (QGraphicsEllipseItemSc a) ((QGraphicsTextItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem_graphicstextitem cobj_x0 cobj_x1
instance QcollidesWithItem_h (QGraphicsEllipseItem ()) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithItem1_graphicstextitem" qtc_QGraphicsEllipseItem_collidesWithItem1_graphicstextitem :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsTextItem t1) -> CLong -> IO CBool
instance QcollidesWithItem_h (QGraphicsEllipseItemSc a) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QPainterPath t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsEllipseItem_setHandler11" qtc_QGraphicsEllipseItem_setHandler11 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem11 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QPainterPath t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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_QGraphicsEllipseItem_setHandler12" qtc_QGraphicsEllipseItem_setHandler12 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem12 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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 QcollidesWithPath_h (QGraphicsEllipseItem ()) ((QPainterPath t1)) where
collidesWithPath_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithPath cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithPath" qtc_QGraphicsEllipseItem_collidesWithPath :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQPainterPath t1) -> IO CBool
instance QcollidesWithPath_h (QGraphicsEllipseItemSc a) ((QPainterPath t1)) where
collidesWithPath_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithPath cobj_x0 cobj_x1
instance QcollidesWithPath_h (QGraphicsEllipseItem ()) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithPath1" qtc_QGraphicsEllipseItem_collidesWithPath1 :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQPainterPath t1) -> CLong -> IO CBool
instance QcollidesWithPath_h (QGraphicsEllipseItemSc a) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler13" qtc_QGraphicsEllipseItem_setHandler13 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem13 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QcontextMenuEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_contextMenuEvent" qtc_QGraphicsEllipseItem_contextMenuEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_contextMenuEvent cobj_x0 cobj_x1
instance QdragEnterEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_dragEnterEvent" qtc_QGraphicsEllipseItem_dragEnterEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragEnterEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_dragLeaveEvent" qtc_QGraphicsEllipseItem_dragLeaveEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragLeaveEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_dragMoveEvent" qtc_QGraphicsEllipseItem_dragMoveEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragMoveEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_dropEvent" qtc_QGraphicsEllipseItem_dropEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdropEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dropEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QGraphicsEllipseItem ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_focusInEvent" qtc_QGraphicsEllipseItem_focusInEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QGraphicsEllipseItemSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QGraphicsEllipseItem ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_focusOutEvent" qtc_QGraphicsEllipseItem_focusOutEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QGraphicsEllipseItemSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_focusOutEvent cobj_x0 cobj_x1
instance QhoverEnterEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_hoverEnterEvent" qtc_QGraphicsEllipseItem_hoverEnterEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverEnterEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverEnterEvent cobj_x0 cobj_x1
instance QhoverLeaveEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_hoverLeaveEvent" qtc_QGraphicsEllipseItem_hoverLeaveEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverLeaveEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverLeaveEvent cobj_x0 cobj_x1
instance QhoverMoveEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_hoverMoveEvent" qtc_QGraphicsEllipseItem_hoverMoveEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverMoveEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverMoveEvent cobj_x0 cobj_x1
instance QinputMethodEvent_h (QGraphicsEllipseItem ()) ((QInputMethodEvent t1)) where
inputMethodEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_inputMethodEvent" qtc_QGraphicsEllipseItem_inputMethodEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent_h (QGraphicsEllipseItemSc a) ((QInputMethodEvent t1)) where
inputMethodEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_inputMethodEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler14" qtc_QGraphicsEllipseItem_setHandler14 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem14 :: (Ptr (TQGraphicsEllipseItem x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QinputMethodQuery_h (QGraphicsEllipseItem ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsEllipseItem_inputMethodQuery" qtc_QGraphicsEllipseItem_inputMethodQuery :: Ptr (TQGraphicsEllipseItem a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QGraphicsEllipseItemSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum x2obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler15" qtc_QGraphicsEllipseItem_setHandler15 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem15 :: (Ptr (TQGraphicsEllipseItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem15_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum x2obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QitemChange_h (QGraphicsEllipseItem ()) ((GraphicsItemChange, QVariant t2)) where
itemChange_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsEllipseItem_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
foreign import ccall "qtc_QGraphicsEllipseItem_itemChange" qtc_QGraphicsEllipseItem_itemChange :: Ptr (TQGraphicsEllipseItem a) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant ()))
instance QitemChange_h (QGraphicsEllipseItemSc a) ((GraphicsItemChange, QVariant t2)) where
itemChange_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsEllipseItem_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
instance QkeyPressEvent_h (QGraphicsEllipseItem ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_keyPressEvent" qtc_QGraphicsEllipseItem_keyPressEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QGraphicsEllipseItemSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_keyPressEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QGraphicsEllipseItem ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_keyReleaseEvent" qtc_QGraphicsEllipseItem_keyReleaseEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QGraphicsEllipseItemSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_keyReleaseEvent cobj_x0 cobj_x1
instance QmouseDoubleClickEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_mouseDoubleClickEvent" qtc_QGraphicsEllipseItem_mouseDoubleClickEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_mouseMoveEvent" qtc_QGraphicsEllipseItem_mouseMoveEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_mousePressEvent" qtc_QGraphicsEllipseItem_mousePressEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_mouseReleaseEvent" qtc_QGraphicsEllipseItem_mouseReleaseEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseReleaseEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsEllipseItem_setHandler16" qtc_QGraphicsEllipseItem_setHandler16 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem16 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem16_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 QsceneEvent_h (QGraphicsEllipseItem ()) ((QEvent t1)) where
sceneEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_sceneEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_sceneEvent" qtc_QGraphicsEllipseItem_sceneEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQEvent t1) -> IO CBool
instance QsceneEvent_h (QGraphicsEllipseItemSc a) ((QEvent t1)) where
sceneEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_sceneEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf 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_QGraphicsEllipseItem_setHandler17" qtc_QGraphicsEllipseItem_setHandler17 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem17 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem17_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf 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 QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf 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_QGraphicsEllipseItem_setHandler18" qtc_QGraphicsEllipseItem_setHandler18 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem18 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem18_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf 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 QsceneEventFilter_h (QGraphicsEllipseItem ()) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsEllipseItem_sceneEventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsEllipseItem_sceneEventFilter" qtc_QGraphicsEllipseItem_sceneEventFilter :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter_h (QGraphicsEllipseItemSc a) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsEllipseItem_sceneEventFilter cobj_x0 cobj_x1 cobj_x2
instance QsceneEventFilter_h (QGraphicsEllipseItem ()) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsEllipseItem_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsEllipseItem_sceneEventFilter_graphicstextitem" qtc_QGraphicsEllipseItem_sceneEventFilter_graphicstextitem :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter_h (QGraphicsEllipseItemSc a) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsEllipseItem_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2
instance QwheelEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_wheelEvent" qtc_QGraphicsEllipseItem_wheelEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneWheelEvent t1) -> IO ()
instance QwheelEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_wheelEvent cobj_x0 cobj_x1
|
uduki/hsQt
|
Qtc/Gui/QGraphicsEllipseItem_h.hs
|
Haskell
|
bsd-2-clause
| 100,132
|
-- | This module provides the type of an (abstract) object.
module Jat.PState.Object
(
Object (..)
, className
, fieldTable
, isInstance
, mapValuesO
, referencesO
, FieldTable
, elemsFT
, updateFT
, emptyFT
, lookupFT
, assocsFT
)
where
import Jat.PState.AbstrValue
import Jat.Utils.Pretty
import qualified Jinja.Program as P
import Data.Char (toLower)
import Data.Maybe (fromMaybe)
import qualified Data.Map as M
-- | A 'FieldTable' maps pairs of class name and field name to abstract values.
type FieldTable i = M.Map (P.ClassId, P.FieldId) (AbstrValue i)
-- | An 'Object' may be a concrete instance or an abstract variable.
data Object i =
Instance P.ClassId (FieldTable i)
| AbsVar P.ClassId
deriving (Show)
-- | Returns the class name of an object.
className :: Object i -> P.ClassId
className (Instance cn _) = cn
className (AbsVar cn) = cn
-- | Returns the field table of an object.
fieldTable :: Object i -> FieldTable i
fieldTable (Instance _ ft) = ft
fieldTable _ = error "assert: illegal access to fieldtable"
-- | Checks if the object is an conrete instance.
isInstance :: Object i -> Bool
isInstance (Instance _ _) = True
isInstance _ = False
-- | Maps a value function over the object.
mapValuesO :: (AbstrValue i -> AbstrValue i) -> Object i -> Object i
mapValuesO f (Instance cn ft) = Instance cn (M.map f ft)
mapValuesO _ var = var
-- | Returns the the addresses stored in an 'Object'.
referencesO :: Object i -> [Address]
referencesO (Instance _ ft) = [ ref | RefVal ref <- M.elems ft ]
referencesO (AbsVar _) = []
-- | Returns an aempty field table.
emptyFT :: FieldTable i
emptyFT = M.empty
-- | Updates a field table.
updateFT :: P.ClassId -> P.FieldId -> AbstrValue i -> FieldTable i -> FieldTable i
updateFT cn fn = M.insert (cn, fn)
-- | Returns the value of the given field of the field table.
-- Returns an error if the field does not exist.
lookupFT :: P.ClassId -> P.FieldId -> FieldTable i -> AbstrValue i
lookupFT cn fn ft = errmsg `fromMaybe` M.lookup (cn,fn) ft
where errmsg = error $ "Jat.PState.Object.lookupFT: element not found " ++ show (cn,fn)
-- | Retuns the entries of the field table as pair of identifier and value.
assocsFT :: FieldTable i -> [((P.ClassId,P.FieldId),AbstrValue i)]
assocsFT = M.assocs
-- | Returns the values of the field table.
elemsFT :: FieldTable i -> [AbstrValue i]
elemsFT = M.elems
instance Pretty i => Pretty (Object i) where
pretty (Instance cn ft) = pretty cn <> encloseSep lparen rparen comma (prettyFT ft)
where
prettyFT = map prettyElem . M.toList
prettyElem ((cne,fne),v) = pretty cne <> dot <> pretty fne <> equals <> pretty v
pretty (AbsVar cn) = text . map toLower . show $ pretty cn
|
ComputationWithBoundedResources/jat
|
src/Jat/PState/Object.hs
|
Haskell
|
bsd-3-clause
| 2,779
|
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module BitBasket where
import Data.Maybe
import Data.Word
import Data.Bits
import Control.Monad
-- Right-to-Left bit basket
data BitBasket a = BitBasket Int a
deriving(Eq,Show)
unsafeUnBasket :: (Bits a) => BitBasket a -> a
unsafeUnBasket (BitBasket 0 _) = 0
unsafeUnBasket (BitBasket p b) =
let x = bit (p-1) in b .&. (x.|.(x - 1))
unBasket :: (Bits a) => BitBasket a -> Maybe a
unBasket (BitBasket 0 _) = Nothing
unBasket bb@(BitBasket _ _) = Just $ unsafeUnBasket $ bb
mkBasket :: (Bits a) => a -> BitBasket a
mkBasket a = BitBasket (bitSize a) a
bbhead :: (Bits a) => BitBasket a -> a
bbhead (BitBasket 0 _) = error "empty BitBasket"
bbhead (BitBasket p b) = if testBit b (p-1) then 1 else 0
bbtail :: (Bits a) => BitBasket a -> BitBasket a
bbtail (BitBasket 0 _) = error "empty BitBasket"
bbtail (BitBasket p b) = BitBasket (p-1) b
bbtake :: (Bits a) => Int -> BitBasket a -> a
bbtake 0 _ = 0
bbtake p bs = (h `shiftR` p) .&. bbtake (p-1) t
where (h,t) = (bbhead bs, bbtail bs)
bbunpack :: (Bits a) => BitBasket a -> [Bool]
bbunpack (BitBasket 0 _) = []
bbunpack (BitBasket p b) = (testBit b (p-1)) : (bbunpack $ BitBasket (p-1) b)
bbnull :: BitBasket a -> Bool
bbnull (BitBasket 0 _) = True
bbnull (BitBasket _ _) = False
bbempty :: (Bits a) => BitBasket a
bbempty = BitBasket 0 0
bblength :: (Bits a) => BitBasket a -> Int
bblength (BitBasket p b) = 0 `max` ((bitSize b) `min` p)
bbappend :: (Bits a) => BitBasket a -> BitBasket a -> BitBasket a
bbappend bb1@(BitBasket p1 b1) bb2@(BitBasket p2 b2)
| (p1 + p2) > bitSize b1 = error "BitBasket: no space left in basket"
| otherwise = BitBasket (p1 + p2) ((b1 `shiftL` p2) .|. (unsafeUnBasket bb2))
bbsplitAt :: (Bits a) => Int -> BitBasket a -> (BitBasket a, BitBasket a)
bbsplitAt n' (BitBasket p b) = (b1,b2)
where
n = 0 `max` (n' `min` p)
b1 = BitBasket n (b `shiftR`(p-n))
b2 = BitBasket (p-n) b
bbparse :: (Bits a) => BitBasket a -> [Int] -> Maybe [a]
bbparse _ [] = Just []
bbparse bb@(BitBasket p b) (w:ws) = do
when (w>p) (fail "Not enough bits")
v <- unBasket (BitBasket w (b `shiftR`(p-w)))
vs <- bbparse (BitBasket (p-w) b) ws
return (v:vs)
getBits :: (Bits a, Monad m) => [Int] -> a -> m [a]
getBits ws v = case bbparse (mkBasket v) ws of
Nothing -> fail "bbparse failed"
Just l -> return l
|
ierton/yteratee
|
src/BitBasket.hs
|
Haskell
|
bsd-3-clause
| 2,497
|
{-# LANGUAGE DeriveDataTypeable, NoMonomorphismRestriction #-}
-----------------------------------------------------------------------------
-- |
-- Module : Diagrams.Backend.Pdf.CmdLine
-- Copyright : (c) 2013 alpheccar.org (see LICENSE)
-- License : BSD-style (see LICENSE)
--
-- Convenient creation of command-line-driven executables for
-- rendering diagrams using the Pdf backend.
--
-- * 'defaultMain' creates an executable which can render a single
-- diagram at various options.
--
-----------------------------------------------------------------------------
module Diagrams.Backend.Pdf.CmdLine
( defaultMain
, multipleMain
, Pdf
) where
import Diagrams.Prelude hiding (width, height, interval)
import Diagrams.Backend.Pdf
import System.Console.CmdArgs.Implicit hiding (args)
import Prelude
import Data.List.Split
import System.Environment (getProgName)
import qualified Graphics.PDF as P
data DiagramOpts = DiagramOpts
{ width :: Maybe Int
, height :: Maybe Int
, output :: FilePath
, compressed :: Maybe Bool
, author :: Maybe String
}
deriving (Show, Data, Typeable)
diagramOpts :: String -> DiagramOpts
diagramOpts prog = DiagramOpts
{ width = def
&= typ "INT"
&= help "Desired width of the output image (default 400)"
, height = def
&= typ "INT"
&= help "Desired height of the output image (default 400)"
, output = def
&= typFile
&= help "Output file"
, compressed = def
&= typ "BOOL"
&= help "Compressed PDF file"
, author = def
&= typ "STRING"
&= help "Author of the document"
}
&= summary "Command-line diagram generation."
&= program prog
-- | This is the simplest way to render diagrams, and is intended to
-- be used like so:
--
-- > ... other definitions ...
-- > myDiagram = ...
-- >
-- > main = defaultMain myDiagram
--
-- Compiling a source file like the above example will result in an
-- executable which takes command-line options for setting the size,
-- output file, and so on, and renders @myDiagram@ with the
-- specified options.
--
-- Pass @--help@ to the generated executable to see all available
-- options. Currently it looks something like
--
-- @
-- Command-line diagram generation.
--
-- Foo [OPTIONS]
--
-- Common flags:
-- -w --width=INT Desired width of the output image (default 400)
-- -h --height=INT Desired height of the output image (default 400)
-- -o --output=FILE Output file
-- -c --compressed Compressed PDF file
-- -? --help Display help message
-- -V --version Print version information
-- @
--
-- For example, a couple common scenarios include
--
-- @
-- $ ghc --make MyDiagram
--
-- # output image.eps with a width of 400pt (and auto-determined height)
-- $ ./MyDiagram --compressed -o image.pdf -w 400
-- @
defaultMain :: Diagram Pdf R2 -> IO ()
defaultMain d = do
prog <- getProgName
opts <- cmdArgs (diagramOpts prog)
let sizeSpec = case (width opts, height opts) of
(Nothing, Nothing) -> Absolute
(Just wi, Nothing) -> Width (fromIntegral wi)
(Nothing, Just he) -> Height (fromIntegral he)
(Just wi, Just he) -> Dims (fromIntegral wi)
(fromIntegral he)
(w,h) = sizeFromSpec sizeSpec
theAuthor = maybe "diagrams-pdf" id (author opts)
compression = maybe False id (compressed opts)
docRect = P.PDFRect 0 0 (floor w) (floor h)
pdfOpts = PdfOptions sizeSpec
ifCanRender opts $ do
P.runPdf (output opts)
(P.standardDocInfo { P.author=P.toPDFString theAuthor, P.compressed = compression}) docRect $ do
page1 <- P.addPage Nothing
P.drawWithPage page1 $ renderDia Pdf pdfOpts d
-- | Generate a multipage PDF document from several diagrams.
-- Each diagram is scaled to the page size
multipleMain :: [Diagram Pdf R2] -> IO ()
multipleMain d = do
prog <- getProgName
opts <- cmdArgs (diagramOpts prog)
let sizeSpec = case (width opts, height opts) of
(Nothing, Nothing) -> Absolute
(Just wi, Nothing) -> Width (fromIntegral wi)
(Nothing, Just he) -> Height (fromIntegral he)
(Just wi, Just he) -> Dims (fromIntegral wi)
(fromIntegral he)
(w,h) = sizeFromSpec sizeSpec
theAuthor = maybe "diagrams-pdf" id (author opts)
compression = maybe False id (compressed opts)
docRect = P.PDFRect 0 0 (floor w) (floor h)
pdfOpts = PdfOptions sizeSpec
createPage aDiag = do
page1 <- P.addPage Nothing
P.drawWithPage page1 $ renderDia Pdf pdfOpts aDiag
ifCanRender opts $ do
P.runPdf (output opts)
(P.standardDocInfo { P.author=P.toPDFString theAuthor, P.compressed = compression}) docRect $ do
mapM_ createPage d
ifCanRender :: DiagramOpts -> IO () -> IO ()
ifCanRender opts action =
case splitOn "." (output opts) of
[""] -> putStrLn "No output file given."
ps | last ps `elem` ["pdf"] -> action
| otherwise -> putStrLn $ "Unknown file type: " ++ last ps
|
alpheccar/diagrams-pdf
|
src/Diagrams/Backend/Pdf/CmdLine.hs
|
Haskell
|
bsd-3-clause
| 5,541
|
{-# LANGUAGE ForeignFunctionInterface, TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances, FlexibleContexts, ScopedTypeVariables, CPP #-}
-----------------------------------------------------------------------------
-- |
-- Licence : BSD-style (see LICENSE)
--
-- Exports data types and functions required by the generated binding files.
--
-----------------------------------------------------------------------------
module Foreign.Salsa.Binding (
module Foreign.Salsa.Common,
module Foreign.Salsa.Core,
module Foreign.Salsa.CLR,
module Foreign.Salsa.Resolver,
FunPtr, unsafePerformIO, liftM,
type_GetType
) where
import Foreign.Salsa.Common
import Foreign.Salsa.Core
import Foreign.Salsa.CLR
import Foreign.Salsa.Resolver
import System.IO.Unsafe ( unsafePerformIO )
import Foreign hiding (new, unsafePerformIO)
import Foreign.C.String
import Control.Monad (liftM)
-- TODO: Perhaps move some/all of this into the generator, so that it can be
-- CLR-version neutral.
--
-- Import the System.Type.GetType(String) and System.Type.MakeArrayType(Int32)
-- methods so they can be used in the implementations of 'typeOf' as produced by
-- the generator.
--
type Type_GetType_stub = SalsaString -> Bool -> IO ObjectId
foreign import ccall "dynamic" make_Type_GetType_stub :: FunPtr Type_GetType_stub -> Type_GetType_stub
{-# NOINLINE type_GetType_stub #-}
type_GetType_stub :: Type_GetType_stub
type_GetType_stub = make_Type_GetType_stub $ unsafePerformIO $ getMethodStub
"System.Type, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" "GetType"
"System.String;System.Boolean"
type_GetType typeName = marshalMethod2s type_GetType_stub undefined undefined (typeName, True)
type Type_MakeArrayType_stub = ObjectId -> Int32 -> IO ObjectId
foreign import ccall "dynamic" make_Type_MakeArrayType_stub :: FunPtr Type_MakeArrayType_stub -> Type_MakeArrayType_stub
{-# NOINLINE type_MakeArrayType_stub #-}
type_MakeArrayType_stub :: Type_MakeArrayType_stub
type_MakeArrayType_stub = make_Type_MakeArrayType_stub $ unsafePerformIO $ getMethodStub
"System.Type, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" "MakeArrayType"
"System.Int32"
--
-- SalsaForeignType instances for primitive types
--
instance SalsaForeignType Int32 where foreignTypeOf _ = foreignTypeFromString "System.Int32"
instance SalsaForeignType String where foreignTypeOf _ = foreignTypeFromString "System.String"
instance SalsaForeignType Bool where foreignTypeOf _ = foreignTypeFromString "System.Boolean"
instance SalsaForeignType Double where foreignTypeOf _ = foreignTypeFromString "System.Double"
foreignTypeFromString :: String -> Obj Type_
foreignTypeFromString s = unsafePerformIO $ do
-- putStrLn $ "typeOfString: " ++ s
type_GetType s
-- marshalMethod1s type_GetType_stub undefined undefined s
-- Define the foreignTypeOf function for arrays by first calling foreignTypeOf on the element type,
-- and then using the Type.MakeArrayType method to return the associated one-dimensional
-- array type:
instance SalsaForeignType t => SalsaForeignType (Arr t) where
foreignTypeOf _ = unsafePerformIO $
marshalMethod1i type_MakeArrayType_stub (foreignTypeOf (undefined :: t)) undefined (1 :: Int32)
-- Note: this function requires ScopedTypeVariables
-- Define foreignTypeOf for reference types in terms of the associated static type.
instance SalsaForeignType t => SalsaForeignType (Obj t) where
foreignTypeOf _ = foreignTypeOf (undefined :: t)
-- vim:set sw=4 ts=4 expandtab:
|
tim-m89/Salsa
|
Foreign/Salsa/Binding.hs
|
Haskell
|
bsd-3-clause
| 3,595
|
{-# LANGUAGE GADTs, DataKinds, KindSignatures, PolyKinds, ConstraintKinds, TypeOperators #-}
module Tests.Util.TypeEquality where
import GHC.Exts
data (:==:) :: k -> k -> * where
Refl :: a :==: a
cong :: (a :==: b) -> (f a :==: f b)
cong Refl = Refl
data Exists :: (a -> *) -> * where
ExI :: f a -> Exists f
data Exists2 :: (a -> b -> *) -> * where
ExI2 :: f a b -> Exists2 f
subst :: (a :==: b) -> f a -> f b
subst Refl x = x
|
liamoc/geordi
|
Tests/Util/TypeEquality.hs
|
Haskell
|
bsd-3-clause
| 443
|
-- |
-- Copyright : (C) 2014 Seagate Technology Limited.
-- License : BSD3
import Control.Applicative
import Control.Alternative.Freer
import qualified Options.Applicative as CL
import qualified Options.Applicative.Help.Core as CL
data Foo x = Foo {
name :: String
, reader :: String -> x
}
instance Functor Foo where
fmap f (Foo n r) = Foo n $ f . r
mkParser :: Foo a -> CL.Parser a
mkParser (Foo n _) = CL.option CL.disabled ( CL.long n )
type Bar a = Alt Foo a
foo :: String -> (String -> x) -> Bar x
foo n r = liftAlt $ Foo n r
myFoo :: Bar [String]
myFoo = many $ foo "Hello" (\_ -> "Hello")
clFoo :: CL.Parser [String]
clFoo = runAlt mkParser $ myFoo
hangs = CL.cmdDesc clFoo
main :: IO ()
main = print hangs
|
seagate-ssg/options-schema
|
test/Applicative.hs
|
Haskell
|
bsd-3-clause
| 736
|
module SSH.Supported where
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Serialize as S
import Crypto.HMAC (MacKey(..), hmac)
import Crypto.Hash.CryptoAPI (MD5, SHA1)
import SSH.Crypto
import SSH.Internal.Util
version :: String
version = "SSH-2.0-DarcsDen"
-- | The required key exchange algorithms are specified in
-- <https://tools.ietf.org/html/rfc4253#section-6.5 rfc4253 section 6.5>.
supportedKeyExchanges :: [String]
supportedKeyExchanges =
[ "diffie-hellman-group1-sha1"
-- TODO: The SSH rfc requires that the following method is also
-- supported.
-- , "diffie-hellman-group-exchange-sha1"
]
-- | The supported key algorithms. Specified in
-- <https://tools.ietf.org/html/rfc4253#section-6.6 rfc4253 section 6.6>.
supportedKeyAlgorithms :: [String]
supportedKeyAlgorithms = ["ssh-rsa", "ssh-dss"]
-- | Suporrted Ciphers.
--
-- Defined in <https://tools.ietf.org/html/rfc4253#section-6.3 rfc4253
-- section 6.3>.
supportedCiphers :: [(String, Cipher)]
supportedCiphers =
[ ("aes256-cbc", aesCipher 32)
, ("aes192-cbc", aesCipher 24)
, ("aes128-cbc", aesCipher 16)
]
where
aesCipher :: Int -> Cipher
aesCipher s = Cipher AES CBC 16 s
-- | The required macs are specified in
-- <https://tools.ietf.org/html/rfc4253#section-6.4 rfc4253 section 6.4>.
supportedMACs :: [(String, LBS.ByteString -> HMAC)]
supportedMACs =
[ ("hmac-sha1", sha)
, ("hmac-md5", md5)
]
where
sha, md5 :: LBS.ByteString -> HMAC
sha k = HMAC 20 $ \b -> bsToLBS . S.runPut $ S.put (hmac (MacKey (strictLBS (LBS.take 20 k))) b :: SHA1)
md5 k = HMAC 16 $ \b -> bsToLBS . S.runPut $ S.put (hmac (MacKey (strictLBS (LBS.take 16 k))) b :: MD5)
bsToLBS :: BS.ByteString -> LBS.ByteString
bsToLBS = LBS.fromChunks . (: [])
-- | Supported compression algorithms.
--
-- Defined in <https://tools.ietf.org/html/rfc4253#section-6.2 rfc4253
-- section 6.2>.
supportedCompression :: String
supportedCompression = "none"
supportedLanguages :: String
supportedLanguages = ""
|
cdepillabout/ssh
|
src/SSH/Supported.hs
|
Haskell
|
bsd-3-clause
| 2,090
|
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
module RevealHs.TH where
import Control.Monad
import Data.HashMap.Strict as HM
import Data.IORef
import Data.Maybe
import Data.String.Interpolate
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import RevealHs.Internal as I
import RevealHs.Options
import RevealHs.QQ
import System.IO.Unsafe
{-# NOINLINE slidesRef #-}
slidesRef :: IORef SlideMap
slidesRef = unsafePerformIO $ newIORef empty
{-# NOINLINE slideGroupOrderRef #-}
slideGroupOrderRef :: IORef [Module]
slideGroupOrderRef = unsafePerformIO $ newIORef []
slide :: (SlideOptions -> Slide) -> DecsQ
slide = slide' defSlideOptions
slide' :: SlideOptions -> (SlideOptions -> Slide) -> DecsQ
slide' so s = do
mod <- thisModule
runIO $ do
slides <- readIORef slidesRef
when (isNothing $ HM.lookup mod slides) $
modifyIORef' slideGroupOrderRef (mod:)
modifyIORef' slidesRef (alter addSlide mod)
return []
where
addSlide Nothing = Just (defGroupOptions, [s so])
addSlide (Just (opts, slides)) = Just (opts, s so:slides)
groupOptions :: GroupOptions -> DecsQ
groupOptions opts = do
mod <- thisModule
runIO $ do
slides <- readIORef slidesRef
when (isNothing $ HM.lookup mod slides) $
modifyIORef' slideGroupOrderRef (mod:)
modifyIORef' slidesRef (alter setOpts mod)
return []
where
setOpts Nothing = Just (opts, [])
setOpts (Just (_, slides)) = Just (opts, slides)
mkRevealPage :: RevealOptions -> DecsQ
mkRevealPage ro = [d|main = putStrLn $export|]
where
export :: ExpQ
export = do
s <- runIO $ do
slides <- readIORef slidesRef
slideGroupOrder <- readIORef slideGroupOrderRef
return $ I.exportRevealPage ro slides slideGroupOrder
stringE s
|
KenetJervet/reveal-hs
|
src/RevealHs/TH.hs
|
Haskell
|
bsd-3-clause
| 1,923
|
{-# LANGUAGE FlexibleContexts #-}
module EFA.Data.Axis.Mono where
import EFA.Utility(Caller,merror, ModuleName(..),FunctionName, genCaller)
import qualified EFA.Data.Vector as DV
-- | TODO -- how many points are allowed to have the same time, only two or more ?
m :: ModuleName
m = ModuleName "Axis.Mono"
nc :: FunctionName -> Caller
nc = genCaller m
-- | Datatype with monotonically rising values
data Axis typ label vec a = Axis {
getLabel :: label,
getVec :: vec a} deriving (Show,Eq)
newtype Idx = Idx {getInt :: Int} deriving Show
map ::
(DV.Walker vec,
DV.Storage vec b,
DV.Storage vec a) =>
(a -> b) -> Axis typ label vec a -> Axis typ label vec b
map f (Axis label vec) = Axis label $ DV.map f vec
imap ::
(DV.Walker vec,
DV.Storage vec b,
DV.Storage vec a) =>
(Idx -> a -> b) -> Axis typ label vec a -> Axis typ label vec b
imap f (Axis label vec) = Axis label $ DV.imap (f . Idx) vec
indexAdd :: Idx -> Int -> Idx
indexAdd (Idx idx) num = Idx $ (idx+num)
len ::
(DV.Storage vec a, DV.Length vec)=>
Axis typ label vec a -> Int
len (Axis _ vec) = DV.length vec
fromVec ::
(DV.Storage vec Bool, DV.Singleton vec,
DV.Zipper vec, DV.Storage vec a,Ord a) =>
Caller -> label -> vec a -> Axis typ label vec a
fromVec caller label vec =
if isMonoton then Axis label vec
else merror caller m "fromVec" "Vector of elements is not monotonically rising"
where isMonoton = DV.all (==True) $ DV.deltaMap (\ x1 x2 -> x2 >= x1) vec
findIndex ::
(DV.Storage vec a, DV.Find vec)=>
(a -> Bool) -> Axis typ label vec a -> Maybe Idx
findIndex f (Axis _ vec) = fmap Idx $ DV.findIndex f vec
lookupUnsafe ::
DV.LookupUnsafe vec a =>
Axis typ label vec a -> Idx -> a
lookupUnsafe (Axis _ axis) (Idx idx) = DV.lookupUnsafe axis idx
findRightInterpolationIndex ::
(DV.Storage vec a, DV.Find vec, Ord a, DV.Length vec) =>
Axis typ label vec a -> a -> Idx
findRightInterpolationIndex axis x = rightIndex
where
idx = findIndex (>x) axis
rightIndex = case idx of
Just (Idx ix) -> if ix==0 then Idx 1 else Idx ix
Nothing -> Idx $ (len axis)-1
-- | TODO -- Code ist wrong -- exact point hits have to be considered
-- | get all Points involved in the interpolation of a point on the given coordinates
getSupportPoints ::
(Ord a,
DV.Storage vec a,
DV.Length vec,
DV.Find vec,
DV.LookupUnsafe vec a) =>
Axis typ label vec a -> a -> ((Idx,Idx),(a,a))
getSupportPoints axis x = ((leftIndex,rightIndex),
(lookupUnsafe axis leftIndex, lookupUnsafe axis rightIndex))
where rightIndex = findRightInterpolationIndex axis x
leftIndex = indexAdd rightIndex (-1)
|
energyflowanalysis/efa-2.1
|
src/EFA/Data/Axis/Mono.hs
|
Haskell
|
bsd-3-clause
| 2,684
|
module Expectation where
import Test.Hspec
import System.Directory
import Control.Exception as E
shouldContain :: Eq a => [a] -> a -> Expectation
shouldContain containers element = do
let res = element `elem` containers
res `shouldBe` True
withDirectory_ :: FilePath -> IO a -> IO a
withDirectory_ dir action = bracket getCurrentDirectory
setCurrentDirectory
(\_ -> setCurrentDirectory dir >> action)
withDirectory :: FilePath -> (FilePath -> IO a) -> IO a
withDirectory dir action = bracket getCurrentDirectory
setCurrentDirectory
(\d -> setCurrentDirectory dir >> action d)
|
eagletmt/ghc-mod
|
test/Expectation.hs
|
Haskell
|
bsd-3-clause
| 730
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Graphics.Tooty
(
module Graphics.Tooty.Image,
module Graphics.Tooty.Matrix,
module Graphics.Tooty.Geometry,
module Graphics.Tooty.Text,
-- * OpenGL context preparation
setup2D,
positionViewport,
) where
import Graphics.Rendering.OpenGL ( GLfloat, ($=) )
import qualified Graphics.Rendering.OpenGL as GL
import Linear.V2
import Graphics.Tooty.Geometry
import Graphics.Tooty.Image
import Graphics.Tooty.Matrix
import Graphics.Tooty.Text
setup2D :: V2 Int -> IO ()
setup2D (V2 w h) = do
GL.depthMask $= GL.Disabled
GL.matrixMode $= GL.Projection
GL.loadIdentity
GL.ortho 0 (fromIntegral w) 0 (fromIntegral h) (-1) 1
GL.matrixMode $= GL.Modelview 0
GL.loadIdentity
GL.translate (GL.Vector3 0.375 0.375 0 :: GL.Vector3 GLfloat)
-- Functionality not specific to 2D:
GL.lineSmooth $= GL.Enabled
GL.pointSmooth $= GL.Enabled
GL.blend $= GL.Enabled
GL.blendFunc $= (GL.SrcAlpha, GL.OneMinusSrcAlpha)
positionViewport :: V2 Int -> IO ()
positionViewport p = do
(_, size) <- GL.get GL.viewport
GL.viewport $= (GL.Position x y, size)
where
V2 x y = fmap fromIntegral p
|
cdxr/haskell-tooty
|
Graphics/Tooty.hs
|
Haskell
|
bsd-3-clause
| 1,217
|
-- |
-- Module : Text.PrettyPrint.Mainland
-- Copyright : (c) Harvard University 2006-2011
-- (c) Geoffrey Mainland 2011-2012
-- License : BSD-style
-- Maintainer : mainland@eecs.harvard.edu
--
-- Stability : provisional
-- Portability : portable
--
-- This module is based on /A Prettier Printer/ by Phil Wadler in /The Fun of
-- Programming/, Jeremy Gibbons and Oege de Moor (eds)
-- <http://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf>
--
-- At the time it was originally written I didn't know about Daan Leijen's
-- pretty printing module based on the same paper. I have since incorporated
-- many of his improvements. This module is geared towards pretty printing
-- source code; its main advantages over other libraries are a 'Pretty' class
-- that handles precedence and the ability to automatically track the source
-- locations associated with pretty printed values and output appropriate
-- #line pragmas.
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverlappingInstances #-}
module Text.PrettyPrint.Mainland (
-- * The document type
Doc,
-- * Basic combinators
empty, text, char, string, fromText, fromLazyText,
line, nest, srcloc, column, nesting,
softline, softbreak, group,
-- * Operators
(<>), (<+>), (</>), (<+/>), (<//>),
-- * Character documents
backquote, colon, comma, dot, dquote, equals, semi, space, spaces, squote,
star, langle, rangle, lbrace, rbrace, lbracket, rbracket, lparen, rparen,
-- * Bracketing combinators
enclose,
angles, backquotes, braces, brackets, dquotes, parens, parensIf, squotes,
-- * Alignment and indentation
align, hang, indent,
-- * Combining lists of documents
folddoc, spread, stack, cat, sep,
punctuate, commasep, semisep,
encloseSep,
tuple, list,
-- * The rendered document type
RDoc(..),
-- * Document rendering
render, renderCompact,
displayS, prettyS, pretty,
displayPragmaS, prettyPragmaS, prettyPragma,
displayLazyText, prettyLazyText,
displayPragmaLazyText, prettyPragmaLazyText,
-- * Document output
putDoc, hPutDoc,
-- * The 'Pretty' type class for pretty printing
Pretty(..),
faildoc, errordoc
) where
import Data.Int
import Data.Loc (L(..),
Loc(..),
Located(..),
Pos(..),
posFile,
posLine)
import qualified Data.Map as Map
import Data.Monoid
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.Lazy.IO as TIO
import qualified Data.Text.Lazy as L
import qualified Data.Text.Lazy.Builder as B
import Data.Word
import GHC.Real (Ratio(..))
import System.IO (Handle)
infixr 5 </>, <+/>, <//>
infixr 6 <+>
data Doc = Empty -- ^ The empty document
| Char Char -- ^ A single character
| String !Int String -- ^ 'String' with associated length (to avoid
-- recomputation)
| Text T.Text -- ^ 'T.Text'
| LazyText L.Text -- ^ 'L.Text'
| Line -- ^ Newline
| Nest !Int Doc -- ^ Indented document
| SrcLoc Loc -- ^ Tag output with source location
| Doc `Cat` Doc -- ^ Document concatenation
| Doc `Alt` Doc -- ^ Provide alternatives. Invariants: all
-- layouts of the two arguments flatten to the
-- same layout
| Column (Int -> Doc) -- ^ Calculate document based on current column
| Nesting (Int -> Doc) -- ^ Calculate document based on current nesting
-- | The empty document.
empty :: Doc
empty = Empty
-- | The document @'text' s@ consists of the string @s@, which should not
-- contain any newlines. For a string that may include newlines, use 'string'.
text :: String -> Doc
text s = String (length s) s
-- | The document @'char' c@ consists the single character @c@.
char :: Char -> Doc
char '\n' = line
char c = Char c
-- | The document @'string' s@ consists of all the characters in @s@ but with
-- newlines replaced by 'line'.
string :: String -> Doc
string "" = empty
string ('\n' : s) = line <> string s
string s = case span (/= '\n') s of
(xs, ys) -> text xs <> string ys
-- | The document @'fromText' s@ consists of the 'T.Text' @s@, which should not
-- contain any newlines.
fromText :: T.Text -> Doc
fromText = Text
-- | The document @'fromLazyText' s@ consists of the 'L.Text' @s@, which should
-- not contain any newlines.
fromLazyText :: L.Text -> Doc
fromLazyText = LazyText
-- | The document @'line'@ advances to the next line and indents to the current
-- indentation level. When undone by 'group', it behaves like 'space'.
line :: Doc
line = Line
-- | The document @'nest' i d@ renders the document @d@ with the current
-- indentation level increased by @i@.
nest :: Int -> Doc -> Doc
nest i d = Nest i d
-- | The document @'srcloc' x@ adds the.
srcloc :: Located a => a -> Doc
srcloc x = SrcLoc (locOf x)
column :: (Int -> Doc) -> Doc
column = Column
nesting :: (Int -> Doc) -> Doc
nesting = Nesting
softline :: Doc
softline = space `Alt` line
softbreak :: Doc
softbreak = empty `Alt` line
group :: Doc -> Doc
group d = flatten d `Alt` d
flatten :: Doc -> Doc
flatten Empty = Empty
flatten (Char c) = Char c
flatten (String l s) = String l s
flatten (Text s) = Text s
flatten (LazyText s) = LazyText s
flatten Line = Char ' '
flatten (x `Cat` y) = flatten x `Cat` flatten y
flatten (Nest i x) = Nest i (flatten x)
flatten (x `Alt` _) = flatten x
flatten (SrcLoc loc) = SrcLoc loc
flatten (Column f) = Column (flatten . f)
flatten (Nesting f) = Nesting (flatten . f)
(<+>) :: Doc -> Doc -> Doc
x <+> y = x <> space <> y
(</>) :: Doc -> Doc -> Doc
x </> y = x <> line <> y
(<+/>) :: Doc -> Doc -> Doc
x <+/> y = x <> softline <> y
(<//>) :: Doc -> Doc -> Doc
x <//> y = x <> softbreak <> y
-- | The document @backquote@ consists of a backquote, \"`\".
backquote :: Doc
backquote = char '`'
-- | The document @colon@ consists of a colon, \":\".
colon :: Doc
colon = char ':'
-- | The document @comma@ consists of a comma, \",\".
comma :: Doc
comma = char ','
-- | The document @dot@ consists of a period, \".\".
dot :: Doc
dot = char '.'
-- | The document @dquote@ consists of a double quote, \"\\\"\".
dquote :: Doc
dquote = char '"'
-- | The document @equals@ consists of an equals sign, \"=\".
equals :: Doc
equals = char '='
-- | The document @semi@ consists of a semicolon, \";\".
semi :: Doc
semi = char ';'
-- | The document @space@ consists of a space, \" \".
space :: Doc
space = char ' '
-- | The document @'space' n@ consists of n spaces.
spaces :: Int -> Doc
spaces n = text (replicate n ' ')
-- | The document @squote@ consists of a single quote, \"\\'\".
squote :: Doc
squote = char '\''
-- | The document @star@ consists of an asterisk, \"*\".
star :: Doc
star = char '*'
-- | The document @langle@ consists of a less-than sign, \"<\".
langle :: Doc
langle = char '<'
-- | The document @rangle@ consists of a greater-than sign, \">\".
rangle :: Doc
rangle = char '>'
-- | The document @lbrace@ consists of a left brace, \"{\".
lbrace :: Doc
lbrace = char '{'
-- | The document @rbrace@ consists of a right brace, \"}\".
rbrace :: Doc
rbrace = char '}'
-- | The document @lbracket@ consists of a right brace, \"[\".
lbracket :: Doc
lbracket = char '['
-- | The document @rbracket@ consists of a right brace, \"]\".
rbracket :: Doc
rbracket = char ']'
-- | The document @lparen@ consists of a right brace, \"(\".
lparen :: Doc
lparen = char '('
-- | The document @rparen@ consists of a right brace, \")\".
rparen :: Doc
rparen = char ')'
-- | The document @'enclose' l r d)@ encloses the document @d@ between the
-- documents @l@ and @r@ using @<>@. It obeys the law
--
-- @'enclose' l r d = l <> d <> r@
enclose :: Doc -> Doc -> Doc -> Doc
enclose left right d = left <> d <> right
-- | The document @'angles' d@ encloses the aligned document @d@ in <...>.
angles :: Doc -> Doc
angles = enclose langle rangle . align
-- | The document @'backquotes' d@ encloses the aligned document @d@ in `...`.
backquotes :: Doc -> Doc
backquotes = enclose backquote backquote . align
-- | The document @'brackets' d@ encloses the aligned document @d@ in [...].
brackets :: Doc -> Doc
brackets = enclose lbracket rbracket . align
-- | The document @'braces' d@ encloses the aligned document @d@ in {...}.
braces :: Doc -> Doc
braces = enclose lbrace rbrace . align
-- | The document @'dquotes' d@ encloses the aligned document @d@ in "...".
dquotes :: Doc -> Doc
dquotes = enclose dquote dquote . align
-- | The document @'parens' d@ encloses the aligned document @d@ in (...).
parens :: Doc -> Doc
parens = enclose lparen rparen . align
-- | The document @'parensIf' p d@ encloses the document @d@ in parenthesis if
-- @p@ is @True@, and otherwise yields just @d@.
parensIf :: Bool -> Doc -> Doc
parensIf True doc = parens doc
parensIf False doc = doc
-- | The document @'parens' d@ encloses the document @d@ in '...'.
squotes :: Doc -> Doc
squotes = enclose squote squote . align
-- | The document @'align' d@ renders @d@ with a nesting level set to the current
-- column.
align :: Doc -> Doc
align d = column $ \k ->
nesting $ \i ->
nest (k - i) d
-- | The document @'hang' i d@ renders @d@ with a nesting level set to the
-- current column plus @i@. This differs from 'indent' in that the first line of
-- @d@ /is not/ indented.
hang :: Int -> Doc -> Doc
hang i d = align (nest i d)
-- | The document @'indent' i d@ indents @d@ @i@ spaces relative to the current
-- column. This differs from 'hang' in that the first line of @d@ /is/ indented.
indent :: Int -> Doc -> Doc
indent i d = align (nest i (spaces i <> d))
-- | The document @'folddoc' f ds@ obeys the laws:
--
-- * @'folddoc' f [] = 'empty'@
-- * @'folddoc' f [d1, d2, ..., dnm1, dn] = d1 `f` (d2 `f` ... (dnm1 `f` dn))@
folddoc :: (Doc -> Doc -> Doc) -> [Doc] -> Doc
folddoc _ [] = empty
folddoc _ [x] = x
folddoc f (x:xs) = f x (folddoc f xs)
-- | The document @'spread' ds@ concatenates the documents @ds@ using @<+>@.
spread :: [Doc] -> Doc
spread = folddoc (<+>)
-- | The document @'stack' ds@ concatenates the documents @ds@ using @</>@.
stack :: [Doc] -> Doc
stack = folddoc (</>)
-- | The document @'cat' ds@ separates the documents @ds@ with the empty
-- document as long as there is room, and uses newlines when there isn't.
cat :: [Doc] -> Doc
cat = group . folddoc (<//>)
-- | The document @'sep' ds@ separates the documents @ds@ with the empty
-- document as long as there is room, and uses spaces when there isn't.
sep :: [Doc] -> Doc
sep = group . folddoc (<+/>)
-- | The document @'punctuate' p ds@ obeys the law:
--
-- @'punctuate' p [d1, d2, ..., dn] = [d1 <> p, d2 <> p, ..., dn]@
punctuate :: Doc -> [Doc] -> [Doc]
punctuate _ [] = []
punctuate _ [d] = [d]
punctuate p (d:ds) = (d <> p) : punctuate p ds
-- | The document @'commasep' ds@ comma-space separates @ds@, aligning the
-- resulting document to the current nesting level.
commasep :: [Doc] -> Doc
commasep = align . sep . punctuate comma
-- | The document @'semisep' ds@ semicolon-space separates @ds@, aligning the
-- resulting document to the current nesting level.
semisep :: [Doc] -> Doc
semisep = align . sep . punctuate semi
-- | The document @'encloseSep' l r p ds@ separates @ds@ with the punctuation @p@
-- and encloses the result using @l@ and @r@. When wrapped, punctuation appears
-- at the end of the line. The enclosed portion of the document is aligned one
-- column to the right of the opening document.
--
-- @
-- \> ws = map text (words \"The quick brown fox jumps over the lazy dog\")
-- \> test = pretty 15 (encloseSep lparen rparen comma ws)
-- @
--
-- will be layed out as:
--
-- @
-- (The, quick,
-- brown, fox,
-- jumps, over,
-- the, lazy,
-- dog)
-- @
encloseSep :: Doc -> Doc -> Doc -> [Doc] -> Doc
encloseSep left right p ds =
case ds of
[] -> left <> right
[d] -> left <> d <> right
_ -> left <> align (sep (punctuate p ds)) <> right
-- | The document @'tuple' ds@ separates @ds@ with commas and encloses them with
-- parentheses.
tuple :: [Doc] -> Doc
tuple = encloseSep lparen rparen comma
-- | The document @'tuple' ds@ separates @ds@ with commas and encloses them with
-- brackets.
list :: [Doc] -> Doc
list = encloseSep lbracket rbracket comma
-- | Equivalent of 'fail', but with a document instead of a string.
faildoc :: Monad m => Doc -> m a
faildoc = fail . show
-- | Equivalent of 'error', but with a document instead of a string.
errordoc :: Doc -> a
errordoc = error . show
-- | Render a document given a maximum width.
render :: Int -> Doc -> RDoc
render w x = best w 0 x
-- | Render a document without indentation on infinitely long lines. Since no
-- \'pretty\' printing is involved, this renderer is fast. The resulting output
-- contains fewer characters.
renderCompact :: Doc -> RDoc
renderCompact doc = scan 0 [doc]
where
scan :: Int -> [Doc] -> RDoc
scan !_ [] = REmpty
scan !k (d:ds) =
case d of
Empty -> scan k ds
Char c -> RChar c (scan (k+1) ds)
String l s -> RString l s (scan (k+l) ds)
Text s -> RText s (scan (k+T.length s) ds)
LazyText s -> RLazyText s (scan (k+fromIntegral (L.length s)) ds)
Line -> RLine 0 (scan 0 ds)
Nest _ x -> scan k (x:ds)
SrcLoc _ -> scan k ds
Cat x y -> scan k (x:y:ds)
Alt x _ -> scan k (x:ds)
Column f -> scan k (f k:ds)
Nesting f -> scan k (f 0:ds)
-- | Display a rendered document.
displayS :: RDoc -> ShowS
displayS = go
where
go :: RDoc -> ShowS
go REmpty = id
go (RChar c x) = showChar c . go x
go (RString _ s x) = showString s . go x
go (RText s x) = showString (T.unpack s) . go x
go (RLazyText s x) = showString (L.unpack s) . go x
go (RPos _ x) = go x
go (RLine i x) = showString ('\n' : replicate i ' ') . go x
-- | Render and display a document.
prettyS :: Int -> Doc -> ShowS
prettyS w x = displayS (render w x)
-- | Render and convert a document to a 'String'.
pretty :: Int -> Doc -> String
pretty w x = prettyS w x ""
-- | Display a rendered document with #line pragmas.
displayPragmaS :: RDoc -> ShowS
displayPragmaS = go
where
go :: RDoc -> ShowS
go REmpty = id
go (RChar c x) = showChar c . go x
go (RString _ s x) = showString s . go x
go (RText s x) = showString (T.unpack s) . go x
go (RLazyText s x) = showString (L.unpack s) . go x
go (RPos p x) = showChar '\n' .
showString "#line " .
shows (posLine p) .
showChar ' ' .
shows (posFile p) .
go x
go (RLine i x) = showString ('\n' : replicate i ' ') .
go x
-- | Render and display a document with #line pragmas.
prettyPragmaS :: Int -> Doc -> ShowS
prettyPragmaS w x = displayPragmaS (render w x)
-- | Render and convert a document to a 'String' with #line pragmas.
prettyPragma :: Int -> Doc -> String
prettyPragma w x = prettyPragmaS w x ""
-- | Display a rendered document as 'L.Text'. Uses a builder.
displayLazyText :: RDoc -> L.Text
displayLazyText = B.toLazyText . go
where
go :: RDoc -> B.Builder
go REmpty = mempty
go (RChar c x) = B.singleton c `mappend` go x
go (RString _ s x) = B.fromString s `mappend` go x
go (RText s x) = B.fromText s `mappend` go x
go (RLazyText s x) = B.fromLazyText s `mappend` go x
go (RPos _ x) = go x
go (RLine i x) = B.fromString ('\n':replicate i ' ') `mappend` go x
-- | Render and display a document as 'L.Text'. Uses a builder.
prettyLazyText :: Int -> Doc -> L.Text
prettyLazyText w x = displayLazyText (render w x)
-- | Display a rendered document with #line pragmas as 'L.Text'. Uses a builder.
displayPragmaLazyText :: RDoc -> L.Text
displayPragmaLazyText = B.toLazyText . go
where
go :: RDoc -> B.Builder
go REmpty = mempty
go (RChar c x) = B.singleton c `mappend` go x
go (RText s x) = B.fromText s `mappend` go x
go (RLazyText s x) = B.fromLazyText s `mappend` go x
go (RString _ s x) = B.fromString s `mappend` go x
go (RPos p x) = B.singleton '\n' `mappend`
B.fromString "#line " `mappend`
(go . renderCompact . ppr) (posLine p) `mappend`
B.singleton ' ' `mappend`
(go . renderCompact . ppr) (posFile p) `mappend`
go x
go (RLine i x) = B.fromString ('\n':replicate i ' ') `mappend`
go x
-- | Render and convert a document to 'L.Text' with #line pragmas. Uses a builder.
prettyPragmaLazyText :: Int -> Doc -> L.Text
prettyPragmaLazyText w x = displayPragmaLazyText (render w x)
merge :: Maybe Pos -> Loc -> Maybe Pos
merge Nothing NoLoc = Nothing
merge Nothing (Loc p _) = Just p
merge (Just p) NoLoc = Just p
merge (Just p1) (Loc p2 _) = let p = min p1 p2 in p `seq` Just p
lineloc :: Maybe Pos -- ^ Previous source position
-> Maybe Pos -- ^ Current source position
-> (Maybe Pos, RDocS) -- ^ Current source position and position to
-- output
lineloc Nothing Nothing = (Nothing, id)
lineloc Nothing (Just p) = (Just p, RPos p)
lineloc (Just p1) (Just p2)
| posFile p2 == posFile p1 &&
posLine p2 == posLine p1 + 1 = (Just p2, id)
| otherwise = (Just p2, RPos p2)
lineloc (Just p1) Nothing
| posFile p2 == posFile p1 &&
posLine p2 == posLine p1 + 1 = (Just p2, id)
| otherwise = (Just p2, RPos p2)
where
p2 = advance p1
advance :: Pos -> Pos
advance (Pos f l c coff) = Pos f (l+1) c coff
-- | A rendered document.
data RDoc = REmpty -- ^ The empty document
| RChar Char RDoc -- ^ A single character
| RString !Int String RDoc -- ^ 'String' with associated length (to
-- avoid recomputation)
| RText T.Text RDoc -- ^ 'T.Text'
| RLazyText L.Text RDoc -- ^ 'L.Text'
| RPos Pos RDoc -- ^ Tag output with source location
| RLine !Int RDoc -- ^ A newline with the indentation of the
-- subsequent line
type RDocS = RDoc -> RDoc
data Docs = Nil -- ^ No document.
| Cons !Int Doc Docs -- ^ Indentation, document and tail
best :: Int -> Int -> Doc -> RDoc
best !w k x = be Nothing Nothing k id (Cons 0 x Nil)
where
be :: Maybe Pos -- ^ Previous source position
-> Maybe Pos -- ^ Current source position
-> Int -- ^ Current column
-> RDocS
-> Docs
-> RDoc
be _ _ !_ f Nil = f REmpty
be p p' !k f (Cons i d ds) =
case d of
Empty -> be p p' k f ds
Char c -> be p p' (k+1) (f . RChar c) ds
String l s -> be p p' (k+l) (f . RString l s) ds
Text s -> be p p' (k+T.length s) (f . RText s) ds
LazyText s -> be p p' (k+fromIntegral (L.length s)) (f . RLazyText s) ds
Line -> (f . pragma . RLine i) (be p'' Nothing i id ds)
x `Cat` y -> be p p' k f (Cons i x (Cons i y ds))
Nest j x -> be p p' k f (Cons (i+j) x ds)
x `Alt` y -> better k f (be p p' k id (Cons i x ds))
(be p p' k id (Cons i y ds))
SrcLoc loc -> be p (merge p' loc) k f ds
Column g -> be p p' k f (Cons i (g k) ds)
Nesting g -> be p p' k f (Cons i (g i) ds)
where
(p'', pragma) = lineloc p p'
better :: Int -> RDocS -> RDoc -> RDoc -> RDoc
better !k f x y | fits (w - k) x = f x
| otherwise = f y
fits :: Int -> RDoc -> Bool
fits !w _ | w < 0 = False
fits !_ REmpty = True
fits !w (RChar _ x) = fits (w - 1) x
fits !w (RString l _ x) = fits (w - l) x
fits !w (RText s x) = fits (w - T.length s) x
fits !w (RLazyText s x) = fits (w - fromIntegral (L.length s)) x
fits !w (RPos _ x) = fits w x
fits !_ (RLine _ _) = True
-- | Render a document with a width of 80 and print it to standard output.
putDoc :: Doc -> IO ()
putDoc = TIO.putStr . prettyLazyText 80
-- | Render a document with a width of 80 and print it to the specified handle.
hPutDoc :: Handle -> Doc -> IO ()
hPutDoc h = TIO.hPutStr h . prettyLazyText 80
#if !MIN_VERSION_base(4,5,0)
infixr 6 <>
(<>) :: Doc -> Doc -> Doc
x <> y = x `Cat` y
#endif /* !MIN_VERSION_base(4,5,0) */
instance Monoid Doc where
mempty = empty
mappend = Cat
instance Show Doc where
showsPrec _ = prettyS 80
class Pretty a where
ppr :: a -> Doc
pprPrec :: Int -> a -> Doc
pprList :: [a] -> Doc
ppr = pprPrec 0
pprPrec _ = ppr
pprList xs = list (map ppr xs)
instance Pretty Int where
ppr = text . show
instance Pretty Integer where
ppr = text . show
instance Pretty Float where
ppr = text . show
instance Pretty Double where
ppr = text . show
ratioPrec, ratioPrec1 :: Int
ratioPrec = 7 -- Precedence of ':%' constructor
ratioPrec1 = ratioPrec + 1
instance (Integral a, Pretty a) => Pretty (Ratio a) where
{-# SPECIALIZE instance Pretty Rational #-}
pprPrec p (x:%y) =
parensIf (p > ratioPrec) $
pprPrec ratioPrec1 x <+> char '%' <+> pprPrec ratioPrec1 y
instance Pretty Bool where
ppr = text . show
instance Pretty Char where
ppr = text . show
pprList = text . show
instance Pretty T.Text where
ppr = text . show
instance Pretty L.Text where
ppr = text . show
instance Pretty a => Pretty [a] where
ppr = pprList
instance Pretty () where
ppr () =
tuple []
instance (Pretty a, Pretty b)
=> Pretty (a, b) where
ppr (a, b) =
tuple [ppr a, ppr b]
instance (Pretty a, Pretty b, Pretty c)
=> Pretty (a, b, c) where
ppr (a, b, c) =
tuple [ppr a, ppr b, ppr c]
instance (Pretty a, Pretty b, Pretty c, Pretty d)
=> Pretty (a, b, c, d) where
ppr (a, b, c, d) =
tuple [ppr a, ppr b, ppr c, ppr d]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e)
=> Pretty (a, b, c, d, e) where
ppr (a, b, c, d, e) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f)
=> Pretty (a, b, c, d, e, f) where
ppr (a, b, c, d, e, f) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g)
=> Pretty (a, b, c, d, e, f, g) where
ppr (a, b, c, d, e, f, g) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g, Pretty h)
=> Pretty (a, b, c, d, e, f, g, h) where
ppr (a, b, c, d, e, f, g, h) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g, ppr h]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g, Pretty h, Pretty i)
=> Pretty (a, b, c, d, e, f, g, h, i) where
ppr (a, b, c, d, e, f, g, h, i) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g, ppr h, ppr i]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g, Pretty h, Pretty i, Pretty j)
=> Pretty (a, b, c, d, e, f, g, h, i, j) where
ppr (a, b, c, d, e, f, g, h, i, j) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g, ppr h, ppr i, ppr j]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g, Pretty h, Pretty i, Pretty j,
Pretty k)
=> Pretty (a, b, c, d, e, f, g, h, i, j, k) where
ppr (a, b, c, d, e, f, g, h, i, j, k) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g, ppr h, ppr i, ppr j,
ppr k]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g, Pretty h, Pretty i, Pretty j,
Pretty k, Pretty l)
=> Pretty (a, b, c, d, e, f, g, h, i, j, k, l) where
ppr (a, b, c, d, e, f, g, h, i, j, k, l) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g, ppr h, ppr i, ppr j,
ppr k, ppr l]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g, Pretty h, Pretty i, Pretty j,
Pretty k, Pretty l, Pretty m)
=> Pretty (a, b, c, d, e, f, g, h, i, j, k, l, m) where
ppr (a, b, c, d, e, f, g, h, i, j, k, l, m) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g, ppr h, ppr i, ppr j,
ppr k, ppr l, ppr m]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g, Pretty h, Pretty i, Pretty j,
Pretty k, Pretty l, Pretty m, Pretty n)
=> Pretty (a, b, c, d, e, f, g, h, i, j, k, l, m, n) where
ppr (a, b, c, d, e, f, g, h, i, j, k, l, m, n) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g, ppr h, ppr i, ppr j,
ppr k, ppr l, ppr m, ppr n]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g, Pretty h, Pretty i, Pretty j,
Pretty k, Pretty l, Pretty m, Pretty n, Pretty o)
=> Pretty (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) where
ppr (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g, ppr h, ppr i, ppr j,
ppr k, ppr l, ppr m, ppr n, ppr o]
instance Pretty a => Pretty (Maybe a) where
pprPrec _ Nothing = empty
pprPrec p (Just a) = pprPrec p a
instance Pretty Pos where
ppr p@(Pos _ l c _) =
text (posFile p) <> colon <> ppr l <> colon <> ppr c
instance Pretty Loc where
ppr NoLoc = text "<no location info>"
ppr (Loc p1@(Pos f1 l1 c1 _) p2@(Pos f2 l2 c2 _))
| f1 == f2 = text (posFile p1) <> colon <//> pprLineCol l1 c1 l2 c2
| otherwise = ppr p1 <> text "-" <> ppr p2
where
pprLineCol :: Int -> Int -> Int -> Int -> Doc
pprLineCol l1 c1 l2 c2
| l1 == l2 && c1 == c2 = ppr l1 <//> colon <//> ppr c1
| l1 == l2 && c1 /= c2 = ppr l1 <//> colon <//>
ppr c1 <> text "-" <> ppr c2
| otherwise = ppr l1 <//> colon <//> ppr c1
<> text "-" <>
ppr l2 <//> colon <//> ppr c2
instance Pretty x => Pretty (L x) where
pprPrec p (L _ x) = pprPrec p x
instance (Pretty k, Pretty v) => Pretty (Map.Map k v) where
ppr = pprList . Map.toList
instance Pretty a => Pretty (Set.Set a) where
ppr = pprList . Set.toList
instance Pretty Word8 where
ppr = text . show
instance Pretty Word16 where
ppr = text . show
instance Pretty Word32 where
ppr = text . show
instance Pretty Word64 where
ppr = text . show
instance Pretty Int8 where
ppr = text . show
instance Pretty Int16 where
ppr = text . show
instance Pretty Int32 where
ppr = text . show
instance Pretty Int64 where
ppr = text . show
|
flowbox-public/mainland-pretty
|
Text/PrettyPrint/Mainland.hs
|
Haskell
|
bsd-3-clause
| 27,921
|
-----------------------------------------------------------------------------
-- |
-- Module : TestSuite.Optimization.Quantified
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- Test suite for optimization iwth quantifiers
-----------------------------------------------------------------------------
{-# LANGUAGE ScopedTypeVariables #-}
module TestSuite.Optimization.Quantified(tests) where
import Data.List (isPrefixOf)
import Utils.SBVTestFramework
import qualified Control.Exception as C
-- Test suite
tests :: TestTree
tests =
testGroup "Optimization.Reals"
[ goldenString "optQuant1" $ optE q1
, goldenVsStringShow "optQuant2" $ opt q2
, goldenVsStringShow "optQuant3" $ opt q3
, goldenVsStringShow "optQuant4" $ opt q4
, goldenString "optQuant5" $ optE q5
]
where opt = optimize Lexicographic
optE q = (show <$> optimize Lexicographic q) `C.catch` (\(e::C.SomeException) -> return (pick (show e)))
pick s = unlines [l | l <- lines s, "***" `isPrefixOf` l]
q1 :: Goal
q1 = do a <- sInteger "a"
[b1, b2] <- sIntegers ["b1", "b2"]
x <- forall "x" :: Symbolic SInteger
constrain $ 2 * (a * x + b1) .== 2
constrain $ 4 * (a * x + b2) .== 4
constrain $ a .>= 0
minimize "goal" $ 2*x
q2 :: Goal
q2 = do a <- sInteger "a"
[b1, b2] <- sIntegers ["b1", "b2"]
x <- forall "x" :: Symbolic SInteger
constrain $ 2 * (a * x + b1) .== 2
constrain $ 4 * (a * x + b2) .== 4
constrain $ a .>= 0
minimize "goal" a
q3 :: Goal
q3 = do a <- sInteger "a"
[b1, b2] <- sIntegers ["b1", "b2"]
minimize "goal" a
x <- forall "x" :: Symbolic SInteger
constrain $ 2 * (a * x + b1) .== 2
constrain $ 4 * (a * x + b2) .== 4
constrain $ a .>= 0
q4 :: Goal
q4 = do a <- sInteger "a"
[b1, b2] <- sIntegers ["b1", "b2"]
minimize "goal" $ 2*a
x <- forall "x" :: Symbolic SInteger
constrain $ 2 * (a * x + b1) .== 2
constrain $ 4 * (a * x + b2) .== 4
constrain $ a .>= 0
q5 :: Goal
q5 = do a <- sInteger "a"
x <- forall "x" :: Symbolic SInteger
y <- forall "y" :: Symbolic SInteger
b <- sInteger "b"
constrain $ a .>= 0
constrain $ b .>= 0
constrain $ x+y .>= 0
minimize "goal" $ a+b
{-# ANN module ("HLint: ignore Reduce duplication" :: String) #-}
|
josefs/sbv
|
SBVTestSuite/TestSuite/Optimization/Quantified.hs
|
Haskell
|
bsd-3-clause
| 2,532
|
{-# LANGUAGE NoImplicitPrelude #-}
-- |
-- Module: $HEADER$
-- Description: Tray icon with configurable popup menu that uses wxWidgets as
-- a backend.
-- Copyright: (c) 2015 Peter Trško
-- License: BSD3
--
-- Maintainer: peter.trsko@gmail.com
-- Stability: experimental
-- Portability: NoImplicitPrelude
--
-- Tray icon with configurable popup menu that uses wxWidgets as a backend.
module Main (main)
where
import Control.Exception (SomeException, handle)
import Control.Monad (Monad((>>=), return), (=<<), mapM_, void)
import Data.Bool ((||), otherwise)
import Data.Eq (Eq((==)))
import Data.Function ((.), ($), flip)
import Data.Functor ((<$))
import Data.Monoid ((<>))
import Data.String (String)
import System.Environment (getArgs)
import System.Exit (exitFailure, exitSuccess)
import System.IO (IO, hPrint, hPutStrLn, stderr)
import System.FilePath ((</>))
import System.Process (system)
import Control.Lens ((^.), foldMapOf)
import Graphics.UI.WX
( Menu
, Prop((:=))
, command
, help
, menuItem
, menuPane
, on
, start
, text
)
import Graphics.UI.WXCore.Events
( EventTaskBarIcon(TaskBarIconLeftDown, TaskBarIconRightDown)
, evtHandlerOnTaskBarIconEvent
)
import Graphics.UI.WXCore.Image (iconCreateFromFile)
import Graphics.UI.WXCore.WxcClasses
( taskBarIconCreate
, taskBarIconSetIcon
, taskBarIconPopupMenu
)
import Graphics.UI.WXCore.WxcClassTypes (Icon, TaskBarIcon)
import Graphics.UI.WXCore.WxcTypes (sizeNull)
import Options.Applicative (fullDesc)
import System.Environment.XDG.BaseDir (getUserConfigFile)
import Main.ConfigFile (getMenuItems, readConfigFile, readUserConfigFile)
import Main.Options (execParser, optionsParser)
import Main.Type.MenuItem (MenuItem)
import Main.Type.MenuItem.Lens (menuItems)
import qualified Main.Type.MenuItem.Lens as MenuItem
( command
, description
, name
)
import qualified Main.Type.Options.Lens as Options (iconFile)
import Paths_toolbox (getDataFileName)
taskBarIcon
:: Icon ()
-> String
-> (TaskBarIcon () -> EventTaskBarIcon -> IO ())
-> IO ()
taskBarIcon icon str f = do
tbi <- taskBarIconCreate
_ <- taskBarIconSetIcon tbi icon str
evtHandlerOnTaskBarIconEvent tbi $ f tbi
main :: IO ()
main = getArgs >>= execParser optionsParser fullDesc >>= \options -> start $ do
menu <- getMenuItems options onConfigError
[ readConfigFile getDataFileName
, readUserConfigFile (getUserConfigFile "toolbox")
]
icon <- flip iconCreateFromFile sizeNull
=<< case options ^. Options.iconFile of
fileName@(c : _)
| c == '/' -> return fileName
| otherwise -> getDataFileName fileName
"" -> getDataFileName $ "icons" </> iconFileName
toolboxMenu <- menuPane [text := "Toolbox"]
foldMapOf menuItems (mapM_ $ addMenuItem toolboxMenu) menu
addMenuItem' toolboxMenu "Exit toolbox" "Exit toolbox" exitSuccess
taskBarIcon icon "Toolbox" $ \tbi evt -> case evt of
_ | evt == TaskBarIconLeftDown || evt == TaskBarIconRightDown
-> () <$ taskBarIconPopupMenu tbi toolboxMenu
| otherwise
-> return ()
where
iconFileName = "elegantthemes-tools-icon.png"
-- iconFileName = "elegantthemes-beautiful-flat-icons-tools-icon.png"
handleExceptions = handle $ \e -> hPrint stderr (e :: SomeException)
addMenuItem :: Menu a -> MenuItem -> IO ()
addMenuItem m item = addMenuItem' m
(item ^. MenuItem.name)
(item ^. MenuItem.description)
. handleExceptions . void . system $ item ^. MenuItem.command
addMenuItem' :: Menu a -> String -> String -> IO () -> IO ()
addMenuItem' m name desc action = () <$ menuItem m
[ text := name
, help := desc
, on command := action
]
onConfigError msg = do
hPutStrLn stderr $ "Parsing configuration failed: " <> msg
exitFailure
|
trskop/toolbox-tray-icon
|
src/WxMain.hs
|
Haskell
|
bsd-3-clause
| 4,019
|
{-# OPTIONS -fglasgow-exts #-}
--
-- Copyright (C) 2004-5 Don Stewart - http://www.cse.unsw.edu.au/~dons
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
-- USA
--
-- | An interface to the GHC runtime's dynamic linker, providing runtime
-- loading and linking of Haskell object files, commonly known as
-- /plugins/.
module System.Plugins.Load (
-- * The @LoadStatus@ type
LoadStatus(..)
-- * High-level interface
, load
, load_
, dynload
, pdynload
, pdynload_
, unload
, unloadAll
, reload
, Module(..)
-- * Low-level interface
, initLinker -- start it up
, loadModule -- load a vanilla .o
, loadFunction -- retrieve a function from an object
, loadFunction_ -- retrieve a function from an object
, loadPackageFunction
, loadPackage -- load a ghc library and its cbits
, unloadPackage -- unload a ghc library and its cbits
, loadPackageWith -- load a pkg using the package.conf provided
, loadShared -- load a .so object file
, resolveObjs -- and resolve symbols
, loadRawObject -- load a bare .o. no dep chasing, no .hi file reading
, Symbol
, getImports
) where
#include "../../../config.h"
import System.Plugins.Make ( build )
import System.Plugins.Env
import System.Plugins.Utils
import System.Plugins.Consts ( sysPkgSuffix, hiSuf, prefixUnderscore )
import System.Plugins.LoadTypes
-- import Language.Hi.Parser
import BinIface
import HscTypes
import Module (moduleName, moduleNameString)
import PackageConfig (packageIdString)
import HscMain (newHscEnv)
import TcRnMonad (initTcRnIf)
import Data.Dynamic ( fromDynamic, Dynamic )
import Data.Typeable ( Typeable )
import Data.List ( isSuffixOf, nub, nubBy )
import Control.Monad ( when, filterM, liftM )
import System.Directory ( doesFileExist, removeFile )
import Foreign.C.String ( CString, withCString, peekCString )
import GHC.Ptr ( Ptr(..), nullPtr )
import GHC.Exts ( addrToHValue# )
import GHC.Prim ( unsafeCoerce# )
#if DEBUG
import System.IO ( hFlush, stdout )
#endif
import System.IO ( hClose )
ifaceModuleName = moduleNameString . moduleName . mi_module
readBinIface' :: FilePath -> IO ModIface
readBinIface' hi_path = do
-- kludgy as hell
e <- newHscEnv undefined
initTcRnIf 'r' e undefined undefined (readBinIface hi_path)
-- TODO need a loadPackage p package.conf :: IO () primitive
--
-- | The @LoadStatus@ type encodes the return status of functions that
-- perform dynamic loading in a type isomorphic to 'Either'. Failure
-- returns a list of error strings, success returns a reference to a
-- loaded module, and the Haskell value corresponding to the symbol that
-- was indexed.
--
data LoadStatus a
= LoadSuccess Module a
| LoadFailure Errors
--
-- | 'load' is the basic interface to the dynamic loader. A call to
-- 'load' imports a single object file into the caller's address space,
-- returning the value associated with the symbol requested. Libraries
-- and modules that the requested module depends upon are loaded and
-- linked in turn.
--
-- The first argument is the path to the object file to load, the second
-- argument is a list of directories to search for dependent modules.
-- The third argument is a list of paths to user-defined, but
-- unregistered, /package.conf/ files. The 'Symbol' argument is the
-- symbol name of the value you with to retrieve.
--
-- The value returned must be given an explicit type signature, or
-- provided with appropriate type constraints such that Haskell compiler
-- can determine the expected type returned by 'load', as the return
-- type is notionally polymorphic.
--
-- Example:
--
-- > do mv <- load "Plugin.o" ["api"] [] "resource"
-- > case mv of
-- > LoadFailure msg -> print msg
-- > LoadSuccess _ v -> return v
--
load :: FilePath -- ^ object file
-> [FilePath] -- ^ any include paths
-> [PackageConf] -- ^ list of package.conf paths
-> Symbol -- ^ symbol to find
-> IO (LoadStatus a)
load obj incpaths pkgconfs sym = do
initLinker
-- load extra package information
mapM_ addPkgConf pkgconfs
(hif,moduleDeps) <- loadDepends obj incpaths
-- why is this the package name?
#if DEBUG
putStr (' ':(decode $ ifaceModuleName hif)) >> hFlush stdout
#endif
m' <- loadObject obj . Object . ifaceModuleName $ hif
let m = m' { iface = hif }
resolveObjs (mapM_ unloadAll (m:moduleDeps))
#if DEBUG
putStrLn " ... done" >> hFlush stdout
#endif
addModuleDeps m' moduleDeps
v <- loadFunction m sym
return $ case v of
Nothing -> LoadFailure ["load: couldn't find symbol <<"++sym++">>"]
Just a -> LoadSuccess m a
--
-- | Like load, but doesn't want a package.conf arg (they are rarely used)
--
load_ :: FilePath -> [FilePath] -> Symbol -> IO (LoadStatus a)
load_ o i s = load o i [] s
--
-- A work-around for Dynamics. The keys used to compare two TypeReps are
-- somehow not equal for the same type in hs-plugin's loaded objects.
-- Solution: implement our own dynamics...
--
-- The problem with dynload is that it requires the plugin to export
-- a value that is a Dynamic (in our case a (TypeRep,a) pair). If this
-- is not the case, we core dump. Use pdynload if you don't trust the
-- user to supply you with a Dynamic
--
dynload :: Typeable a
=> FilePath
-> [FilePath]
-> [PackageConf]
-> Symbol
-> IO (LoadStatus a)
dynload obj incpaths pkgconfs sym = do
s <- load obj incpaths pkgconfs sym
case s of e@(LoadFailure _) -> return e
LoadSuccess m dyn_v -> return $
case fromDynamic (unsafeCoerce# dyn_v :: Dynamic) of
Just v' -> LoadSuccess m v'
Nothing -> LoadFailure ["Mismatched types in interface"]
------------------------------------------------------------------------
--
-- The super-replacement for dynload
--
-- Use GHC at runtime so we get staged type inference, providing full
-- power dynamics, *on module interfaces only*. This is quite suitable
-- for plugins, of coures :)
--
-- TODO where does the .hc file go in the call to build() ?
--
pdynload :: FilePath -- ^ object to load
-> [FilePath] -- ^ include paths
-> [PackageConf] -- ^ package confs
-> Type -- ^ API type
-> Symbol -- ^ symbol
-> IO (LoadStatus a)
pdynload object incpaths pkgconfs ty sym = do
#if DEBUG
putStr "Checking types ... " >> hFlush stdout
#endif
errors <- unify object incpaths [] ty sym
#if DEBUG
putStrLn "done"
#endif
if null errors
then load object incpaths pkgconfs sym
else return $ LoadFailure errors
--
-- | Like pdynload, but you can specify extra arguments to the
-- typechecker.
--
pdynload_ :: FilePath -- ^ object to load
-> [FilePath] -- ^ include paths for loading
-> [PackageConf] -- ^ any extra package.conf files
-> [Arg] -- ^ extra arguments to ghc, when typechecking
-> Type -- ^ expected type
-> Symbol -- ^ symbol to load
-> IO (LoadStatus a)
pdynload_ object incpaths pkgconfs args ty sym = do
#if DEBUG
putStr "Checking types ... " >> hFlush stdout
#endif
errors <- unify object incpaths args ty sym
#if DEBUG
putStrLn "done"
#endif
if null errors
then load object incpaths pkgconfs sym
else return $ LoadFailure errors
------------------------------------------------------------------------
-- run the typechecker over the constraint file
--
-- Problem: if the user depends on a non-auto package to build the
-- module, then that package will not be in scope when we try to build
-- the module, when performing `unify'. Normally make() will handle this
-- (as it takes extra ghc args). pdynload ignores these, atm -- but it
-- shouldn't. Consider a pdynload() that accepts extra -package flags?
--
-- Also, pdynload() should accept extra in-scope modules.
-- Maybe other stuff we want to hack in here.
--
unify obj incs args ty sym = do
(tmpf,hdl) <- mkTemp
(tmpf1,hdl1) <- mkTemp -- and send .hi file here.
hClose hdl1
let nm = mkModid (basename tmpf)
src = mkTest nm (hierize' . mkModid . hierize $ obj)
(fst $ break (=='.') ty) ty sym
is = map ("-i"++) incs -- api
i = "-i" ++ dirname obj -- plugin
hWrite hdl src
e <- build tmpf tmpf1 (i:is++args++["-fno-code","-ohi "++tmpf1])
mapM_ removeFile [tmpf,tmpf1]
return e
where
-- fix up hierarchical names
hierize [] = []
hierize ('/':cs) = '\\' : hierize cs
hierize (c:cs) = c : hierize cs
hierize'[] = []
hierize' ('\\':cs) = '.' : hierize' cs
hierize' (c:cs) = c : hierize' cs
mkTest modnm plugin api ty sym =
"module "++ modnm ++" where" ++
"\nimport qualified " ++ plugin ++
"\nimport qualified " ++ api ++
"{-# LINE 1 \"<typecheck>\" #-}" ++
"\n_ = "++ plugin ++"."++ sym ++" :: "++ty
------------------------------------------------------------------------
{-
--
-- old version that tried to rip stuff from .hi files
--
pdynload obj incpaths pkgconfs sym ty = do
(m, v) <- load obj incpaths pkgconfs sym
ty' <- mungeIface sym obj
if ty == ty'
then return $ Just (m, v)
else return Nothing -- mismatched types
where
-- grab the iface output from GHC. find the line relevant to our
-- symbol. grab the string rep of the type.
mungeIface sym o = do
let hi = replaceSuffix o hiSuf
(out,_) <- exec ghc ["--show-iface", hi]
case find (\s -> (sym ++ " :: ") `isPrefixOf` s) out of
Nothing -> return undefined
Just v -> do let v' = drop 3 $ dropWhile (/= ':') v
return v'
-}
{-
--
-- a version of load the also unwraps and types a Dynamic object
--
dynload2 :: Typeable a =>
FilePath ->
FilePath ->
Maybe [PackageConf] ->
Symbol ->
IO (Module, a)
dynload2 obj incpath pkgconfs sym = do
(m, v) <- load obj incpath pkgconfs sym
case fromDynamic v of
Nothing -> panic $ "load: couldn't type "++(show v)
Just a -> return (m,a)
-}
------------------------------------------------------------------------
--
-- | unload a module (not its dependencies)
-- we have the dependencies, so cascaded unloading is possible
--
-- once you unload it, you can't 'load' it again, you have to 'reload'
-- it. Cause we don't unload all the dependencies
--
unload :: Module -> IO ()
unload m = rmModuleDeps m >> unloadObj m
------------------------------------------------------------------------
--
-- | unload a module and its dependencies
-- we have the dependencies, so cascaded unloading is possible
--
unloadAll :: Module -> IO ()
unloadAll m = do moduleDeps <- getModuleDeps m
rmModuleDeps m
mapM_ unloadAll moduleDeps
unload m
--
-- | this will be nice for panTHeon, needs thinking about the interface
-- reload a single object file. don't care about depends, assume they
-- are loaded. (should use state to store all this)
--
-- assumes you've already done a 'load'
--
-- should factor the code
--
reload :: Module -> Symbol -> IO (LoadStatus a)
reload m@(Module{path = p, iface = hi}) sym = do
unloadObj m -- unload module (and delete)
#if DEBUG
putStr ("Reloading "++(mname m)++" ... ") >> hFlush stdout
#endif
m_ <- loadObject p . Object . ifaceModuleName $ hi -- load object at path p
let m' = m_ { iface = hi }
resolveObjs (unloadAll m)
#if DEBUG
putStrLn "done" >> hFlush stdout
#endif
v <- loadFunction m' sym
return $ case v of
Nothing -> LoadFailure ["load: couldn't find symbol <<"++sym++">>"]
Just a -> LoadSuccess m' a
-- ---------------------------------------------------------------------
-- This is a stripped-down version of André Pang's runtime_loader,
-- which in turn is based on GHC's ghci\/ObjLinker.lhs binding
--
-- Load and unload\/Haskell modules at runtime. This is not really
-- \'dynamic loading\', as such -- that implies that you\'re working
-- with proper shared libraries, whereas this is far more simple and
-- only loads object files. But it achieves the same goal: you can
-- load a Haskell module at runtime, load a function from it, and run
-- the function. I have no idea if this works for types, but that
-- doesn\'t mean that you can\'t try it :).
--
-- read $fptools\/ghc\/compiler\/ghci\/ObjLinker.lhs for how to use this stuff
--
------------------------------------------------------------------------
-- | Call the initLinker function first, before calling any of the other
-- functions in this module - otherwise you\'ll get unresolved symbols.
-- initLinker :: IO ()
-- our initLinker transparently calls the one in GHC
--
-- | Load a function from a module (which must be loaded and resolved first).
--
loadFunction :: Module -- ^ The module the value is in
-> String -- ^ Symbol name of value
-> IO (Maybe a) -- ^ The value you want
loadFunction (Module { iface = i }) valsym
= loadFunction_ (ifaceModuleName i) valsym
loadFunction_ :: String
-> String
-> IO (Maybe a)
loadFunction_ = loadFunction__ Nothing
loadFunction__ :: Maybe String
-> String
-> String
-> IO (Maybe a)
loadFunction__ pkg m valsym
= do let symbol = prefixUnderscore++(maybe "" (\p -> encode p++"_") pkg)
++encode m++"_"++(encode valsym)++"_closure"
#if DEBUG
putStrLn $ "Looking for <<"++symbol++">>"
#endif
ptr@(~(Ptr addr)) <- withCString symbol c_lookupSymbol
if (ptr == nullPtr)
then return Nothing
else case addrToHValue# addr of
(# hval #) -> return ( Just hval )
-- | Loads a function from a package module, given the package name,
-- module name and symbol name.
loadPackageFunction :: String -- ^ Package name, including version number.
-> String -- ^ Module name
-> String -- ^ Symbol to lookup in the module
-> IO (Maybe a)
loadPackageFunction pkgName modName functionName =
do loadPackage pkgName
resolveObjs (unloadPackage pkgName)
loadFunction__ (Just pkgName) modName functionName
--
-- | Load a GHC-compiled Haskell vanilla object file.
-- The first arg is the path to the object file
--
-- We make it idempotent to stop the nasty problem of loading the same
-- .o twice. Also the rts is a very special package that is already
-- loaded, even if we ask it to be loaded. N.B. we should insert it in
-- the list of known packages.
--
-- NB the environment stores the *full path* to an object. So if you
-- want to know if a module is already loaded, you need to supply the
-- *path* to that object, not the name.
--
-- NB -- let's try just the module name.
--
-- loadObject loads normal .o objs, and packages too. .o objs come with
-- a nice canonical Z-encoded modid. packages just have a simple name.
-- Do we want to ensure they won't clash? Probably.
--
--
-- the second argument to loadObject is a string to use as the unique
-- identifier for this object. For normal .o objects, it should be the
-- Z-encoded modid from the .hi file. For archives\/packages, we can
-- probably get away with the package name
--
loadObject :: FilePath -> Key -> IO Module
loadObject p ky@(Object k) = loadObject' p ky k
loadObject p ky@(Package k) = loadObject' p ky k
loadObject' :: FilePath -> Key -> String -> IO Module
loadObject' p ky k
| ("HSrts"++sysPkgSuffix) `isSuffixOf` p = return (emptyMod p)
| otherwise
= do alreadyLoaded <- isLoaded k
when (not alreadyLoaded) $ do
r <- withCString p c_loadObj
when (not r) (panic $ "Could not load module `"++p++"'")
addModule k (emptyMod p) -- needs to Z-encode module name
return (emptyMod p)
where emptyMod q = Module q (mkModid q) Vanilla undefined ky
--
-- load a single object. no dependencies. You should know what you're
-- doing.
--
loadModule :: FilePath -> IO Module
loadModule obj = do
let hifile = replaceSuffix obj hiSuf
exists <- doesFileExist hifile
if (not exists)
then error $ "No .hi file found for "++show obj
else do hiface <- readBinIface' hifile
loadObject obj (Object (ifaceModuleName hiface))
--
-- | Load a generic .o file, good for loading C objects.
-- You should know what you're doing..
-- Returns a fairly meaningless iface value.
--
loadRawObject :: FilePath -> IO Module
loadRawObject obj = loadObject obj (Object k)
where
k = encode (mkModid obj) -- Z-encoded module name
--
-- | Resolve (link) the modules loaded by the 'loadObject' function.
--
resolveObjs :: IO a -> IO ()
resolveObjs unloadLoaded
= do r <- c_resolveObjs
when (not r) $ unloadLoaded >> panic "resolvedObjs failed."
-- | Unload a module
unloadObj :: Module -> IO ()
unloadObj (Module { path = p, kind = k, key = ky }) = case k of
Vanilla -> withCString p $ \c_p -> do
removed <- rmModule name
when (removed) $ do r <- c_unloadObj c_p
when (not r) (panic "unloadObj: failed")
Shared -> return () -- can't unload .so?
where name = case ky of Object s -> s ; Package pk -> pk
--
-- | from ghci\/ObjLinker.c
--
-- Load a .so type object file.
--
loadShared :: FilePath -> IO Module
loadShared str = do
#if DEBUG
putStrLn $ " shared: " ++ str
#endif
maybe_errmsg <- withCString str $ \dll -> c_addDLL dll
if maybe_errmsg == nullPtr
then return (Module str (mkModid str) Shared undefined (Package (mkModid str)))
else do e <- peekCString maybe_errmsg
panic $ "loadShared: couldn't load `"++str++"\' because "++e
--
-- Load a -package that we might need, implicitly loading the cbits too
-- The argument is the name of package (e.g. \"concurrent\")
--
-- How to find a package is determined by the package.conf info we store
-- in the environment. It is just a matter of looking it up.
--
-- Not printing names of dependent pkgs
--
loadPackage :: String -> IO ()
loadPackage p = do
#if DEBUG
putStr (' ':p) >> hFlush stdout
#endif
(libs,dlls) <- lookupPkg p
mapM_ (\l -> loadObject l (Package (mkModid l))) libs
#if DEBUG
putStr (' ':show libs) >> hFlush stdout
putStr (' ':show dlls) >> hFlush stdout
#endif
mapM_ loadShared dlls
--
-- Unload a -package, that has already been loaded. Unload the cbits
-- too. The argument is the name of the package.
--
-- May need to check if it exists.
--
-- Note that we currently need to unload everything. grumble grumble.
--
-- We need to add the version number to the package name with 6.4 and
-- over. "yi-0.1" for example. This is a bug really.
--
unloadPackage :: String -> IO ()
unloadPackage pkg = do
let pkg' = takeWhile (/= '-') pkg -- in case of *-0.1
libs <- liftM (\(a,_) -> (filter (isSublistOf pkg') ) a) (lookupPkg pkg)
flip mapM_ libs $ \p -> withCString p $ \c_p -> do
r <- c_unloadObj c_p
when (not r) (panic "unloadObj: failed")
rmModule (mkModid p) -- unrecord this module
--
-- load a package using the given package.conf to help
-- TODO should report if it doesn't actually load the package, instead
-- of mapM_ doing nothing like above.
--
loadPackageWith :: String -> [PackageConf] -> IO ()
loadPackageWith p pkgconfs = do
#if DEBUG
putStr "Loading package" >> hFlush stdout
#endif
mapM_ addPkgConf pkgconfs
loadPackage p
#if DEBUG
putStrLn " done"
#endif
-- ---------------------------------------------------------------------
-- module dependency loading
--
-- given an Foo.o vanilla object file, supposed to be a plugin compiled
-- by our library, find the associated .hi file. If this is found, load
-- the dependencies, packages first, then the modules. If it doesn't
-- exist, assume the user knows what they are doing and continue. The
-- linker will crash on them anyway. Second argument is any include
-- paths to search in
--
-- ToDo problem with absolute and relative paths, and different forms of
-- relative paths. A user may cause a dependency to be loaded, which
-- will search the incpaths, and perhaps find "./Foo.o". The user may
-- then explicitly load "Foo.o". These are the same, and the loader
-- should ignore the second load request. However, isLoaded will say
-- that "Foo.o" is not loaded, as the full string is used as a key to
-- the modenv fm. We need a canonical form for the keys -- is basename
-- good enough?
--
loadDepends :: FilePath -> [FilePath] -> IO (ModIface,[Module])
loadDepends obj incpaths = do
let hifile = replaceSuffix obj hiSuf
exists <- doesFileExist hifile
if (not exists)
then do
#if DEBUG
putStrLn "No .hi file found." >> hFlush stdout
#endif
return (undefined,[]) -- could be considered fatal
else do hiface <- readBinIface' hifile
let ds = mi_deps hiface
-- remove ones that we've already loaded
ds' <- filterM loaded . map (moduleNameString . fst) . dep_mods $ ds
-- now, try to generate a path to the actual .o file
-- fix up hierachical names
let mods_ = map (\s -> (s, map (\c ->
if c == '.' then '/' else c) $ s)) ds'
-- construct a list of possible dependent modules to load
let mods = concatMap (\p ->
map (\(hi,m) -> (hi,p </> m++".o")) mods_) incpaths
-- remove modules that don't exist
mods' <- filterM (\(_,y) -> doesFileExist y) $
nubBy (\v u -> snd v == snd u) mods
-- now remove duplicate valid paths to the same object
let mods'' = nubBy (\v u -> fst v == fst u) mods'
-- and find some packages to load, as well.
let ps = dep_pkgs ds
ps' <- filterM loaded . map packageIdString . nub $ ps
#if DEBUG
when (not (null ps')) $
putStr "Loading package" >> hFlush stdout
#endif
mapM_ loadPackage ps'
#if DEBUG
when (not (null ps')) $
putStr " ... linking ... " >> hFlush stdout
#endif
resolveObjs (mapM_ unloadPackage ps')
#if DEBUG
when (not (null ps')) $ putStrLn "done"
putStr "Loading object"
mapM_ (\(m,_) -> putStr (" "++ m) >> hFlush stdout) mods''
#endif
moduleDeps <- mapM (\(hi,m) -> loadObject m (Object hi)) mods''
return (hiface,moduleDeps)
-- ---------------------------------------------------------------------
-- Nice interface to .hi parser
--
getImports :: String -> IO [String]
getImports m = do
hi <- readBinIface' (m ++ hiSuf)
return . map (moduleNameString . fst) . dep_mods . mi_deps $ hi
-- ---------------------------------------------------------------------
-- C interface
--
foreign import ccall threadsafe "lookupSymbol"
c_lookupSymbol :: CString -> IO (Ptr a)
foreign import ccall unsafe "loadObj"
c_loadObj :: CString -> IO Bool
foreign import ccall unsafe "unloadObj"
c_unloadObj :: CString -> IO Bool
foreign import ccall unsafe "resolveObjs"
c_resolveObjs :: IO Bool
foreign import ccall unsafe "addDLL"
c_addDLL :: CString -> IO CString
foreign import ccall unsafe "initLinker"
initLinker :: IO ()
|
abuiles/turbinado-blog
|
tmp/dependencies/hs-plugins-1.3.1/src/System/Plugins/Load.hs
|
Haskell
|
bsd-3-clause
| 25,431
|
-- | Definitions of kinds of factions present in a game, both human
-- and computer-controlled.
module Content.FactionKind
( -- * Group name patterns
pattern EXPLORER_REPRESENTATIVE, pattern EXPLORER_SHORT, pattern EXPLORER_NO_ESCAPE, pattern EXPLORER_MEDIUM, pattern EXPLORER_TRAPPED, pattern EXPLORER_AUTOMATED, pattern EXPLORER_AUTOMATED_TRAPPED, pattern EXPLORER_CAPTIVE, pattern EXPLORER_PACIFIST, pattern COMPETITOR_REPRESENTATIVE, pattern COMPETITOR_SHORT, pattern COMPETITOR_NO_ESCAPE, pattern CIVILIAN_REPRESENTATIVE, pattern CONVICT_REPRESENTATIVE, pattern MONSTER_REPRESENTATIVE, pattern MONSTER_ANTI, pattern MONSTER_ANTI_CAPTIVE, pattern MONSTER_ANTI_PACIFIST, pattern MONSTER_TOURIST, pattern MONSTER_TOURIST_PASSIVE, pattern MONSTER_CAPTIVE, pattern MONSTER_CAPTIVE_NARRATING, pattern ANIMAL_REPRESENTATIVE, pattern ANIMAL_MAGNIFICENT, pattern ANIMAL_EXQUISITE, pattern ANIMAL_CAPTIVE, pattern ANIMAL_NARRATING, pattern ANIMAL_MAGNIFICENT_NARRATING, pattern ANIMAL_CAPTIVE_NARRATING, pattern HORROR_REPRESENTATIVE, pattern HORROR_CAPTIVE, pattern HORROR_PACIFIST
, pattern REPRESENTATIVE
, groupNamesSingleton, groupNames
, -- * Content
content
#ifdef EXPOSE_INTERNAL
-- * Group name patterns
#endif
) where
import Prelude ()
import Game.LambdaHack.Core.Prelude
import Game.LambdaHack.Content.FactionKind
import qualified Game.LambdaHack.Content.ItemKind as IK
import Game.LambdaHack.Definition.Ability
import Game.LambdaHack.Definition.Defs
import Game.LambdaHack.Definition.DefsInternal
import Content.ItemKindActor
import Content.ItemKindOrgan
-- * Group name patterns
groupNamesSingleton :: [GroupName FactionKind]
groupNamesSingleton =
[EXPLORER_REPRESENTATIVE, EXPLORER_SHORT, EXPLORER_NO_ESCAPE, EXPLORER_MEDIUM, EXPLORER_TRAPPED, EXPLORER_AUTOMATED, EXPLORER_AUTOMATED_TRAPPED, EXPLORER_CAPTIVE, EXPLORER_PACIFIST, COMPETITOR_REPRESENTATIVE, COMPETITOR_SHORT, COMPETITOR_NO_ESCAPE, CIVILIAN_REPRESENTATIVE, CONVICT_REPRESENTATIVE, MONSTER_REPRESENTATIVE, MONSTER_ANTI, MONSTER_ANTI_CAPTIVE, MONSTER_ANTI_PACIFIST, MONSTER_TOURIST, MONSTER_TOURIST_PASSIVE, MONSTER_CAPTIVE, MONSTER_CAPTIVE_NARRATING, ANIMAL_REPRESENTATIVE, ANIMAL_MAGNIFICENT, ANIMAL_EXQUISITE, ANIMAL_CAPTIVE, ANIMAL_NARRATING, ANIMAL_MAGNIFICENT_NARRATING, ANIMAL_CAPTIVE_NARRATING, HORROR_REPRESENTATIVE, HORROR_CAPTIVE, HORROR_PACIFIST]
pattern EXPLORER_REPRESENTATIVE, EXPLORER_SHORT, EXPLORER_NO_ESCAPE, EXPLORER_MEDIUM, EXPLORER_TRAPPED, EXPLORER_AUTOMATED, EXPLORER_AUTOMATED_TRAPPED, EXPLORER_CAPTIVE, EXPLORER_PACIFIST, COMPETITOR_REPRESENTATIVE, COMPETITOR_SHORT, COMPETITOR_NO_ESCAPE, CIVILIAN_REPRESENTATIVE, CONVICT_REPRESENTATIVE, MONSTER_REPRESENTATIVE, MONSTER_ANTI, MONSTER_ANTI_CAPTIVE, MONSTER_ANTI_PACIFIST, MONSTER_TOURIST, MONSTER_TOURIST_PASSIVE, MONSTER_CAPTIVE, MONSTER_CAPTIVE_NARRATING, ANIMAL_REPRESENTATIVE, ANIMAL_MAGNIFICENT, ANIMAL_EXQUISITE, ANIMAL_CAPTIVE, ANIMAL_NARRATING, ANIMAL_MAGNIFICENT_NARRATING, ANIMAL_CAPTIVE_NARRATING, HORROR_REPRESENTATIVE, HORROR_CAPTIVE, HORROR_PACIFIST :: GroupName FactionKind
groupNames :: [GroupName FactionKind]
groupNames = [REPRESENTATIVE]
pattern REPRESENTATIVE :: GroupName FactionKind
pattern REPRESENTATIVE = GroupName "representative"
pattern EXPLORER_REPRESENTATIVE = GroupName "explorer"
pattern EXPLORER_SHORT = GroupName "explorer short"
pattern EXPLORER_NO_ESCAPE = GroupName "explorer no escape"
pattern EXPLORER_MEDIUM = GroupName "explorer medium"
pattern EXPLORER_TRAPPED = GroupName "explorer trapped"
pattern EXPLORER_AUTOMATED = GroupName "explorer automated"
pattern EXPLORER_AUTOMATED_TRAPPED = GroupName "explorer automated trapped"
pattern EXPLORER_CAPTIVE = GroupName "explorer captive"
pattern EXPLORER_PACIFIST = GroupName "explorer pacifist"
pattern COMPETITOR_REPRESENTATIVE = GroupName "competitor"
pattern COMPETITOR_SHORT = GroupName "competitor short"
pattern COMPETITOR_NO_ESCAPE = GroupName "competitor no escape"
pattern CIVILIAN_REPRESENTATIVE = GroupName "civilian"
pattern CONVICT_REPRESENTATIVE = GroupName "convict"
pattern MONSTER_REPRESENTATIVE = GroupName "monster"
pattern MONSTER_ANTI = GroupName "monster anti"
pattern MONSTER_ANTI_CAPTIVE = GroupName "monster anti captive"
pattern MONSTER_ANTI_PACIFIST = GroupName "monster anti pacifist"
pattern MONSTER_TOURIST = GroupName "monster tourist"
pattern MONSTER_TOURIST_PASSIVE = GroupName "monster tourist passive"
pattern MONSTER_CAPTIVE = GroupName "monster captive"
pattern MONSTER_CAPTIVE_NARRATING = GroupName "monster captive narrating"
pattern ANIMAL_REPRESENTATIVE = GroupName "animal"
pattern ANIMAL_MAGNIFICENT = GroupName "animal magnificent"
pattern ANIMAL_EXQUISITE = GroupName "animal exquisite"
pattern ANIMAL_CAPTIVE = GroupName "animal captive"
pattern ANIMAL_NARRATING = GroupName "animal narrating"
pattern ANIMAL_MAGNIFICENT_NARRATING = GroupName "animal magnificent narrating"
pattern ANIMAL_CAPTIVE_NARRATING = GroupName "animal captive narrating"
pattern HORROR_REPRESENTATIVE = GroupName "horror"
pattern HORROR_CAPTIVE = GroupName "horror captive"
pattern HORROR_PACIFIST = GroupName "horror pacifist"
-- * Teams
teamCompetitor, teamCivilian, teamConvict, teamMonster, teamAnimal, teamHorror, teamOther :: TeamContinuity
teamCompetitor = TeamContinuity 2
teamCivilian = TeamContinuity 3
teamConvict = TeamContinuity 4
teamMonster = TeamContinuity 5
teamAnimal = TeamContinuity 6
teamHorror = TeamContinuity 7
teamOther = TeamContinuity 10
-- * Content
content :: [FactionKind]
content = [factExplorer, factExplorerShort, factExplorerNoEscape, factExplorerMedium, factExplorerTrapped, factExplorerAutomated, factExplorerAutomatedTrapped, factExplorerCaptive, factExplorerPacifist, factCompetitor, factCompetitorShort, factCompetitorNoEscape, factCivilian, factConvict, factMonster, factMonsterAnti, factMonsterAntiCaptive, factMonsterAntiPacifist, factMonsterTourist, factMonsterTouristPassive, factMonsterCaptive, factMonsterCaptiveNarrating, factAnimal, factAnimalMagnificent, factAnimalExquisite, factAnimalCaptive, factAnimalNarrating, factAnimalMagnificentNarrating, factAnimalCaptiveNarrating, factHorror, factHorrorCaptive, factHorrorPacifist]
factExplorer, factExplorerShort, factExplorerNoEscape, factExplorerMedium, factExplorerTrapped, factExplorerAutomated, factExplorerAutomatedTrapped, factExplorerCaptive, factExplorerPacifist, factCompetitor, factCompetitorShort, factCompetitorNoEscape, factCivilian, factConvict, factMonster, factMonsterAnti, factMonsterAntiCaptive, factMonsterAntiPacifist, factMonsterTourist, factMonsterTouristPassive, factMonsterCaptive, factMonsterCaptiveNarrating, factAnimal, factAnimalMagnificent, factAnimalExquisite, factAnimalCaptive, factAnimalNarrating, factAnimalMagnificentNarrating, factAnimalCaptiveNarrating, factHorror, factHorrorCaptive, factHorrorPacifist :: FactionKind
-- * Content
-- ** teamExplorer
factExplorer = FactionKind
{ fname = "Explorer"
, ffreq = [(EXPLORER_REPRESENTATIVE, 1), (REPRESENTATIVE, 1)]
, fteam = teamExplorer
, fgroups = [(HERO, 100)] -- don't spam the escapists, etc., in description
, fskillsOther = meleeAdjacent
, fcanEscape = True
, fneverEmpty = True
, fhiCondPoly = hiHeroLong
, fhasGender = True
, finitDoctrine = TExplore
, fspawnsFast = False
, fhasPointman = True
, fhasUI = True
, finitUnderAI = False
, fenemyTeams = [teamCompetitor, teamMonster, teamAnimal, teamHorror]
, falliedTeams = []
}
factExplorerShort = factExplorer
{ ffreq = [(EXPLORER_SHORT, 1)]
, fhiCondPoly = hiHeroShort
, fenemyTeams = [teamMonster, teamAnimal, teamHorror]
}
factExplorerNoEscape = factExplorer
{ ffreq = [(EXPLORER_NO_ESCAPE, 1)]
, fcanEscape = False
, fhiCondPoly = hiHeroMedium
}
factExplorerMedium = factExplorer
{ ffreq = [(EXPLORER_MEDIUM, 1)]
, fhiCondPoly = hiHeroMedium
}
factExplorerTrapped = factExplorer
{ ffreq = [(EXPLORER_TRAPPED, 1)]
, fcanEscape = False
, fhiCondPoly = hiHeroLong
}
factExplorerAutomated = factExplorer
{ ffreq = [(EXPLORER_AUTOMATED, 1)]
, fhasUI = False
, finitUnderAI = True
}
factExplorerAutomatedTrapped = factExplorerAutomated
{ ffreq = [(EXPLORER_AUTOMATED_TRAPPED, 1)]
, fcanEscape = False
, fhiCondPoly = hiHeroLong
}
factExplorerCaptive = factExplorer
{ ffreq = [(EXPLORER_CAPTIVE, 1)]
, fneverEmpty = True -- already there
}
factExplorerPacifist = factExplorerCaptive
{ ffreq = [(EXPLORER_PACIFIST, 1)]
, fenemyTeams = []
, falliedTeams = []
}
-- ** teamCompetitor, symmetric opponents of teamExplorer
factCompetitor = factExplorer
{ fname = "Indigo Researcher"
, ffreq = [(COMPETITOR_REPRESENTATIVE, 1), (REPRESENTATIVE, 1)]
, fteam = teamCompetitor
, fhasUI = False
, finitUnderAI = True
, fenemyTeams = [teamExplorer, teamMonster, teamAnimal, teamHorror]
, falliedTeams = []
}
factCompetitorShort = factCompetitor
{ fname = "Indigo Founder" -- early
, ffreq = [(COMPETITOR_SHORT, 1)]
, fhiCondPoly = hiHeroShort
, fenemyTeams = [teamMonster, teamAnimal, teamHorror]
}
factCompetitorNoEscape = factCompetitor
{ ffreq = [(COMPETITOR_NO_ESCAPE, 1)]
, fcanEscape = False
, fhiCondPoly = hiHeroMedium
}
-- ** teamCivilian
factCivilian = FactionKind
{ fname = "Civilian"
, ffreq = [(CIVILIAN_REPRESENTATIVE, 1), (REPRESENTATIVE, 1)]
, fteam = teamCivilian
, fgroups = [(HERO, 100), (CIVILIAN, 100)] -- symmetric vs player
, fskillsOther = zeroSkills -- not coordinated by any leadership
, fcanEscape = False
, fneverEmpty = True
, fhiCondPoly = hiHeroMedium
, fhasGender = True
, finitDoctrine = TPatrol
, fspawnsFast = False
, fhasPointman = False -- unorganized
, fhasUI = False
, finitUnderAI = True
, fenemyTeams = [teamMonster, teamAnimal, teamHorror]
, falliedTeams = []
}
-- ** teamConvict, different demographics
factConvict = factCivilian
{ fname = "Hunam Convict"
, ffreq = [(CONVICT_REPRESENTATIVE, 1), (REPRESENTATIVE, 1)]
, fteam = teamConvict
, fhasPointman = True -- convicts organize better
, finitUnderAI = True
, fenemyTeams = [teamMonster, teamAnimal, teamHorror]
, falliedTeams = []
}
-- ** teamMonster
factMonster = FactionKind
{ fname = "Monster Hive"
, ffreq = [(MONSTER_REPRESENTATIVE, 1), (REPRESENTATIVE, 1)]
, fteam = teamMonster
, fgroups = [ (MONSTER, 100)
, (MOBILE_MONSTER, 1) ]
, fskillsOther = zeroSkills
, fcanEscape = False
, fneverEmpty = False
, fhiCondPoly = hiDweller
, fhasGender = False
, finitDoctrine = TExplore
, fspawnsFast = True
, fhasPointman = True
, fhasUI = False
, finitUnderAI = True
, fenemyTeams = [teamExplorer, teamCompetitor, teamCivilian, teamConvict]
, falliedTeams = [teamAnimal]
}
-- This has continuity @teamMonster@, despite being playable.
factMonsterAnti = factMonster
{ ffreq = [(MONSTER_ANTI, 1)]
, fhasUI = True
, finitUnderAI = False
}
factMonsterAntiCaptive = factMonsterAnti
{ ffreq = [(MONSTER_ANTI_CAPTIVE, 1)]
, fneverEmpty = True
}
factMonsterAntiPacifist = factMonsterAntiCaptive
{ ffreq = [(MONSTER_ANTI_PACIFIST, 1)]
, fenemyTeams = []
, falliedTeams = []
}
-- More flavour and special backstory, but the same team.
factMonsterTourist = factMonsterAnti
{ fname = "Monster Tourist Office"
, ffreq = [(MONSTER_TOURIST, 1)]
, fcanEscape = True
, fneverEmpty = True -- no spawning
, fhiCondPoly = hiHeroMedium
, finitDoctrine = TFollow -- follow-the-guide, as tourists do
, fspawnsFast = False -- on a trip, so no spawning
, finitUnderAI = False
, fenemyTeams =
[teamAnimal, teamExplorer, teamCompetitor, teamCivilian, teamConvict]
, falliedTeams = []
}
factMonsterTouristPassive = factMonsterTourist
{ ffreq = [(MONSTER_TOURIST_PASSIVE, 1)]
, fhasUI = False
, finitUnderAI = True
}
factMonsterCaptive = factMonster
{ ffreq = [(MONSTER_CAPTIVE, 1)]
, fneverEmpty = True
}
factMonsterCaptiveNarrating = factMonsterAntiCaptive
{ ffreq = [(MONSTER_CAPTIVE_NARRATING, 1)]
, fhasUI = True
}
-- ** teamAnimal
factAnimal = FactionKind
{ fname = "Animal Kingdom"
, ffreq = [(ANIMAL_REPRESENTATIVE, 1), (REPRESENTATIVE, 1)]
, fteam = teamAnimal
, fgroups = [ (ANIMAL, 100), (INSECT, 100), (GEOPHENOMENON, 100)
-- only the distinct enough ones
, (MOBILE_ANIMAL, 1), (IMMOBILE_ANIMAL, 1), (SCAVENGER, 1) ]
, fskillsOther = zeroSkills
, fcanEscape = False
, fneverEmpty = False
, fhiCondPoly = hiDweller
, fhasGender = False
, finitDoctrine = TRoam -- can't pick up, so no point exploring
, fspawnsFast = True
, fhasPointman = False
, fhasUI = False
, finitUnderAI = True
, fenemyTeams = [teamExplorer, teamCompetitor, teamCivilian, teamConvict]
, falliedTeams = [teamMonster]
}
-- These two differ from outside, but share information and boasting
-- about them tends to be general, too.
factAnimalMagnificent = factAnimal
{ fname = "Animal Magnificent Specimen Variety"
, ffreq = [(ANIMAL_MAGNIFICENT, 1)]
, fneverEmpty = True
, fenemyTeams =
[teamMonster, teamExplorer, teamCompetitor, teamCivilian, teamConvict]
, falliedTeams = []
}
factAnimalExquisite = factAnimal
{ fname = "Animal Exquisite Herds and Packs Galore"
, ffreq = [(ANIMAL_EXQUISITE, 1)]
, fteam = teamOther
-- in the same mode as @factAnimalMagnificent@, so borrow
-- identity from horrors to avoid a clash
, fneverEmpty = True
, fenemyTeams =
[teamMonster, teamExplorer, teamCompetitor, teamCivilian, teamConvict]
, falliedTeams = []
}
factAnimalCaptive = factAnimal
{ ffreq = [(ANIMAL_CAPTIVE, 1)]
, fneverEmpty = True
}
factAnimalNarrating = factAnimal
{ ffreq = [(ANIMAL_NARRATING, 1)]
, fhasUI = True
}
factAnimalMagnificentNarrating = factAnimalMagnificent
{ ffreq = [(ANIMAL_MAGNIFICENT_NARRATING, 1)]
, fhasPointman = True
, fhasUI = True
, finitUnderAI = False
}
factAnimalCaptiveNarrating = factAnimalCaptive
{ ffreq = [(ANIMAL_CAPTIVE_NARRATING, 1)]
, fhasUI = True
}
-- ** teamHorror, not much of a continuity intended, but can't be ignored
-- | A special faction, for summoned actors that don't belong to any
-- of the main factions of a given game. E.g., animals summoned during
-- a brawl game between two hero factions land in the horror faction.
-- In every game, either all factions for which summoning items exist
-- should be present or a horror faction should be added to host them.
factHorror = FactionKind
{ fname = "Horror Den"
, ffreq = [(HORROR_REPRESENTATIVE, 1), (REPRESENTATIVE, 1)]
, fteam = teamHorror
, fgroups = [(IK.HORROR, 100)]
, fskillsOther = zeroSkills
, fcanEscape = False
, fneverEmpty = False
, fhiCondPoly = []
, fhasGender = False
, finitDoctrine = TPatrol -- disoriented
, fspawnsFast = False
, fhasPointman = False
, fhasUI = False
, finitUnderAI = True
, fenemyTeams = [teamExplorer, teamCompetitor, teamCivilian, teamConvict]
, falliedTeams = []
}
factHorrorCaptive = factHorror
{ ffreq = [(HORROR_CAPTIVE, 1)]
, fneverEmpty = True
}
factHorrorPacifist = factHorrorCaptive
{ ffreq = [(HORROR_PACIFIST, 1)]
, fenemyTeams = []
, falliedTeams = []
}
|
LambdaHack/LambdaHack
|
GameDefinition/Content/FactionKind.hs
|
Haskell
|
bsd-3-clause
| 15,238
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
-- |
-- Module: $HEADER$
-- Description: Test cases for Data.DHT.Type.Result module.
-- Copyright: (c) 2015 Jan Šipr, Matej Kollár; 2015-2016 Peter Trško
-- License: BSD3
--
-- Stability: stable
-- Portability: GHC specific language extensions.
--
-- Test cases for "Data.DHT.Type.Result" module.
module TestCase.Data.DHT.Type.Result (tests)
where
import Control.Exception (Exception(fromException), SomeException)
import Control.Monad (Monad((>>=), return))
import Data.Bool (Bool(False, True))
import Data.Eq (Eq)
import Data.Function (($))
import Data.Maybe (Maybe(Just, Nothing))
import Data.Monoid ((<>))
import Data.Typeable (Typeable)
import System.IO (IO)
import Text.Show (Show(show))
import Test.HUnit (Assertion, assertBool, assertFailure)
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Data.DHT.Type.Result
( exception
, result
, wait'
)
tests :: [Test]
tests =
[ testGroup "wait'"
[ testCase "Handle received exception"
handleExceptionTest
, testCase "Receive result without handler being invoked"
handleResultTest
]
]
handleExceptionTest :: Assertion
handleExceptionTest =
exception DummyException >>= wait' handler >>= checkResult
where
handler :: SomeException -> IO Bool
handler ex = case fromException ex of
Just DummyException -> return True
Nothing -> do
assertFailure $ "Received unexpected exception: " <> show ex
return False
checkResult = assertBool
"Exception handler wasn't invoked, which it should have been."
handleResultTest :: Assertion
handleResultTest = result True >>= wait' handler >>= checkResult
where
handler :: SomeException -> IO Bool
handler _exception = return False
checkResult = assertBool
"Exception handler was invoked, which it wasn't supposed to."
data DummyException = DummyException
deriving (Eq, Show, Typeable)
instance Exception DummyException
|
FPBrno/dht-api
|
test/TestCase/Data/DHT/Type/Result.hs
|
Haskell
|
bsd-3-clause
| 2,153
|
{-# LANGUAGE CPP #-}
module Main where
import System.Posix.Internals (c_read, c_open, c_close, c_write, o_RDWR, o_CREAT, o_NONBLOCK)
import Foreign.C.String
import Foreign.Marshal.Alloc
import Control.Monad
import Control.Concurrent.Async (forConcurrently_)
import System.Environment
import Data.Bits
#if defined(mingw32_HOST_OS)
import Foreign.Ptr (castPtr)
#endif
main :: IO ()
main = do
[file] <- getArgs
forConcurrently_ [0..100] $ \ i -> do
let file' = file ++ "-" ++ show i
withCString file $ \ fp -> do
withCString file' $ \ fp' -> do
#if defined(mingw32_HOST_OS)
fd <- c_open (castPtr fp) (o_RDWR .|. o_NONBLOCK) 0o666
fd' <- c_open (castPtr fp') (o_CREAT .|. o_RDWR .|. o_NONBLOCK) 0o666
#else
fd <- c_open fp (o_RDWR .|. o_NONBLOCK) 0o666
fd' <- c_open fp' (o_CREAT .|. o_RDWR .|. o_NONBLOCK) 0o666
#endif
loop fd fd'
c_close fd
c_close fd'
where
loop fd fd' = do
ptr <- mallocBytes 32750
siz <- c_read fd ptr 32750
loopWrite fd' ptr (fromIntegral siz)
free ptr
case siz `compare` 0 of
LT -> error ("error:" ++ show siz)
EQ -> return ()
GT -> loop fd fd'
loopWrite fd ptr n = do
siz <- fromIntegral `fmap` c_write fd ptr n
case siz `compare` n of
LT -> loopWrite fd ptr (n - siz)
EQ -> return ()
GT -> error ("over write:" ++ show siz)
|
winterland1989/stdio
|
bench/diskIO/UnSafeFFI.hs
|
Haskell
|
bsd-3-clause
| 1,537
|
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE InstanceSigs #-}
-- NonZero4aryRandomAccessList
module PFDS.Sec9.Ex18 where
import Data.Vector (Vector, (!?), (//))
import qualified Data.Vector as V
import PFDS.Commons.RandomAccessList
import Prelude hiding (head, tail, lookup)
data Tree a = Leaf a | Node (Vector (Tree a))
-- ^^^^^^ 4 trees
type RList a = [Vector (Tree a)]
-- ^^^^^^ 1 ~ 4 trees
type instance Elem (RList a) = a
instance RandomAccessList (RList a) where
empty :: RList a
empty = []
isEmpty :: RList a -> Bool
isEmpty = null
cons :: a -> RList a -> RList a
cons x vs = consTree (Leaf x) vs
head :: RList a -> a -- raise Empty
head vs = let (Leaf x, _) = unconsTree vs in x
tail :: RList a -> RList a -- raise Empty
tail vs = let (_, vs') = unconsTree vs in vs'
lookup :: Int -> RList a -> a -- raise Subscript
lookup i vs = lookupList i 1 vs
update :: Int -> a -> RList a -> RList a -- raise Subscript
update i y vs = updateList i 1 y vs
-- helper
consTree :: Tree a -> RList a -> RList a
consTree t [] = [V.singleton t]
consTree t (v : vs) = if V.length v < 4
then V.cons t v : vs
else V.singleton t : consTree (Node v) vs
unconsTree :: RList a -> (Tree a, RList a)
unconsTree [] = error "Empty"
unconsTree [v] | V.length v == 1 = (V.head v, [])
unconsTree (v : vs) = if V.length v > 1
then (V.head v, V.tail v : vs)
else let (Node v', vs') = unconsTree vs in (V.head v, V.tail v : vs')
lookupList :: Int -> Int -> RList a -> a
lookupList i w [] = error "Subscript"
lookupList i w (v : vs) = if i <= w * V.length v
then lookupVector i w v
else lookupList (i - w * V.length v) (w * 4) vs
lookupVector :: Int -> Int -> Vector (Tree a) -> a
lookupVector i w v = let j = i `div` w in case v !? j of
Nothing -> error "Subscript"
Just (Leaf x) -> x
Just (Node v') -> lookupVector (i - j) (w `div` 4) v'
updateList :: Int -> Int -> a -> RList a -> RList a
updateList i w y [] = error "Subscript"
updateList i w y (v : vs) = if i <= w * V.length v
then updateVector i w y v : vs
else v : updateList (i - w * V.length v) (w * 4) y vs
updateVector :: Int -> Int -> a -> Vector (Tree a) -> Vector (Tree a)
updateVector i w y v = let j = i `div` w in case v !? j of
Nothing -> error "Subscript"
Just (Leaf _) -> v // [(j, Leaf y)]
Just (Node v') -> updateVector (i - j) (w `div` 4) y v'
|
matonix/pfds
|
src/PFDS/Sec9/Ex18.hs
|
Haskell
|
bsd-3-clause
| 2,474
|
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module :
-- Copyright : (c) 2012 Boyun Tang
-- License : BSD-style
-- Maintainer : tangboyun@hotmail.com
-- Stability : experimental
-- Portability : ghc
--
--
--
-----------------------------------------------------------------------------
module Bio.Sequence.GB.Types
where
import Data.ByteString (ByteString)
import Data.ByteString.Char8 (unpack,append)
import qualified Data.ByteString.Char8 as B8
import Data.Char (isDigit,toLower)
import Data.List (intercalate)
import Data.List.Split (splitEvery)
import Data.Maybe (fromMaybe)
import Text.Printf (printf)
getDEFINITION :: GBRecord -> ByteString
getDEFINITION = definitionToBS . definition
getACCESSION :: GBRecord -> ByteString
getACCESSION = accessionToBS . accession
getKEYWORDS :: GBRecord -> ByteString
getKEYWORDS = keywordsToBS . keywords
getSOURCE :: GBRecord -> ORGANISM
getSOURCE = sourceToOG . source
data GBRecord = GB {
locus :: LOCUS
,definition :: DEFINITION
,accession :: ACCESSION
,version :: VERSION
,dblink :: Maybe DBLINK
,keywords :: KEYWORDS
,segment :: Maybe SEGMENT
,source :: SOURCE
,references :: Maybe [REFERENCE] -- e.g. NM_053042 has no reference
,comment :: Maybe COMMENT
,features :: [FEATURE]
,origin :: ORIGIN
}
data GeneBankDivision = PRI -- ^ primate sequences
| ROD -- ^ rodent sequences
| MAM -- ^ other mammalian sequences
| VRT -- ^ other vertebrate sequences
| INV -- ^ invertebrate sequences
| PLN -- ^ plant, fungal, and algal sequences
| BCT -- ^ bacterial sequences
| VRL -- ^ viral sequences
| PHG -- ^ bacteriophage sequences
| SYN -- ^ synthetic sequences
| UNA -- ^ unannotated sequences
| EST -- ^ EST sequences (expressed sequence tags)
| PAT -- ^ patent sequences
| STS -- ^ STS sequences (sequence tagged sites)
| GSS -- ^ GSS sequences (genome survey sequences)
| HTG -- ^ HTG sequences (high-throughput genomic sequences)
| HTC -- ^ unfinished high-throughput cDNA sequencing
| ENV -- ^ environmental sampling sequences
deriving (Show,Read)
data MoleculeType = MoleculeType {
molType :: !ByteString
,topo :: !(Maybe Topology)
}
data Topology = Linear
| Circular
deriving (Show,Read)
-- data Polymer = DNA
-- | RNA
-- | PRO
-- deriving (Show,Eq,Read)
data LOCUS = LOCUS {
locusName :: !ByteString
,sequenceLength :: {-# UNPACK #-} !Int
,moleculeType :: !MoleculeType
,geneBankDivision :: !GeneBankDivision
,modificationDate :: !ByteString
}
data VERSION = VERSION ByteString !GI
type Genus = ByteString
type Species = ByteString
data ORGANISM = ORGANISM !Genus !Species
data DBLINK = Project !ByteString
| BioProject !ByteString
data REFERENCE = REFERENCE {
author :: !(Maybe ByteString)
,consortium :: !(Maybe ByteString)
,title :: !(Maybe ByteString)
,journal :: !ByteString
,pubmed :: !(Maybe ByteString)
,remark :: !(Maybe ByteString)
}
data FEATURE = FEATURE {
feature :: !ByteString
,locationDescriptor :: !ByteString
,values :: ![(ByteString,ByteString)]
}
newtype SEGMENT = SEGMENT {
segmentToBS :: ByteString
}
newtype CONTIG = CONTIG {
contigToBS :: ByteString
}
newtype ORIGIN = ORIGIN {
originToBS :: ByteString
}
newtype DEFINITION = DEFINITION {
definitionToBS :: ByteString
}
newtype ACCESSION = ACCESSION {
accessionToBS :: ByteString
}
newtype GI = GI {
giToBS :: ByteString
}
newtype KEYWORDS = KEYWORDS {
keywordsToBS :: ByteString
}
newtype SOURCE = SOURCE {
sourceToOG :: ORGANISM
}
newtype COMMENT = COMMENT {
commentToBS :: ByteString
}
instance Show LOCUS where
show (LOCUS name len mole gbd date) =
"LOCUS" ++ "\t" ++
unpack name ++ "\t" ++
show len ++
" " ++ locusStr ++ "\t" ++
show gbd ++
"\t" ++ unpack date
where
locusStr = case mole of
MoleculeType poly (Just str) ->
let unit =
if "NP_" `B8.isPrefixOf` name
then "aa"
else "bp"
in unit ++ "\t" ++ unpack poly ++ "\t" ++ (map toLower $ show str)
MoleculeType poly _ ->
let unit =
if "NP_" `B8.isPrefixOf` name
then "aa"
else "bp"
in unit ++ "\t" ++ unpack poly
instance Show DEFINITION where
show (DEFINITION str) = "DEFINITION\t" ++ unpack str
instance Show ACCESSION where
show (ACCESSION str) = "ACCESSION\t" ++ unpack str
instance Show VERSION where
show (VERSION str1 (GI str2)) = "VERSION\t" ++ unpack str1 ++
"\t" ++ unpack str2
instance Show DBLINK where
show dbl =
case dbl of
Project str -> "DBLINK\t" ++ "Project: " ++ unpack str
BioProject str -> "DBLINK\t" ++ "BioProject: " ++ unpack str
instance Show KEYWORDS where
show (KEYWORDS str) = "KEYWORDS\t" ++ unpack str
instance Show SEGMENT where
show (SEGMENT str) = "SEGMENT\t" ++ unpack str
instance Show SOURCE where
show (SOURCE (ORGANISM str1 str2)) = "SOURCE\n " ++ "ORGANISM\t" ++
unpack str1 ++ " " ++ unpack str2
instance Show REFERENCE where
show art =
unpack $
B8.intercalate "\n" $
filter (not . B8.null) $
map (fromMaybe "") $
zipWith ($)
[fmap (s2 `append` "AUTHORS\t" `append`) . author
,fmap (s2 `append` "CONSRTM\t" `append`) . consortium
,fmap (s2 `append` "TITLE\t" `append`) . title
,fmap (s2 `append` "JOURNAL\t" `append`) . Just . journal
,fmap (s3 `append` "PUBMED\t" `append`) . pubmed
,fmap (s2 `append` "REMARK\t" `append`) . remark] $
repeat art
where
s2 = " "
s3 = " "
instance Show COMMENT where
show (COMMENT str) = "COMMENT\t" ++ unpack str
instance Show FEATURE where
show (FEATURE na loc ps) =
myShow na loc ps
where
myShow str l vs = s5 ++ unpack str ++ "\t" ++ unpack l ++ "\n" ++ showPS vs
s5 = replicate 5 ' '
showPS ss =
B8.unpack $ B8.intercalate "\n" $
map (\(k,v) ->
let v' = if (all isDigit $ unpack v) || (k == "number") || (k == "citation")
then v
else '"' `B8.cons` v `B8.snoc` '"'
s21 = B8.pack (replicate 21 ' ') `B8.snoc` '/'
in if k /= "translation"
then s21 `B8.append` k `B8.snoc` '=' `B8.append` v'
else let (vh,vt) = B8.splitAt 45 v'
s' = '\n' `B8.cons` B8.pack (replicate 21 ' ')
vS = B8.intercalate s' $
vh:map B8.pack (splitEvery 58 $ B8.unpack vt)
in s21 `B8.append` k `B8.snoc` '=' `B8.append` vS
) ss
instance Show ORIGIN where
show (ORIGIN str) = "ORIGIN" ++ "\n" ++
intercalate "\n"
(map (\(i,s) ->
printf "%10d" (i * 60 + 1) ++ " " ++ s) $
zip ([0..]::[Int]) $ map unwords $
splitEvery 6 $ splitEvery 10 (unpack str)) ++ "\n//"
instance Show GBRecord where
show gb =
intercalate "\n" $
filter (not . null) $
map (fromMaybe "") $
zipWith ($)
[fmap show . Just . locus
,fmap show . Just . definition
,fmap show . Just . accession
,fmap show . Just . version
,fmap show . dblink
,fmap show . Just . keywords
,fmap show . segment
,fmap show . Just . source
,fmap
(intercalate "\n" . map
(\(i,r) ->
"REFERENCE\t" ++ show i ++ "\n" ++ show r
) . zip ([1..]::[Int])) . references
,fmap show . comment
,fmap (("FEATURES\tLocation/Qualifiers\n" ++) .
intercalate "\n" . map show) . Just . features
,fmap show . Just . origin] $
repeat gb
|
tangboyun/bio-seq-gb
|
Bio/Sequence/GB/Types.hs
|
Haskell
|
bsd-3-clause
| 8,871
|
{-# LANGUAGE PatternGuards, TypeSynonymInstances, CPP #-}
module IRTS.Compiler where
import IRTS.Lang
import IRTS.Defunctionalise
import IRTS.Simplified
import IRTS.CodegenCommon
import IRTS.CodegenC
import IRTS.CodegenJava
import IRTS.DumpBC
import IRTS.CodegenJavaScript
#ifdef IDRIS_LLVM
import IRTS.CodegenLLVM
#else
import Util.LLVMStubs
#endif
import IRTS.Inliner
import Idris.AbsSyntax
import Idris.UnusedArgs
import Idris.Error
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Core.CaseTree
import Control.Monad.State
import Data.List
import System.Process
import System.IO
import System.Directory
import System.Environment
import System.FilePath ((</>), addTrailingPathSeparator)
import Paths_idris
compile :: Codegen -> FilePath -> Term -> Idris ()
compile codegen f tm
= do checkMVs
let tmnames = namesUsed (STerm tm)
usedIn <- mapM (allNames []) tmnames
let used = [sUN "prim__subBigInt", sUN "prim__addBigInt"] : usedIn
defsIn <- mkDecls tm (concat used)
findUnusedArgs (concat used)
maindef <- irMain tm
objs <- getObjectFiles codegen
libs <- getLibs codegen
flags <- getFlags codegen
hdrs <- getHdrs codegen
impdirs <- allImportDirs
let defs = defsIn ++ [(sMN 0 "runMain", maindef)]
-- iputStrLn $ showSep "\n" (map show defs)
let (nexttag, tagged) = addTags 65536 (liftAll defs)
let ctxtIn = addAlist tagged emptyContext
iLOG "Defunctionalising"
let defuns_in = defunctionalise nexttag ctxtIn
logLvl 5 $ show defuns_in
iLOG "Inlining"
let defuns = inline defuns_in
logLvl 5 $ show defuns
iLOG "Resolving variables for CG"
-- iputStrLn $ showSep "\n" (map show (toAlist defuns))
let checked = checkDefs defuns (toAlist defuns)
outty <- outputTy
dumpCases <- getDumpCases
dumpDefun <- getDumpDefun
case dumpCases of
Nothing -> return ()
Just f -> runIO $ writeFile f (showCaseTrees defs)
case dumpDefun of
Nothing -> return ()
Just f -> runIO $ writeFile f (dumpDefuns defuns)
triple <- targetTriple
cpu <- targetCPU
optimize <- optLevel
iLOG "Building output"
case checked of
OK c -> runIO $ case codegen of
ViaC ->
codegenC c f outty hdrs
(concatMap mkObj objs)
(concatMap mkLib libs)
(concatMap mkFlag flags ++
concatMap incdir impdirs) NONE
ViaJava ->
codegenJava [] c f hdrs libs outty
ViaJavaScript ->
codegenJavaScript JavaScript c f outty
ViaNode ->
codegenJavaScript Node c f outty
ViaLLVM -> codegenLLVM c triple cpu optimize f outty
Bytecode -> dumpBC c f
Error e -> ierror e
where checkMVs = do i <- getIState
case map fst (idris_metavars i) \\ primDefs of
[] -> return ()
ms -> ifail $ "There are undefined metavariables: " ++ show ms
inDir d h = do let f = d </> h
ex <- doesFileExist f
if ex then return f else return h
mkObj f = f ++ " "
mkLib l = "-l" ++ l ++ " "
mkFlag l = l ++ " "
incdir i = "-I" ++ i ++ " "
irMain :: TT Name -> Idris LDecl
irMain tm = do i <- ir tm
return $ LFun [] (sMN 0 "runMain") [] (LForce i)
mkDecls :: Term -> [Name] -> Idris [(Name, LDecl)]
mkDecls t used
= do i <- getIState
let ds = filter (\ (n, d) -> n `elem` used || isCon d) $ ctxtAlist (tt_ctxt i)
mapM traceUnused used
decls <- mapM build ds
return decls
showCaseTrees :: [(Name, LDecl)] -> String
showCaseTrees ds = showSep "\n\n" (map showCT ds)
where
showCT (n, LFun _ f args lexp)
= show n ++ " " ++ showSep " " (map show args) ++ " =\n\t "
++ show lexp
showCT (n, LConstructor c t a) = "data " ++ show n ++ " " ++ show a
isCon (TyDecl _ _) = True
isCon _ = False
class ToIR a where
ir :: a -> Idris LExp
build :: (Name, Def) -> Idris (Name, LDecl)
build (n, d)
= do i <- getIState
case lookup n (idris_scprims i) of
Just (ar, op) ->
let args = map (\x -> sMN x "op") [0..] in
return (n, (LFun [] n (take ar args)
(LOp op (map (LV . Glob) (take ar args)))))
_ -> do def <- mkLDecl n d
logLvl 3 $ "Compiled " ++ show n ++ " =\n\t" ++ show def
return (n, def)
getPrim :: IState -> Name -> [LExp] -> Maybe LExp
getPrim i n args = case lookup n (idris_scprims i) of
Just (ar, op) ->
if (ar == length args)
then return (LOp op args)
else Nothing
_ -> Nothing
declArgs args inl n (LLam xs x) = declArgs (args ++ xs) inl n x
declArgs args inl n x = LFun (if inl then [Inline] else []) n args x
mkLDecl n (Function tm _) = do e <- ir tm
return (declArgs [] True n e)
mkLDecl n (CaseOp ci _ _ _ pats cd)
= let (args, sc) = cases_runtime cd in
do e <- ir (args, sc)
return (declArgs [] (case_inlinable ci) n e)
mkLDecl n (TyDecl (DCon t a) _) = return $ LConstructor n t a
mkLDecl n (TyDecl (TCon t a) _) = return $ LConstructor n (-1) a
mkLDecl n _ = return (LFun [] n [] (LError ("Impossible declaration " ++ show n)))
instance ToIR (TT Name) where
ir tm = ir' [] tm where
ir' env tm@(App f a)
| (P _ (UN m) _, args) <- unApply tm,
m == txt "mkForeignPrim"
= doForeign env args
| (P _ (UN u) _, [_, arg]) <- unApply tm,
u == txt "unsafePerformPrimIO"
= ir' env arg
-- TMP HACK - until we get inlining.
| (P _ (UN r) _, [_, _, _, _, _, arg]) <- unApply tm,
r == txt "replace"
= ir' env arg
| (P _ (UN l) _, [_, arg]) <- unApply tm,
l == txt "lazy"
= do arg' <- ir' env arg
return $ LLazyExp arg'
| (P _ (UN a) _, [_, _, _, arg]) <- unApply tm,
a == txt "assert_smaller"
= ir' env arg
| (P _ (UN p) _, [_, arg]) <- unApply tm,
p == txt "par"
= do arg' <- ir' env arg
return $ LOp LPar [LLazyExp arg']
| (P _ (UN pf) _, [arg]) <- unApply tm,
pf == txt "prim_fork"
= do arg' <- ir' env arg
return $ LOp LFork [LLazyExp arg']
| (P _ (UN m) _, [_,size,t]) <- unApply tm,
m == txt "malloc"
= do size' <- ir' env size
t' <- ir' env t
return t' -- TODO $ malloc_ size' t'
| (P _ (UN tm) _, [_,t]) <- unApply tm,
tm == txt "trace_malloc"
= do t' <- ir' env t
return t' -- TODO
-- | (P _ (NS (UN "S") ["Nat", "Prelude"]) _, [k]) <- unApply tm
-- = do k' <- ir' env k
-- return (LOp LBPlus [k', LConst (BI 1)])
| (P (DCon t a) n _, args) <- unApply tm
= irCon env t a n args
| (P (TCon t a) n _, args) <- unApply tm
= return LNothing
| (P _ n _, args) <- unApply tm
= do i <- getIState
args' <- mapM (ir' env) args
case getPrim i n args' of
Just tm -> return tm
_ -> do
let collapse
= case lookupCtxtExact n
(idris_optimisation i) of
Just oi -> collapsible oi
_ -> False
let unused
= case lookupCtxtExact n
(idris_callgraph i) of
Just (CGInfo _ _ _ _ unusedpos) ->
unusedpos
_ -> []
if collapse
then return LNothing
else return (LApp False (LV (Glob n))
(mkUnused unused 0 args'))
| (f, args) <- unApply tm
= do f' <- ir' env f
args' <- mapM (ir' env) args
return (LApp False f' args')
where mkUnused u i [] = []
mkUnused u i (x : xs) | i `elem` u = LNothing : mkUnused u (i + 1) xs
| otherwise = x : mkUnused u (i + 1) xs
-- ir' env (P _ (NS (UN "Z") ["Nat", "Prelude"]) _)
-- = return $ LConst (BI 0)
ir' env (P _ n _) = return $ LV (Glob n)
ir' env (V i) | i >= 0 && i < length env = return $ LV (Glob (env!!i))
| otherwise = ifail $ "IR fail " ++ show i ++ " " ++ show tm
ir' env (Bind n (Lam _) sc)
= do let n' = uniqueName n env
sc' <- ir' (n' : env) sc
return $ LLam [n'] sc'
ir' env (Bind n (Let _ v) sc)
= do sc' <- ir' (n : env) sc
v' <- ir' env v
return $ LLet n v' sc'
ir' env (Bind _ _ _) = return $ LNothing
ir' env (Proj t i) | i == -1
= do t' <- ir' env t
return $ LOp (LMinus (ATInt ITBig))
[t', LConst (BI 1)]
ir' env (Proj t i) = do t' <- ir' env t
return $ LProj t' i
ir' env (Constant c) = return $ LConst c
ir' env (TType _) = return $ LNothing
ir' env Erased = return $ LNothing
ir' env Impossible = return $ LNothing
-- ir' env _ = return $ LError "Impossible"
irCon env t arity n args
| length args == arity = buildApp env (LV (Glob n)) args
| otherwise = let extra = satArgs (arity - length args) in
do sc' <- irCon env t arity n
(args ++ map (\n -> P Bound n undefined) extra)
return $ LLam extra sc'
satArgs n = map (\i -> sMN i "sat") [1..n]
buildApp env e [] = return e
buildApp env e xs = do xs' <- mapM (ir' env) xs
return $ LApp False e xs'
doForeign :: [Name] -> [TT Name] -> Idris LExp
doForeign env (_ : fgn : args)
| (_, (Constant (Str fgnName) : fgnArgTys : ret : [])) <- unApply fgn
= let maybeTys = getFTypes fgnArgTys
rty = mkIty' ret in
case maybeTys of
Nothing -> ifail $ "Foreign type specification is not a constant list: " ++ show (fgn:args)
Just tys -> do
args' <- mapM (ir' env) (init args)
-- wrap it in a prim__IO
-- return $ con_ 0 @@ impossible @@
return $ -- LLazyExp $
LForeign LANG_C rty fgnName (zip tys args')
| otherwise = ifail "Badly formed foreign function call"
getFTypes :: TT Name -> Maybe [FType]
getFTypes tm = case unApply tm of
(nil, []) -> Just []
(cons, [ty, xs]) ->
fmap (mkIty' ty :) (getFTypes xs)
_ -> Nothing
mkIty' (P _ (UN ty) _) = mkIty (str ty)
mkIty' (App (P _ (UN fi) _) (P _ (UN intTy) _))
| fi == txt "FIntT" = mkIntIty (str intTy)
mkIty' (App (App (P _ (UN ff) _) _) (App (P _ (UN fa) _) (App (P _ (UN io) _) _)))
| ff == txt "FFunction" && fa == txt "FAny" &&
io == txt "IO"
= FFunctionIO
mkIty' (App (App (P _ (UN ff) _) _) _)
| ff == txt "FFunction" = FFunction
mkIty' _ = FAny
-- would be better if these FInt types were evaluated at compile time
-- TODO: add %eval directive for such things
mkIty "FFloat" = FArith ATFloat
mkIty "FInt" = mkIntIty "ITNative"
mkIty "FChar" = mkIntIty "ITChar"
mkIty "FByte" = mkIntIty "IT8"
mkIty "FShort" = mkIntIty "IT16"
mkIty "FLong" = mkIntIty "IT64"
mkIty "FBits8" = mkIntIty "IT8"
mkIty "FBits16" = mkIntIty "IT16"
mkIty "FBits32" = mkIntIty "IT32"
mkIty "FBits64" = mkIntIty "IT64"
mkIty "FString" = FString
mkIty "FPtr" = FPtr
mkIty "FUnit" = FUnit
mkIty "FFunction" = FFunction
mkIty "FFunctionIO" = FFunctionIO
mkIty "FBits8x16" = FArith (ATInt (ITVec IT8 16))
mkIty "FBits16x8" = FArith (ATInt (ITVec IT16 8))
mkIty "FBits32x4" = FArith (ATInt (ITVec IT32 4))
mkIty "FBits64x2" = FArith (ATInt (ITVec IT64 2))
mkIty x = error $ "Unknown type " ++ x
mkIntIty "ITNative" = FArith (ATInt ITNative)
mkIntIty "ITChar" = FArith (ATInt ITChar)
mkIntIty "IT8" = FArith (ATInt (ITFixed IT8))
mkIntIty "IT16" = FArith (ATInt (ITFixed IT16))
mkIntIty "IT32" = FArith (ATInt (ITFixed IT32))
mkIntIty "IT64" = FArith (ATInt (ITFixed IT64))
zname = sNS (sUN "Z") ["Nat","Prelude"]
sname = sNS (sUN "S") ["Nat","Prelude"]
instance ToIR ([Name], SC) where
ir (args, tree) = do logLvl 3 $ "Compiling " ++ show args ++ "\n" ++ show tree
tree' <- ir tree
return $ LLam args tree'
instance ToIR SC where
ir t = ir' t where
ir' (STerm t) = ir t
ir' (UnmatchedCase str) = return $ LError str
ir' (ProjCase tm alts) = do tm' <- ir tm
alts' <- mapM (mkIRAlt tm') alts
return $ LCase tm' alts'
ir' (Case n alts) = do alts' <- mapM (mkIRAlt (LV (Glob n))) alts
return $ LCase (LV (Glob n)) alts'
ir' ImpossibleCase = return LNothing
-- special cases for Z and S
-- Needs rethink: projections make this fail
-- mkIRAlt n (ConCase z _ [] rhs) | z == zname
-- = mkIRAlt n (ConstCase (BI 0) rhs)
-- mkIRAlt n (ConCase s _ [arg] rhs) | s == sname
-- = do n' <- ir n
-- rhs' <- ir rhs
-- return $ LDefaultCase
-- (LLet arg (LOp LBMinus [n', LConst (BI 1)])
-- rhs')
mkIRAlt _ (ConCase n t args rhs)
= do rhs' <- ir rhs
return $ LConCase (-1) n args rhs'
mkIRAlt _ (ConstCase x rhs)
| matchable x
= do rhs' <- ir rhs
return $ LConstCase x rhs'
| matchableTy x
= do rhs' <- ir rhs
return $ LDefaultCase rhs'
mkIRAlt tm (SucCase n rhs)
= do rhs' <- ir rhs
return $ LDefaultCase (LLet n (LOp (LMinus (ATInt ITBig))
[tm,
LConst (BI 1)]) rhs')
-- return $ LSucCase n rhs'
mkIRAlt _ (ConstCase c rhs)
= ifail $ "Can't match on (" ++ show c ++ ")"
mkIRAlt _ (DefaultCase rhs)
= do rhs' <- ir rhs
return $ LDefaultCase rhs'
matchable (I _) = True
matchable (BI _) = True
matchable (Ch _) = True
matchable (Str _) = True
matchable _ = False
matchableTy (AType (ATInt ITNative)) = True
matchableTy (AType (ATInt ITBig)) = True
matchableTy (AType (ATInt ITChar)) = True
matchableTy StrType = True
matchableTy (AType (ATInt (ITFixed IT8))) = True
matchableTy (AType (ATInt (ITFixed IT16))) = True
matchableTy (AType (ATInt (ITFixed IT32))) = True
matchableTy (AType (ATInt (ITFixed IT64))) = True
matchableTy _ = False
|
ctford/Idris-Elba-dev
|
src/IRTS/Compiler.hs
|
Haskell
|
bsd-3-clause
| 16,544
|
{-# LANGUAGE OverloadedStrings #-}
import EditRope
import Criterion.Main
import TestHelper
main :: IO ()
main = do
let toTest = renderTokensForLine attrMap
defaultMain [
bgroup "renderTokensForLine" [
bench "original line" $ whnf (toTest []) lineABC
, bench "lineABC" $ whnf (toTest tokensLineABC) lineABC
, bench "lineABC_123" $ whnf (toTest tokensLineABC_123) lineABC_123
, bench "lineABC_123_rev" $ whnf (toTest tokensLineABC_123_rev) lineABC_123
]
]
|
clojj/hsedit
|
test/Criterion.hs
|
Haskell
|
bsd-3-clause
| 568
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Numeric.Natural.QuickCheck where
import Numeric.Natural
import Test.QuickCheck (Arbitrary, arbitrary, CoArbitrary, coarbitrary, suchThat, variant)
import Control.Applicative ((<$>))
instance Arbitrary Natural where
arbitrary = fromInteger <$> (arbitrary `suchThat` (0 <=))
instance CoArbitrary Natural where
coarbitrary = variant
|
kmyk/proof-haskell
|
Numeric/Natural/QuickCheck.hs
|
Haskell
|
mit
| 386
|
module API.RequestSpec (spec) where
import Universum
import Data.Either (isLeft)
import Formatting (build, sformat)
import Test.Hspec
import Cardano.Wallet.API.Request.Filter
import Cardano.Wallet.API.Request.Sort
import Cardano.Wallet.API.V1.Types
import qualified Pos.Core as Core
spec :: Spec
spec = describe "Request" $ do
describe "Sort" sortSpec
describe "Filter" filterSpec
sortSpec :: Spec
sortSpec =
describe "parseSortOperation" $ do
describe "Transaction" $ do
let ptimestamp = Proxy @(V1 Core.Timestamp)
pt = Proxy @Transaction
it "knows the query param" $ do
parseSortOperation pt ptimestamp "ASC[created_at]"
`shouldBe`
Right (SortByIndex SortAscending ptimestamp)
it "infers DESC for nonspecified sort" $
parseSortOperation pt ptimestamp "created_at"
`shouldBe`
Right (SortByIndex SortDescending ptimestamp)
it "fails if the param name is wrong" $ do
parseSortOperation pt ptimestamp "ASC[balance]"
`shouldSatisfy`
isLeft
it "fails if the syntax is wrong" $ do
parseSortOperation pt ptimestamp "ASC[created_at"
`shouldSatisfy`
isLeft
filterSpec :: Spec
filterSpec = do
describe "parseFilterOperation" $ do
describe "Wallet" $ do
let pw = Proxy @Wallet
pwid = Proxy @WalletId
pcoin = Proxy @Core.Coin
it "supports index" $ do
parseFilterOperation pw pwid "asdf"
`shouldBe`
Right (FilterByIndex (WalletId "asdf"))
forM_ [minBound .. maxBound] $ \p ->
it ("supports predicate: " <> show p) $ do
parseFilterOperation pw pwid
(sformat build p <> "[asdf]")
`shouldBe`
Right (FilterByPredicate p (WalletId "asdf"))
it "supports range" $ do
parseFilterOperation pw pcoin "RANGE[123,456]"
`shouldBe`
Right
(FilterByRange (Core.mkCoin 123)
(Core.mkCoin 456))
it "fails if the thing can't be parsed" $ do
parseFilterOperation pw pcoin "nope"
`shouldSatisfy`
isLeft
it "supports IN" $ do
parseFilterOperation pw pcoin "IN[1,2,3]"
`shouldBe`
Right
(FilterIn (map Core.mkCoin [1,2,3]))
describe "toQueryString" $ do
let ops = FilterByRange (Core.mkCoin 2345) (Core.mkCoin 2348)
`FilterOp` FilterByIndex (WalletId "hello")
`FilterOp` NoFilters
:: FilterOperations '[Core.Coin, WalletId] Wallet
it "does what you'd want it to do" $ do
toQueryString ops
`shouldBe`
[ ("balance", Just "RANGE[2345,2348]")
, ("id", Just "hello")
]
describe "toFilterOperations" $ do
let params :: [(Text, Maybe Text)]
params =
[ ("id", Just "3")
, ("balance", Just "RANGE[10,50]")
]
fops :: FilterOperations '[WalletId, Core.Coin] Wallet
fops = FilterByIndex (WalletId "3")
`FilterOp` FilterByRange (Core.mkCoin 10) (Core.mkCoin 50)
`FilterOp` NoFilters
prxy :: Proxy '[WalletId, Core.Coin]
prxy = Proxy
it "can parse the thing" $ do
toFilterOperations params prxy
`shouldBe`
fops
|
input-output-hk/pos-haskell-prototype
|
wallet/test/unit/API/RequestSpec.hs
|
Haskell
|
mit
| 4,025
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{- |
Module : Neovim.RPC.SocketReader
Description : The component which reads RPC messages from the neovim instance
Copyright : (c) Sebastian Witte
License : Apache-2.0
Maintainer : woozletoff@gmail.com
Stability : experimental
-}
module Neovim.RPC.SocketReader (
runSocketReader,
parseParams,
) where
import Neovim.Classes
import Neovim.Context
import qualified Neovim.Context.Internal as Internal
import Neovim.Plugin.Classes (CommandArguments (..),
CommandOption (..),
FunctionName (..),
FunctionalityDescription (..),
getCommandOptions)
import Neovim.Plugin.IPC.Classes
import Neovim.Plugin (registerInStatelessContext)
import qualified Neovim.RPC.Classes as MsgpackRPC
import Neovim.RPC.Common
import Neovim.RPC.FunctionCall
import Control.Applicative
import Control.Concurrent (forkIO)
import Control.Concurrent.STM
import Control.Monad (void)
import Control.Monad.Trans.Class (lift)
import Data.Conduit as C
import Data.Conduit.Binary
import Data.Conduit.Cereal
import Data.Default (def)
import Data.Foldable (foldl', forM_)
import qualified Data.Map as Map
import Data.MessagePack
import Data.Monoid
import qualified Data.Serialize (get)
import System.IO (Handle)
import System.Log.Logger
import Prelude
logger :: String
logger = "Socket Reader"
type SocketHandler = Neovim RPCConfig ()
-- | This function will establish a connection to the given socket and read
-- msgpack-rpc events from it.
runSocketReader :: Handle
-> Internal.Config RPCConfig st
-> IO ()
runSocketReader readableHandle cfg =
void . runNeovim (Internal.retypeConfig (Internal.customConfig cfg) () cfg) () $ do
-- addCleanup (cleanUpHandle h) (sourceHandle h)
-- TODO test whether/how this should be handled
-- this has been commented out because I think that restarting the
-- plugin provider should not cause the stdin and stdout handles to be
-- closed since that would cause neovim to stop the plugin provider (I
-- think).
sourceHandle readableHandle
$= conduitGet Data.Serialize.get
$$ messageHandlerSink
-- | Sink that delegates the messages depending on their type.
-- <https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md>
messageHandlerSink :: Sink Object SocketHandler ()
messageHandlerSink = awaitForever $ \rpc -> do
liftIO . debugM logger $ "Received: " <> show rpc
case fromObject rpc of
Right (MsgpackRPC.Request (Request fn i ps)) ->
handleRequestOrNotification (Just i) fn ps
Right (MsgpackRPC.Response i r) ->
handleResponse i r
Right (MsgpackRPC.Notification (Notification fn ps)) ->
handleRequestOrNotification Nothing fn ps
Left e -> liftIO . errorM logger $
"Unhandled rpc message: " <> show e
handleResponse :: Int64 -> Either Object Object -> Sink a SocketHandler ()
handleResponse i result = do
answerMap <- asks recipients
mReply <- Map.lookup i <$> liftIO (readTVarIO answerMap)
case mReply of
Nothing -> liftIO $ warningM logger
"Received response but could not find a matching recipient."
Just (_,reply) -> do
atomically' . modifyTVar' answerMap $ Map.delete i
atomically' $ putTMVar reply result
-- | Act upon the received request or notification. The main difference between
-- the two is that a notification does not generate a reply. The distinction
-- between those two cases is done via the first paramater which is 'Maybe' the
-- function call identifier.
handleRequestOrNotification :: Maybe Int64 -> FunctionName -> [Object] -> Sink a SocketHandler ()
handleRequestOrNotification mi m params = do
cfg <- lift Internal.ask'
void . liftIO . forkIO $ handle cfg
where
lookupFunction
:: TMVar Internal.FunctionMap
-> STM (Maybe (FunctionalityDescription, Internal.FunctionType))
lookupFunction funMap = Map.lookup m <$> readTMVar funMap
handle :: Internal.Config RPCConfig () -> IO ()
handle rpc = atomically (lookupFunction (Internal.globalFunctionMap rpc)) >>= \case
Nothing -> do
let errM = "No provider for: " <> show m
debugM logger errM
forM_ mi $ \i -> atomically' . writeTQueue (Internal.eventQueue rpc)
. SomeMessage $ MsgpackRPC.Response i (Left (toObject errM))
Just (copts, Internal.Stateless f) -> do
liftIO . debugM logger $ "Executing stateless function with ID: " <> show mi
-- Stateless function: Create a boring state object for the
-- Neovim context.
-- drop the state of the result with (fmap fst <$>)
let rpc' = rpc
{ Internal.customConfig = ()
, Internal.pluginSettings = Just . Internal.StatelessSettings $
registerInStatelessContext (\_ -> return ())
}
res <- fmap fst <$> runNeovim rpc' () (f $ parseParams copts params)
-- Send the result to the event handler
forM_ mi $ \i -> atomically' . writeTQueue (Internal.eventQueue rpc)
. SomeMessage . MsgpackRPC.Response i $ either (Left . toObject) Right res
Just (copts, Internal.Stateful c) -> do
now <- liftIO getCurrentTime
reply <- liftIO newEmptyTMVarIO
let q = (recipients . Internal.customConfig) rpc
liftIO . debugM logger $ "Executing stateful function with ID: " <> show mi
case mi of
Just i -> do
atomically' . modifyTVar q $ Map.insert i (now, reply)
atomically' . writeTQueue c . SomeMessage $
Request m i (parseParams copts params)
Nothing ->
atomically' . writeTQueue c . SomeMessage $
Notification m (parseParams copts params)
parseParams :: FunctionalityDescription -> [Object] -> [Object]
parseParams (Function _ _) args = case args of
-- Defining a function on the remote host creates a function that, that
-- passes all arguments in a list. At the time of this writing, no other
-- arguments are passed for such a function.
--
-- The function generating the function on neovim side is called:
-- @remote#define#FunctionOnHost@
[ObjectArray fArgs] -> fArgs
_ -> args
parseParams cmd@(Command _ opts) args = case args of
(ObjectArray _ : _) ->
let cmdArgs = filter isPassedViaRPC (getCommandOptions opts)
(c,args') =
foldl' createCommandArguments (def, []) $
zip cmdArgs args
in toObject c : args'
_ -> parseParams cmd $ [ObjectArray args]
where
isPassedViaRPC :: CommandOption -> Bool
isPassedViaRPC = \case
CmdSync{} -> False
_ -> True
-- Neovim passes arguments in a special form, depending on the
-- CommandOption values used to export the (command) function (e.g. via
-- 'command' or 'command'').
createCommandArguments :: (CommandArguments, [Object])
-> (CommandOption, Object)
-> (CommandArguments, [Object])
createCommandArguments old@(c, args') = \case
(CmdRange _, o) ->
either (const old) (\r -> (c { range = Just r }, args')) $ fromObject o
(CmdCount _, o) ->
either (const old) (\n -> (c { count = Just n }, args')) $ fromObject o
(CmdBang, o) ->
either (const old) (\b -> (c { bang = Just b }, args')) $ fromObject o
(CmdNargs "*", ObjectArray os) ->
-- CommandArguments -> [String] -> Neovim r st a
(c, os)
(CmdNargs "+", ObjectArray (o:os)) ->
-- CommandArguments -> String -> [String] -> Neovim r st a
(c, o : [ObjectArray os])
(CmdNargs "?", ObjectArray [o]) ->
-- CommandArguments -> Maybe String -> Neovim r st a
(c, [toObject (Just o)])
(CmdNargs "?", ObjectArray []) ->
-- CommandArguments -> Maybe String -> Neovim r st a
(c, [toObject (Nothing :: Maybe Object)])
(CmdNargs "0", ObjectArray []) ->
-- CommandArguments -> Neovim r st a
(c, [])
(CmdNargs "1", ObjectArray [o]) ->
-- CommandArguments -> String -> Neovim r st a
(c, [o])
(CmdRegister, o) ->
either (const old) (\r -> (c { register = Just r }, args')) $ fromObject o
_ -> old
parseParams (Autocmd _ _ _) args = case args of
[ObjectArray fArgs] -> fArgs
_ -> args
|
lslah/nvim-hs
|
library/Neovim/RPC/SocketReader.hs
|
Haskell
|
apache-2.0
| 9,448
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TupleSections #-}
-- | Generate HPC (Haskell Program Coverage) reports
module Stack.Coverage
( deleteHpcReports
, updateTixFile
, generateHpcReport
, HpcReportOpts(..)
, generateHpcReportForTargets
, generateHpcUnifiedReport
, generateHpcMarkupIndex
) where
import Stack.Prelude hiding (Display (..))
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy as BL
import Data.List
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import Distribution.Version (mkVersion)
import Path
import Path.Extra (toFilePathNoTrailingSep)
import Path.IO
import Stack.Build.Target
import Stack.Constants
import Stack.Constants.Config
import Stack.Package
import Stack.Types.Compiler
import Stack.Types.Config
import Stack.Types.NamedComponent
import Stack.Types.Package
import Stack.Types.SourceMap
import System.FilePath (isPathSeparator)
import qualified RIO
import RIO.PrettyPrint
import RIO.Process
import Trace.Hpc.Tix
import Web.Browser (openBrowser)
newtype CoverageException = NonTestSuiteTarget PackageName deriving Typeable
instance Exception CoverageException
instance Show CoverageException where
show (NonTestSuiteTarget name) =
"Can't specify anything except test-suites as hpc report targets (" ++
packageNameString name ++
" is used with a non test-suite target)"
-- | Invoked at the beginning of running with "--coverage"
deleteHpcReports :: HasEnvConfig env => RIO env ()
deleteHpcReports = do
hpcDir <- hpcReportDir
liftIO $ ignoringAbsence (removeDirRecur hpcDir)
-- | Move a tix file into a sub-directory of the hpc report directory. Deletes the old one if one is
-- present.
updateTixFile :: HasEnvConfig env => PackageName -> Path Abs File -> String -> RIO env ()
updateTixFile pkgName' tixSrc testName = do
exists <- doesFileExist tixSrc
when exists $ do
tixDest <- tixFilePath pkgName' testName
liftIO $ ignoringAbsence (removeFile tixDest)
ensureDir (parent tixDest)
-- Remove exe modules because they are problematic. This could be revisited if there's a GHC
-- version that fixes https://ghc.haskell.org/trac/ghc/ticket/1853
mtix <- readTixOrLog tixSrc
case mtix of
Nothing -> logError $ "Failed to read " <> fromString (toFilePath tixSrc)
Just tix -> do
liftIO $ writeTix (toFilePath tixDest) (removeExeModules tix)
-- TODO: ideally we'd do a file move, but IIRC this can
-- have problems. Something about moving between drives
-- on windows?
copyFile tixSrc =<< parseAbsFile (toFilePath tixDest ++ ".premunging")
liftIO $ ignoringAbsence (removeFile tixSrc)
-- | Get the directory used for hpc reports for the given pkgId.
hpcPkgPath :: HasEnvConfig env => PackageName -> RIO env (Path Abs Dir)
hpcPkgPath pkgName' = do
outputDir <- hpcReportDir
pkgNameRel <- parseRelDir (packageNameString pkgName')
return (outputDir </> pkgNameRel)
-- | Get the tix file location, given the name of the file (without extension), and the package
-- identifier string.
tixFilePath :: HasEnvConfig env
=> PackageName -> String -> RIO env (Path Abs File)
tixFilePath pkgName' testName = do
pkgPath <- hpcPkgPath pkgName'
tixRel <- parseRelFile (testName ++ "/" ++ testName ++ ".tix")
return (pkgPath </> tixRel)
-- | Generates the HTML coverage report and shows a textual coverage summary for a package.
generateHpcReport :: HasEnvConfig env
=> Path Abs Dir -> Package -> [Text] -> RIO env ()
generateHpcReport pkgDir package tests = do
compilerVersion <- view actualCompilerVersionL
-- If we're using > GHC 7.10, the hpc 'include' parameter must specify a ghc package key. See
-- https://github.com/commercialhaskell/stack/issues/785
let pkgName' = T.pack $ packageNameString (packageName package)
pkgId = packageIdentifierString (packageIdentifier package)
ghcVersion = getGhcVersion compilerVersion
hasLibrary =
case packageLibraries package of
NoLibraries -> False
HasLibraries _ -> True
internalLibs = packageInternalLibraries package
eincludeName <-
-- Pre-7.8 uses plain PKG-version in tix files.
if ghcVersion < mkVersion [7, 10] then return $ Right $ Just [pkgId]
-- We don't expect to find a package key if there is no library.
else if not hasLibrary && Set.null internalLibs then return $ Right Nothing
-- Look in the inplace DB for the package key.
-- See https://github.com/commercialhaskell/stack/issues/1181#issuecomment-148968986
else do
-- GHC 8.0 uses package id instead of package key.
-- See https://github.com/commercialhaskell/stack/issues/2424
let hpcNameField = if ghcVersion >= mkVersion [8, 0] then "id" else "key"
eincludeName <- findPackageFieldForBuiltPackage pkgDir (packageIdentifier package) internalLibs hpcNameField
case eincludeName of
Left err -> do
logError $ RIO.display err
return $ Left err
Right includeNames -> return $ Right $ Just $ map T.unpack includeNames
forM_ tests $ \testName -> do
tixSrc <- tixFilePath (packageName package) (T.unpack testName)
let report = "coverage report for " <> pkgName' <> "'s test-suite \"" <> testName <> "\""
reportDir = parent tixSrc
case eincludeName of
Left err -> generateHpcErrorReport reportDir (RIO.display (sanitize (T.unpack err)))
-- Restrict to just the current library code, if there is a library in the package (see
-- #634 - this will likely be customizable in the future)
Right mincludeName -> do
let extraArgs = case mincludeName of
Just includeNames -> "--include" : intersperse "--include" (map (\n -> n ++ ":") includeNames)
Nothing -> []
mreportPath <- generateHpcReportInternal tixSrc reportDir report extraArgs extraArgs
forM_ mreportPath (displayReportPath report . pretty)
generateHpcReportInternal :: HasEnvConfig env
=> Path Abs File -> Path Abs Dir -> Text -> [String] -> [String]
-> RIO env (Maybe (Path Abs File))
generateHpcReportInternal tixSrc reportDir report extraMarkupArgs extraReportArgs = do
-- If a .tix file exists, move it to the HPC output directory and generate a report for it.
tixFileExists <- doesFileExist tixSrc
if not tixFileExists
then do
logError $
"Didn't find .tix for " <>
RIO.display report <>
" - expected to find it at " <>
fromString (toFilePath tixSrc) <>
"."
return Nothing
else (`catch` \(err :: ProcessException) -> do
logError $ displayShow err
generateHpcErrorReport reportDir $ RIO.display $ sanitize $ show err
return Nothing) $
(`onException` logError ("Error occurred while producing " <> RIO.display report)) $ do
-- Directories for .mix files.
hpcRelDir <- hpcRelativeDir
-- Compute arguments used for both "hpc markup" and "hpc report".
pkgDirs <- view $ buildConfigL.to (map ppRoot . Map.elems . smwProject . bcSMWanted)
let args =
-- Use index files from all packages (allows cross-package coverage results).
concatMap (\x -> ["--srcdir", toFilePathNoTrailingSep x]) pkgDirs ++
-- Look for index files in the correct dir (relative to each pkgdir).
["--hpcdir", toFilePathNoTrailingSep hpcRelDir, "--reset-hpcdirs"]
logInfo $ "Generating " <> RIO.display report
outputLines <- liftM (map (S8.filter (/= '\r')) . S8.lines . BL.toStrict . fst) $
proc "hpc"
( "report"
: toFilePath tixSrc
: (args ++ extraReportArgs)
)
readProcess_
if all ("(0/0)" `S8.isSuffixOf`) outputLines
then do
let msg html =
"Error: The " <>
RIO.display report <>
" did not consider any code. One possible cause of this is" <>
" if your test-suite builds the library code (see stack " <>
(if html then "<a href='https://github.com/commercialhaskell/stack/issues/1008'>" else "") <>
"issue #1008" <>
(if html then "</a>" else "") <>
"). It may also indicate a bug in stack or" <>
" the hpc program. Please report this issue if you think" <>
" your coverage report should have meaningful results."
logError (msg False)
generateHpcErrorReport reportDir (msg True)
return Nothing
else do
let reportPath = reportDir </> relFileHpcIndexHtml
-- Print output, stripping @\r@ characters because Windows.
forM_ outputLines (logInfo . displayBytesUtf8)
-- Generate the markup.
void $ proc "hpc"
( "markup"
: toFilePath tixSrc
: ("--destdir=" ++ toFilePathNoTrailingSep reportDir)
: (args ++ extraMarkupArgs)
)
readProcess_
return (Just reportPath)
data HpcReportOpts = HpcReportOpts
{ hroptsInputs :: [Text]
, hroptsAll :: Bool
, hroptsDestDir :: Maybe String
, hroptsOpenBrowser :: Bool
} deriving (Show)
generateHpcReportForTargets :: HasEnvConfig env
=> HpcReportOpts -> [Text] -> [Text] -> RIO env ()
generateHpcReportForTargets opts tixFiles targetNames = do
targetTixFiles <-
-- When there aren't any package component arguments, and --all
-- isn't passed, default to not considering any targets.
if not (hroptsAll opts) && null targetNames
then return []
else do
when (hroptsAll opts && not (null targetNames)) $
logWarn $ "Since --all is used, it is redundant to specify these targets: " <> displayShow targetNames
targets <- view $ envConfigL.to envConfigSourceMap.to smTargets.to smtTargets
liftM concat $ forM (Map.toList targets) $ \(name, target) ->
case target of
TargetAll PTDependency -> throwString $
"Error: Expected a local package, but " ++
packageNameString name ++
" is either an extra-dep or in the snapshot."
TargetComps comps -> do
pkgPath <- hpcPkgPath name
forM (toList comps) $ \nc ->
case nc of
CTest testName ->
liftM (pkgPath </>) $ parseRelFile (T.unpack testName ++ "/" ++ T.unpack testName ++ ".tix")
_ -> throwIO $ NonTestSuiteTarget name
TargetAll PTProject -> do
pkgPath <- hpcPkgPath name
exists <- doesDirExist pkgPath
if exists
then do
(dirs, _) <- listDir pkgPath
liftM concat $ forM dirs $ \dir -> do
(_, files) <- listDir dir
return (filter ((".tix" `isSuffixOf`) . toFilePath) files)
else return []
tixPaths <- liftM (\xs -> xs ++ targetTixFiles) $ mapM (resolveFile' . T.unpack) tixFiles
when (null tixPaths) $
throwString "Not generating combined report, because no targets or tix files are specified."
outputDir <- hpcReportDir
reportDir <- case hroptsDestDir opts of
Nothing -> return (outputDir </> relDirCombined </> relDirCustom)
Just destDir -> do
dest <- resolveDir' destDir
ensureDir dest
return dest
let report = "combined report"
mreportPath <- generateUnionReport report reportDir tixPaths
forM_ mreportPath $ \reportPath ->
if hroptsOpenBrowser opts
then do
prettyInfo $ "Opening" <+> pretty reportPath <+> "in the browser."
void $ liftIO $ openBrowser (toFilePath reportPath)
else displayReportPath report (pretty reportPath)
generateHpcUnifiedReport :: HasEnvConfig env => RIO env ()
generateHpcUnifiedReport = do
outputDir <- hpcReportDir
ensureDir outputDir
(dirs, _) <- listDir outputDir
tixFiles0 <- liftM (concat . concat) $ forM (filter (("combined" /=) . dirnameString) dirs) $ \dir -> do
(dirs', _) <- listDir dir
forM dirs' $ \dir' -> do
(_, files) <- listDir dir'
return (filter ((".tix" `isSuffixOf`) . toFilePath) files)
extraTixFiles <- findExtraTixFiles
let tixFiles = tixFiles0 ++ extraTixFiles
reportDir = outputDir </> relDirCombined </> relDirAll
if length tixFiles < 2
then logInfo $
(if null tixFiles then "No tix files" else "Only one tix file") <>
" found in " <>
fromString (toFilePath outputDir) <>
", so not generating a unified coverage report."
else do
let report = "unified report"
mreportPath <- generateUnionReport report reportDir tixFiles
forM_ mreportPath (displayReportPath report . pretty)
generateUnionReport :: HasEnvConfig env
=> Text -> Path Abs Dir -> [Path Abs File]
-> RIO env (Maybe (Path Abs File))
generateUnionReport report reportDir tixFiles = do
(errs, tix) <- fmap (unionTixes . map removeExeModules) (mapMaybeM readTixOrLog tixFiles)
logDebug $ "Using the following tix files: " <> fromString (show tixFiles)
unless (null errs) $ logWarn $
"The following modules are left out of the " <>
RIO.display report <>
" due to version mismatches: " <>
mconcat (intersperse ", " (map fromString errs))
tixDest <- liftM (reportDir </>) $ parseRelFile (dirnameString reportDir ++ ".tix")
ensureDir (parent tixDest)
liftIO $ writeTix (toFilePath tixDest) tix
generateHpcReportInternal tixDest reportDir report [] []
readTixOrLog :: HasLogFunc env => Path b File -> RIO env (Maybe Tix)
readTixOrLog path = do
mtix <- liftIO (readTix (toFilePath path)) `catchAny` \errorCall -> do
logError $ "Error while reading tix: " <> fromString (show errorCall)
return Nothing
when (isNothing mtix) $
logError $ "Failed to read tix file " <> fromString (toFilePath path)
return mtix
-- | Module names which contain '/' have a package name, and so they weren't built into the
-- executable.
removeExeModules :: Tix -> Tix
removeExeModules (Tix ms) = Tix (filter (\(TixModule name _ _ _) -> '/' `elem` name) ms)
unionTixes :: [Tix] -> ([String], Tix)
unionTixes tixes = (Map.keys errs, Tix (Map.elems outputs))
where
(errs, outputs) = Map.mapEither id $ Map.unionsWith merge $ map toMap tixes
toMap (Tix ms) = Map.fromList (map (\x@(TixModule k _ _ _) -> (k, Right x)) ms)
merge (Right (TixModule k hash1 len1 tix1))
(Right (TixModule _ hash2 len2 tix2))
| hash1 == hash2 && len1 == len2 = Right (TixModule k hash1 len1 (zipWith (+) tix1 tix2))
merge _ _ = Left ()
generateHpcMarkupIndex :: HasEnvConfig env => RIO env ()
generateHpcMarkupIndex = do
outputDir <- hpcReportDir
let outputFile = outputDir </> relFileIndexHtml
ensureDir outputDir
(dirs, _) <- listDir outputDir
rows <- liftM (catMaybes . concat) $ forM dirs $ \dir -> do
(subdirs, _) <- listDir dir
forM subdirs $ \subdir -> do
let indexPath = subdir </> relFileHpcIndexHtml
exists' <- doesFileExist indexPath
if not exists' then return Nothing else do
relPath <- stripProperPrefix outputDir indexPath
let package = dirname dir
testsuite = dirname subdir
return $ Just $ T.concat
[ "<tr><td>"
, pathToHtml package
, "</td><td><a href=\""
, pathToHtml relPath
, "\">"
, pathToHtml testsuite
, "</a></td></tr>"
]
writeBinaryFileAtomic outputFile $
"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" <>
-- Part of the css from HPC's output HTML
"<style type=\"text/css\">" <>
"table.dashboard { border-collapse: collapse; border: solid 1px black }" <>
".dashboard td { border: solid 1px black }" <>
".dashboard th { border: solid 1px black }" <>
"</style>" <>
"</head>" <>
"<body>" <>
(if null rows
then
"<b>No hpc_index.html files found in \"" <>
encodeUtf8Builder (pathToHtml outputDir) <>
"\".</b>"
else
"<table class=\"dashboard\" width=\"100%\" border=\"1\"><tbody>" <>
"<p><b>NOTE: This is merely a listing of the html files found in the coverage reports directory. Some of these reports may be old.</b></p>" <>
"<tr><th>Package</th><th>TestSuite</th><th>Modification Time</th></tr>" <>
foldMap encodeUtf8Builder rows <>
"</tbody></table>") <>
"</body></html>"
unless (null rows) $
logInfo $ "\nAn index of the generated HTML coverage reports is available at " <>
fromString (toFilePath outputFile)
generateHpcErrorReport :: MonadIO m => Path Abs Dir -> Utf8Builder -> m ()
generateHpcErrorReport dir err = do
ensureDir dir
let fp = toFilePath (dir </> relFileHpcIndexHtml)
writeFileUtf8Builder fp $
"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></head><body>" <>
"<h1>HPC Report Generation Error</h1>" <>
"<p>" <>
err <>
"</p>" <>
"</body></html>"
pathToHtml :: Path b t -> Text
pathToHtml = T.dropWhileEnd (=='/') . sanitize . toFilePath
-- | Escape HTML symbols (copied from Text.Hastache)
htmlEscape :: LT.Text -> LT.Text
htmlEscape = LT.concatMap proc_
where
proc_ '&' = "&"
proc_ '\\' = "\"
proc_ '"' = """
proc_ '\'' = "'"
proc_ '<' = "<"
proc_ '>' = ">"
proc_ h = LT.singleton h
sanitize :: String -> Text
sanitize = LT.toStrict . htmlEscape . LT.pack
dirnameString :: Path r Dir -> String
dirnameString = dropWhileEnd isPathSeparator . toFilePath . dirname
findPackageFieldForBuiltPackage
:: HasEnvConfig env
=> Path Abs Dir -> PackageIdentifier -> Set.Set Text -> Text
-> RIO env (Either Text [Text])
findPackageFieldForBuiltPackage pkgDir pkgId internalLibs field = do
distDir <- distDirFromDir pkgDir
let inplaceDir = distDir </> relDirPackageConfInplace
pkgIdStr = packageIdentifierString pkgId
notFoundErr = return $ Left $ "Failed to find package key for " <> T.pack pkgIdStr
extractField path = do
contents <- readFileUtf8 (toFilePath path)
case asum (map (T.stripPrefix (field <> ": ")) (T.lines contents)) of
Just result -> return $ Right $ T.strip result
Nothing -> notFoundErr
cabalVer <- view cabalVersionL
if cabalVer < mkVersion [1, 24]
then do
-- here we don't need to handle internal libs
path <- liftM (inplaceDir </>) $ parseRelFile (pkgIdStr ++ "-inplace.conf")
logDebug $ "Parsing config in Cabal < 1.24 location: " <> fromString (toFilePath path)
exists <- doesFileExist path
if exists then fmap (:[]) <$> extractField path else notFoundErr
else do
-- With Cabal-1.24, it's in a different location.
logDebug $ "Scanning " <> fromString (toFilePath inplaceDir) <> " for files matching " <> fromString pkgIdStr
(_, files) <- handleIO (const $ return ([], [])) $ listDir inplaceDir
logDebug $ displayShow files
-- From all the files obtained from the scanning process above, we
-- need to identify which are .conf files and then ensure that
-- there is at most one .conf file for each library and internal
-- library (some might be missing if that component has not been
-- built yet). We should error if there are more than one .conf
-- file for a component or if there are no .conf files at all in
-- the searched location.
let toFilename = T.pack . toFilePath . filename
-- strip known prefix and suffix from the found files to determine only the conf files
stripKnown = T.stripSuffix ".conf" <=< T.stripPrefix (T.pack (pkgIdStr ++ "-"))
stripped = mapMaybe (\file -> fmap (,file) . stripKnown . toFilename $ file) files
-- which component could have generated each of these conf files
stripHash n = let z = T.dropWhile (/= '-') n in if T.null z then "" else T.tail z
matchedComponents = map (\(n, f) -> (stripHash n, [f])) stripped
byComponents = Map.restrictKeys (Map.fromListWith (++) matchedComponents) $ Set.insert "" internalLibs
logDebug $ displayShow byComponents
if Map.null $ Map.filter (\fs -> length fs > 1) byComponents
then case concat $ Map.elems byComponents of
[] -> notFoundErr
-- for each of these files, we need to extract the requested field
paths -> do
(errors, keys) <- partitionEithers <$> traverse extractField paths
case errors of
(a:_) -> return $ Left a -- the first error only, since they're repeated anyway
[] -> return $ Right keys
else return $ Left $ "Multiple files matching " <> T.pack (pkgIdStr ++ "-*.conf") <> " found in " <>
T.pack (toFilePath inplaceDir) <> ". Maybe try 'stack clean' on this package?"
displayReportPath :: (HasTerm env)
=> Text -> StyleDoc -> RIO env ()
displayReportPath report reportPath =
prettyInfo $ "The" <+> fromString (T.unpack report) <+> "is available at" <+> reportPath
findExtraTixFiles :: HasEnvConfig env => RIO env [Path Abs File]
findExtraTixFiles = do
outputDir <- hpcReportDir
let dir = outputDir </> relDirExtraTixFiles
dirExists <- doesDirExist dir
if dirExists
then do
(_, files) <- listDir dir
return $ filter ((".tix" `isSuffixOf`) . toFilePath) files
else return []
|
juhp/stack
|
src/Stack/Coverage.hs
|
Haskell
|
bsd-3-clause
| 24,184
|
--
-- Copyright © 2013-2014 Anchor Systems, Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
-- the 3-clause BSD licence.
--
-- | client interface for sending data to the vault.
--
-- This module provides functions for preparing and queuing points to be sent
-- by a server to the vault.
--
-- If you call close, you can be assured that your data is safe and will at
-- some point end up in the data vault (excluding local disk failure). This
-- assumption is based on a functional marquise daemon with connectivity
-- eventually running within your namespace.
--
-- We provide no way to *absolutely* ensure that a point is currently written
-- to the vault. Such a guarantee would require blocking and complex queuing,
-- or observing various underlying mechanisms that should ideally remain
-- abstract.
--
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- Hide warnings for the deprecated ErrorT transformer:
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
module Marquise.Client.Core where
import Control.Applicative
import qualified Control.Exception as E
import Control.Monad.Error
import Crypto.MAC.SipHash
import Data.Bits
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Char (isAlphaNum)
import Data.Packer
import Data.Word (Word64)
import Pipes
import Marquise.Classes
import Marquise.Types
import Vaultaire.Types
-- | Create a SpoolName. Only alphanumeric characters are allowed, max length
-- is 32 characters.
makeSpoolName :: Monad m => String -> m SpoolName
makeSpoolName s
| any (not . isAlphaNum) s = E.throw $ MarquiseException s
| otherwise = return (SpoolName s)
-- | Create a name in the spool. Only alphanumeric characters are allowed, max length
-- is 32 characters.
createSpoolFiles :: MarquiseSpoolFileMonad m
=> String
-> m SpoolFiles
createSpoolFiles s = do
n <- makeSpoolName s
createDirectories n
randomSpoolFiles n
-- | Deterministically convert a ByteString to an Address by taking the
-- most significant 63 bytes of its SipHash-2-4[0] with a zero key. The
-- LSB of the resulting 64-bit value is not part of the unique portion
-- of the address; it is set when queueing writes, depending on the
-- point type (simple or extended) being written.
--
-- [0] https://131002.net/siphash/
hashIdentifier :: ByteString -> Address
hashIdentifier = Address . (`clearBit` 0) . unSipHash . hash iv
where
iv = SipKey 0 0
unSipHash (SipHash h) = h :: Word64
-- | Generate an un-used Address. You will need to store this for later re-use.
requestUnique :: MarquiseContentsMonad m conn
=> Origin
-> conn
-> m Address
requestUnique origin conn = do
sendContentsRequest GenerateNewAddress origin conn
response <- recvContentsResponse conn
case response of
RandomAddress addr -> return addr
_ -> error "requestUnique: Invalid response"
-- | Set the key,value tags as metadata on the given Address.
updateSourceDict :: MarquiseContentsMonad m conn
=> Address
-> SourceDict
-> Origin
-> conn
-> m ()
updateSourceDict addr source_dict origin conn = do
sendContentsRequest (UpdateSourceTag addr source_dict) origin conn
response <- recvContentsResponse conn
case response of
UpdateSuccess -> return ()
_ -> error "requestSourceDictUpdate: Invalid response"
-- | Remove the supplied key,value tags from metadata on the Address, if present.
removeSourceDict :: MarquiseContentsMonad m conn
=> Address
-> SourceDict
-> Origin
-> conn
-> m ()
removeSourceDict addr source_dict origin conn = do
sendContentsRequest (RemoveSourceTag addr source_dict) origin conn
response <- recvContentsResponse conn
case response of
RemoveSuccess -> return ()
_ -> error "requestSourceDictRemoval: Invalid response"
-- | Stream read every Address associated with the given Origin
enumerateOrigin :: MarquiseContentsMonad m conn
=> Origin
-> conn
-> Producer (Address, SourceDict) m ()
enumerateOrigin origin conn = do
lift $ sendContentsRequest ContentsListRequest origin conn
loop
where
loop = do
resp <- lift $ recvContentsResponse conn
case resp of
ContentsListEntry addr dict -> do
yield (addr, dict)
loop
EndOfContentsList -> return ()
_ -> error "enumerateOrigin loop: Invalid response"
-- | Stream read every SimpleBurst from the Address between the given times
readSimple :: MarquiseReaderMonad m conn
=> Address
-> TimeStamp
-> TimeStamp
-> Origin
-> conn
-> Producer' SimpleBurst m ()
readSimple addr start end origin conn = do
lift $ sendReaderRequest (SimpleReadRequest addr start end) origin conn
loop
where
loop = do
response <- lift $ recvReaderResponse conn
case response of
SimpleStream burst ->
yield burst >> loop
EndOfStream ->
return ()
InvalidReadOrigin ->
error "readSimple loop: Invalid origin"
_ ->
error "readSimple loop: Invalid response"
-- | Like @readSimple@ but also decodes the points.
--
readSimplePoints
:: MarquiseReaderMonad m conn
=> Address
-> TimeStamp
-> TimeStamp
-> Origin
-> conn
-> Producer' SimplePoint m ()
readSimplePoints addr start end origin conn
= for (readSimple addr start end origin conn >-> decodeSimple) yield
-- | Stream read every ExtendedBurst from the Address between the given times
readExtended :: MarquiseReaderMonad m conn
=> Address
-> TimeStamp
-> TimeStamp
-> Origin
-> conn
-> Producer' ExtendedBurst m ()
readExtended addr start end origin conn = do
lift $ sendReaderRequest (ExtendedReadRequest addr start end) origin conn
loop
where
loop = do
response <- lift $ recvReaderResponse conn
case response of
ExtendedStream burst ->
yield burst >> loop
EndOfStream ->
return ()
_ ->
error "readExtended loop: Invalid response"
-- | Like @readExtended@ but also decodes the points.
--
readExtendedPoints
:: MarquiseReaderMonad m conn
=> Address
-> TimeStamp
-> TimeStamp
-> Origin
-> conn
-> Producer' ExtendedPoint m ()
readExtendedPoints addr start end origin conn
= for (readExtended addr start end origin conn >-> decodeExtended) yield
-- | Stream converts raw SimpleBursts into SimplePoints
decodeSimple :: Monad m => Pipe SimpleBurst SimplePoint m ()
decodeSimple = forever (unSimpleBurst <$> await >>= emitFrom 0)
where
emitFrom os chunk
| os >= BS.length chunk = return ()
| otherwise = do
yield $ decodeSimple' os chunk
emitFrom (os + 24) chunk
-- | Decodes a single point at an offset.
decodeSimple' :: Int -> ByteString -> SimplePoint
decodeSimple' offset chunk = flip runUnpacking chunk $ do
unpackSetPosition offset
addr <- Address <$> getWord64LE
time <- TimeStamp <$> getWord64LE
payload <- getWord64LE
return $ SimplePoint addr time payload
-- | Stream converts raw ExtendedBursts into ExtendedPoints
decodeExtended :: Monad m => Pipe ExtendedBurst ExtendedPoint m ()
decodeExtended = forever (unExtendedBurst <$> await >>= emitFrom 0)
where
emitFrom os chunk
| os >= BS.length chunk = return ()
| otherwise = do
let result = runUnpacking (unpack os) chunk
yield result
let size = BS.length (extendedPayload result) + 24
emitFrom (os + size) chunk
unpack os = do
unpackSetPosition os
addr <- Address <$> getWord64LE
time <- TimeStamp <$> getWord64LE
len <- fromIntegral <$> getWord64LE
payload <- if len == 0
then return BS.empty
else getBytes len
return $ ExtendedPoint addr time payload
-- | Send a "simple" data point. Interpretation of this point, e.g.
-- float/signed is up to you, but it must be sent in the form of a Word64.
-- Clears the least-significant bit of the address to indicate that this
-- is a simple datapoint.
queueSimple
:: MarquiseSpoolFileMonad m
=> SpoolFiles
-> Address
-> TimeStamp
-> Word64
-> m ()
queueSimple sfs (Address ad) (TimeStamp ts) w = appendPoints sfs bytes
where
bytes = runPacking 24 $ do
putWord64LE (ad `clearBit` 0)
putWord64LE ts
putWord64LE w
-- | Send an "extended" data point. Again, representation is up to you.
-- Sets the least-significant bit of the address to indicate that this is
-- an extended data point.
queueExtended
:: MarquiseSpoolFileMonad m
=> SpoolFiles
-> Address
-> TimeStamp
-> ByteString
-> m ()
queueExtended sfs (Address ad) (TimeStamp ts) bs = appendPoints sfs bytes
where
len = BS.length bs
bytes = runPacking (24 + len) $ do
putWord64LE (ad `setBit` 0)
putWord64LE ts
putWord64LE $ fromIntegral len
putBytes bs
-- | Updates the SourceDict at addr with source_dict
queueSourceDictUpdate
:: MarquiseSpoolFileMonad m
=> SpoolFiles
-> Address
-> SourceDict
-> m ()
queueSourceDictUpdate sfs (Address addr) source_dict = appendContents sfs bytes
where
source_dict_bytes = toWire source_dict
source_dict_len = BS.length source_dict_bytes
bytes = runPacking (source_dict_len + 16) $ do
putWord64LE addr
putWord64LE (fromIntegral source_dict_len)
putBytes source_dict_bytes
-- | Ensure that all sent points have hit the local disk.
flush
:: MarquiseSpoolFileMonad m
=> SpoolFiles
-> m ()
flush = close
|
anchor/marquise
|
lib/Marquise/Client/Core.hs
|
Haskell
|
bsd-3-clause
| 10,352
|
{-# OPTIONS_GHC -Wall #-}
module Optimize.Inline (inline) where
import Control.Arrow (second, (***))
import Control.Monad (foldM)
import qualified Data.List as List
import qualified Data.Map as Map
import AST.Expression.Optimized (Expr(..), Decider(..), Choice(..))
import qualified AST.Expression.Optimized as Opt
import qualified AST.Variable as Var
import qualified Optimize.Environment as Env
inline :: Map.Map String Opt.Expr -> Opt.Expr -> Env.Optimizer Opt.Expr
inline rawSubs expression =
let
counts =
count expression
annotatedSubs =
Map.toList (Map.intersectionWith (,) counts rawSubs)
in
do (Subs subs defs) <- foldM processSubs (Subs Map.empty []) annotatedSubs
let inlinedExpr = replace subs expression
return $
if null defs then
inlinedExpr
else
Let (map (\(name, expr) -> Opt.Def Opt.dummyFacts name expr) defs) inlinedExpr
data Subs = Subs
{ _substitutions :: Map.Map String Opt.Expr
, _definitions :: [(String, Opt.Expr)]
}
processSubs :: Subs -> (String, (Int, Opt.Expr)) -> Env.Optimizer Subs
processSubs (Subs subs defs) (name, (n, expr)) =
if n == 1 then
return $ Subs (Map.insert name expr subs) defs
else
do uniqueName <- Env.freshName
return $ Subs
(Map.insert name (Opt.Var (Var.local uniqueName)) subs)
((uniqueName, expr) : defs)
-- HELPERS
deleteBatch :: [String] -> Map.Map String a -> Map.Map String a
deleteBatch names dict =
List.foldl' (flip Map.delete) dict names
getDefName :: Opt.Def -> String
getDefName def =
case def of
Opt.Def _ name _ ->
name
Opt.TailDef _ name _ _ ->
name
-- COUNT VARIABLE APPEARANCES
count :: Opt.Expr -> Map.Map String Int
count expression =
let
count2 a b =
Map.unionWith (+) (count a) (count b)
countMany xs =
Map.unionsWith (+) (map count xs)
in
case expression of
Literal _ ->
Map.empty
Var (Var.Canonical home name) ->
case home of
Var.Local ->
Map.singleton name 1
Var.BuiltIn ->
Map.empty
Var.Module _ ->
Map.empty
Var.TopLevel _ ->
Map.empty
Range lo hi ->
count2 lo hi
ExplicitList exprs ->
countMany exprs
Binop _op left right ->
count2 left right
Function args body ->
deleteBatch args (count body)
Call func args ->
Map.unionWith (+) (count func) (countMany args)
TailCall _name _argNames args ->
countMany args
If branches finally ->
Map.unionsWith (+) (count finally : map (uncurry count2) branches)
Let defs expr ->
let
countDef def =
case def of
Opt.Def _ name body ->
Map.delete name (count body)
Opt.TailDef _ name argNames body ->
deleteBatch (name:argNames) (count body)
exprCount =
deleteBatch (map getDefName defs) (count expr)
in
Map.unionsWith (+) (exprCount : map countDef defs)
Case _ decider jumps ->
let
countDecider dcdr =
case dcdr of
Leaf (Inline expr) ->
count expr
Leaf (Jump _) ->
Map.empty
Chain _ success failure ->
Map.unionWith (+) (countDecider success) (countDecider failure)
FanOut _path tests fallback ->
Map.unionsWith (+) (map countDecider (fallback : map snd tests))
in
Map.unionsWith (+) (countDecider decider : map (count . snd) jumps)
Data _tag values ->
countMany values
DataAccess root _index ->
count root
Access record _field ->
count record
Update record fields ->
Map.unionWith (+) (count record) (countMany (map snd fields))
Record fields ->
countMany (map snd fields)
Cmd _ ->
Map.empty
Sub _ ->
Map.empty
OutgoingPort _ _ ->
Map.empty
IncomingPort _ _ ->
Map.empty
Program _ expr ->
count expr
GLShader _ _ _ ->
Map.empty
Crash _ _ maybeBranchProblem ->
maybe Map.empty count maybeBranchProblem
-- REPLACE
replace :: Map.Map String Opt.Expr -> Opt.Expr -> Opt.Expr
replace substitutions expression =
let
go = replace substitutions
in
case expression of
Literal _ ->
expression
Var (Var.Canonical Var.Local name) ->
maybe expression id (Map.lookup name substitutions)
Var _ ->
expression
Range lo hi ->
Range (go lo) (go hi)
ExplicitList exprs ->
ExplicitList (map go exprs)
Binop op left right ->
Binop op (go left) (go right)
Function args body ->
Function args (replace (deleteBatch args substitutions) body)
Call func args ->
Call (go func) (map go args)
TailCall name argNames args ->
TailCall name argNames (map go args)
If branches finally ->
If (map (go *** go) branches) (go finally)
Let defs expr ->
let
replaceDef def =
case def of
Opt.Def facts name body ->
Opt.Def facts name
(replace (Map.delete name substitutions) body)
Opt.TailDef facts name argNames body ->
Opt.TailDef facts name argNames
(replace (deleteBatch (name:argNames) substitutions) body)
boundNames =
map getDefName defs
in
Let
(map replaceDef defs)
(replace (deleteBatch boundNames substitutions) expr)
Case exprName decider jumps ->
let
goDecider dcdr =
case dcdr of
Leaf (Inline expr) ->
Leaf (Inline (go expr))
Leaf (Jump _target) ->
dcdr
Chain chain success failure ->
Chain chain (goDecider success) (goDecider failure)
FanOut path tests fallback ->
FanOut path (map (second goDecider) tests) (goDecider fallback)
in
Case exprName (goDecider decider) (map (second go) jumps)
Data tag values ->
Data tag (map go values)
DataAccess root index ->
DataAccess (go root) index
Access record field ->
Access (go record) field
Update record fields ->
Update (go record) (map (second go) fields)
Record fields ->
Record (map (second go) fields)
Cmd _ ->
expression
Sub _ ->
expression
OutgoingPort _ _ ->
expression
IncomingPort _ _ ->
expression
Program kind expr ->
Program kind (go expr)
GLShader _ _ _ ->
expression
Crash home region maybeBranchProblem ->
Crash home region (fmap go maybeBranchProblem)
|
mgold/Elm
|
src/Optimize/Inline.hs
|
Haskell
|
bsd-3-clause
| 7,028
|
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, FlexibleContexts #-}
module Text.Parsec.Indentation.Char where
import Text.Parsec.Prim (ParsecT, mkPT, runParsecT,
Stream(..),
Consumed(..), Reply(..),
State(..))
import Text.Parsec.Pos (sourceColumn)
import Text.Parser.Indentation.Implementation (Indentation)
----------------
-- Unicode char
-- newtype UnicodeIndentStream
----------------
-- Based on Char
{-# INLINE mkCharIndentStream #-}
mkCharIndentStream :: s -> CharIndentStream s
mkCharIndentStream s = CharIndentStream 1 s
data CharIndentStream s = CharIndentStream { charIndentStreamColumn :: {-# UNPACK #-} !Indentation,
charIndentStreamStream :: !s } deriving (Show)
instance (Stream s m Char) => Stream (CharIndentStream s) m (Char, Indentation) where
uncons (CharIndentStream i s) = do
x <- uncons s
case x of
Nothing -> return Nothing
Just (c, cs) -> return (Just ((c, i), CharIndentStream (updateColumn i c) cs))
{-# INLINE updateColumn #-}
updateColumn :: Integral a => a -> Char -> a
updateColumn _ '\n' = 1
updateColumn i '\t' = i + 8 - ((i-1) `mod` 8)
updateColumn i _ = i + 1
{-# INLINE charIndentStreamParser #-}
charIndentStreamParser :: (Monad m) => ParsecT s u m t -> ParsecT (CharIndentStream s) u m (t, Indentation)
charIndentStreamParser p = mkPT $ \state ->
let go (Ok a state' e) = return (Ok (a, sourceColumn $ statePos state) (state' { stateInput = CharIndentStream (sourceColumn $ statePos state') (stateInput state') }) e)
go (Error e) = return (Error e)
in runParsecT p (state { stateInput = charIndentStreamStream (stateInput state) })
>>= consumed (return . Consumed . go) (return . Empty . go)
{-# INLINE consumed #-}
consumed :: (Monad m) => (a -> m b) -> (a -> m b) -> Consumed (m a) -> m b
consumed c _ (Consumed m) = m >>= c
consumed _ e (Empty m) = m >>= e
|
lambdageek/indentation
|
indentation-parsec/src/Text/Parsec/Indentation/Char.hs
|
Haskell
|
bsd-3-clause
| 1,980
|
y = f(x1) + g(Foo.x2)
|
mpickering/hlint-refactor
|
tests/examples/Bracket38.hs
|
Haskell
|
bsd-3-clause
| 22
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Vimus.Render (
Render
, runRender
, getWindowSize
, addstr
, addLine
, chgat
, withColor
-- * exported to silence warnings
, Environment (..)
-- * exported for testing
, fitToColumn
) where
import Control.Applicative
import Control.Monad.Reader
import UI.Curses hiding (wgetch, ungetch, mvaddstr, err, mvwchgat, addstr, wcolor_set)
import Data.Char.WCWidth
import Vimus.Widget.Type
import Vimus.WindowLayout
data Environment = Environment {
environmentWindow :: Window
, environmentOffsetY :: Int
, environmentOffsetX :: Int
, environmentSize :: WindowSize
}
newtype Render a = Render (ReaderT Environment IO a)
deriving (Functor, Monad, Applicative)
runRender :: Window -> Int -> Int -> WindowSize -> Render a -> IO a
runRender window y x ws (Render action) = runReaderT action (Environment window y x ws)
getWindowSize :: Render WindowSize
getWindowSize = Render (asks environmentSize)
-- | Translate given coordinates and run given action
--
-- The action is only run, if coordinates are within the drawing area.
withTranslated :: Int -> Int -> (Window -> Int -> Int -> Int -> IO a) -> Render ()
withTranslated y_ x_ action = Render $ do
r <- ask
case r of
Environment window offsetY offsetX (WindowSize sizeY sizeX)
| 0 <= x && x < (sizeX + offsetX)
&& 0 <= y && y < (sizeY + offsetY) -> liftIO $ void (action window y x n)
| otherwise -> return ()
where
x = x_ + offsetX
y = y_ + offsetY
n = sizeX - x
addstr :: Int -> Int -> String -> Render ()
addstr y_ x_ str = withTranslated y_ x_ $ \window y x n ->
mvwaddnwstr window y x str (fitToColumn str n)
-- |
-- Determine how many characters from a given string fit in a column of a given
-- width.
fitToColumn :: String -> Int -> Int
fitToColumn str maxWidth = go str 0 0
where
go [] _ n = n
go (x:xs) width n
| width_ <= maxWidth = go xs width_ (succ n)
| otherwise = n
where
width_ = width + wcwidth x
addLine :: Int -> Int -> TextLine -> Render ()
addLine y_ x_ (TextLine xs) = go y_ x_ xs
where
go y x chunks = case chunks of
[] -> return ()
c:cs -> case c of
Plain s -> addstr y x s >> go y (x + length s) cs
Colored color s -> withColor color (addstr y x s) >> go y (x + length s) cs
chgat :: Int -> [Attribute] -> WindowColor -> Render ()
chgat y_ attr wc = withTranslated y_ 0 $ \window y x n ->
mvwchgat window y x n attr wc
withColor :: WindowColor -> Render a -> Render a
withColor color action = do
window <- Render $ asks environmentWindow
setColor window color *> action <* setColor window MainColor
where
setColor w c = Render . liftIO $ wcolor_set w c
|
haasn/vimus
|
src/Vimus/Render.hs
|
Haskell
|
mit
| 2,872
|
{-# LANGUAGE CPP, RecordWildCards, GADTs #-}
module CmmLayoutStack (
cmmLayoutStack, setInfoTableStackMap
) where
import StgCmmUtils ( callerSaveVolatileRegs ) -- XXX layering violation
import StgCmmForeign ( saveThreadState, loadThreadState ) -- XXX layering violation
import BasicTypes
import Cmm
import CmmInfo
import BlockId
import CLabel
import CmmUtils
import MkGraph
import ForeignCall
import CmmLive
import CmmProcPoint
import SMRep
import Hoopl
import UniqSupply
import StgCmmUtils ( newTemp )
import Maybes
import UniqFM
import Util
import DynFlags
import FastString
import Outputable hiding ( isEmpty )
import qualified Data.Set as Set
import Control.Monad.Fix
import Data.Array as Array
import Data.Bits
import Data.List (nub)
import Control.Monad (liftM)
import Prelude hiding ((<*>))
#include "HsVersions.h"
{- Note [Stack Layout]
The job of this pass is to
- replace references to abstract stack Areas with fixed offsets from Sp.
- replace the CmmHighStackMark constant used in the stack check with
the maximum stack usage of the proc.
- save any variables that are live across a call, and reload them as
necessary.
Before stack allocation, local variables remain live across native
calls (CmmCall{ cmm_cont = Just _ }), and after stack allocation local
variables are clobbered by native calls.
We want to do stack allocation so that as far as possible
- stack use is minimized, and
- unnecessary stack saves and loads are avoided.
The algorithm we use is a variant of linear-scan register allocation,
where the stack is our register file.
- First, we do a liveness analysis, which annotates every block with
the variables live on entry to the block.
- We traverse blocks in reverse postorder DFS; that is, we visit at
least one predecessor of a block before the block itself. The
stack layout flowing from the predecessor of the block will
determine the stack layout on entry to the block.
- We maintain a data structure
Map Label StackMap
which describes the contents of the stack and the stack pointer on
entry to each block that is a successor of a block that we have
visited.
- For each block we visit:
- Look up the StackMap for this block.
- If this block is a proc point (or a call continuation, if we
aren't splitting proc points), emit instructions to reload all
the live variables from the stack, according to the StackMap.
- Walk forwards through the instructions:
- At an assignment x = Sp[loc]
- Record the fact that Sp[loc] contains x, so that we won't
need to save x if it ever needs to be spilled.
- At an assignment x = E
- If x was previously on the stack, it isn't any more
- At the last node, if it is a call or a jump to a proc point
- Lay out the stack frame for the call (see setupStackFrame)
- emit instructions to save all the live variables
- Remember the StackMaps for all the successors
- emit an instruction to adjust Sp
- If the last node is a branch, then the current StackMap is the
StackMap for the successors.
- Manifest Sp: replace references to stack areas in this block
with real Sp offsets. We cannot do this until we have laid out
the stack area for the successors above.
In this phase we also eliminate redundant stores to the stack;
see elimStackStores.
- There is one important gotcha: sometimes we'll encounter a control
transfer to a block that we've already processed (a join point),
and in that case we might need to rearrange the stack to match
what the block is expecting. (exactly the same as in linear-scan
register allocation, except here we have the luxury of an infinite
supply of temporary variables).
- Finally, we update the magic CmmHighStackMark constant with the
stack usage of the function, and eliminate the whole stack check
if there was no stack use. (in fact this is done as part of the
main traversal, by feeding the high-water-mark output back in as
an input. I hate cyclic programming, but it's just too convenient
sometimes.)
There are plenty of tricky details: update frames, proc points, return
addresses, foreign calls, and some ad-hoc optimisations that are
convenient to do here and effective in common cases. Comments in the
code below explain these.
-}
-- All stack locations are expressed as positive byte offsets from the
-- "base", which is defined to be the address above the return address
-- on the stack on entry to this CmmProc.
--
-- Lower addresses have higher StackLocs.
--
type StackLoc = ByteOff
{-
A StackMap describes the stack at any given point. At a continuation
it has a particular layout, like this:
| | <- base
|-------------|
| ret0 | <- base + 8
|-------------|
. upd frame . <- base + sm_ret_off
|-------------|
| |
. vars .
. (live/dead) .
| | <- base + sm_sp - sm_args
|-------------|
| ret1 |
. ret vals . <- base + sm_sp (<--- Sp points here)
|-------------|
Why do we include the final return address (ret0) in our stack map? I
have absolutely no idea, but it seems to be done that way consistently
in the rest of the code generator, so I played along here. --SDM
Note that we will be constructing an info table for the continuation
(ret1), which needs to describe the stack down to, but not including,
the update frame (or ret0, if there is no update frame).
-}
data StackMap = StackMap
{ sm_sp :: StackLoc
-- ^ the offset of Sp relative to the base on entry
-- to this block.
, sm_args :: ByteOff
-- ^ the number of bytes of arguments in the area for this block
-- Defn: the offset of young(L) relative to the base is given by
-- (sm_sp - sm_args) of the StackMap for block L.
, sm_ret_off :: ByteOff
-- ^ Number of words of stack that we do not describe with an info
-- table, because it contains an update frame.
, sm_regs :: UniqFM (LocalReg,StackLoc)
-- ^ regs on the stack
}
instance Outputable StackMap where
ppr StackMap{..} =
text "Sp = " <> int sm_sp $$
text "sm_args = " <> int sm_args $$
text "sm_ret_off = " <> int sm_ret_off $$
text "sm_regs = " <> ppr (eltsUFM sm_regs)
cmmLayoutStack :: DynFlags -> ProcPointSet -> ByteOff -> CmmGraph
-> UniqSM (CmmGraph, BlockEnv StackMap)
cmmLayoutStack dflags procpoints entry_args
graph0@(CmmGraph { g_entry = entry })
= do
-- We need liveness info. Dead assignments are removed later
-- by the sinking pass.
let (graph, liveness) = (graph0, cmmLocalLiveness dflags graph0)
blocks = postorderDfs graph
(final_stackmaps, _final_high_sp, new_blocks) <-
mfix $ \ ~(rec_stackmaps, rec_high_sp, _new_blocks) ->
layout dflags procpoints liveness entry entry_args
rec_stackmaps rec_high_sp blocks
new_blocks' <- mapM (lowerSafeForeignCall dflags) new_blocks
return (ofBlockList entry new_blocks', final_stackmaps)
layout :: DynFlags
-> BlockSet -- proc points
-> BlockEnv CmmLocalLive -- liveness
-> BlockId -- entry
-> ByteOff -- stack args on entry
-> BlockEnv StackMap -- [final] stack maps
-> ByteOff -- [final] Sp high water mark
-> [CmmBlock] -- [in] blocks
-> UniqSM
( BlockEnv StackMap -- [out] stack maps
, ByteOff -- [out] Sp high water mark
, [CmmBlock] -- [out] new blocks
)
layout dflags procpoints liveness entry entry_args final_stackmaps final_sp_high blocks
= go blocks init_stackmap entry_args []
where
(updfr, cont_info) = collectContInfo blocks
init_stackmap = mapSingleton entry StackMap{ sm_sp = entry_args
, sm_args = entry_args
, sm_ret_off = updfr
, sm_regs = emptyUFM
}
go [] acc_stackmaps acc_hwm acc_blocks
= return (acc_stackmaps, acc_hwm, acc_blocks)
go (b0 : bs) acc_stackmaps acc_hwm acc_blocks
= do
let (entry0@(CmmEntry entry_lbl tscope), middle0, last0) = blockSplit b0
let stack0@StackMap { sm_sp = sp0 }
= mapFindWithDefault
(pprPanic "no stack map for" (ppr entry_lbl))
entry_lbl acc_stackmaps
-- (a) Update the stack map to include the effects of
-- assignments in this block
let stack1 = foldBlockNodesF (procMiddle acc_stackmaps) middle0 stack0
-- (b) Insert assignments to reload all the live variables if this
-- block is a proc point
let middle1 = if entry_lbl `setMember` procpoints
then foldr blockCons middle0 (insertReloads stack0)
else middle0
-- (c) Look at the last node and if we are making a call or
-- jumping to a proc point, we must save the live
-- variables, adjust Sp, and construct the StackMaps for
-- each of the successor blocks. See handleLastNode for
-- details.
(middle2, sp_off, last1, fixup_blocks, out)
<- handleLastNode dflags procpoints liveness cont_info
acc_stackmaps stack1 tscope middle0 last0
-- (d) Manifest Sp: run over the nodes in the block and replace
-- CmmStackSlot with CmmLoad from Sp with a concrete offset.
--
-- our block:
-- middle1 -- the original middle nodes
-- middle2 -- live variable saves from handleLastNode
-- Sp = Sp + sp_off -- Sp adjustment goes here
-- last1 -- the last node
--
let middle_pre = blockToList $ foldl blockSnoc middle1 middle2
final_blocks = manifestSp dflags final_stackmaps stack0 sp0 final_sp_high entry0
middle_pre sp_off last1 fixup_blocks
acc_stackmaps' = mapUnion acc_stackmaps out
-- If this block jumps to the GC, then we do not take its
-- stack usage into account for the high-water mark.
-- Otherwise, if the only stack usage is in the stack-check
-- failure block itself, we will do a redundant stack
-- check. The stack has a buffer designed to accommodate
-- the largest amount of stack needed for calling the GC.
--
this_sp_hwm | isGcJump last0 = 0
| otherwise = sp0 - sp_off
hwm' = maximum (acc_hwm : this_sp_hwm : map sm_sp (mapElems out))
go bs acc_stackmaps' hwm' (final_blocks ++ acc_blocks)
-- -----------------------------------------------------------------------------
-- Not foolproof, but GCFun is the culprit we most want to catch
isGcJump :: CmmNode O C -> Bool
isGcJump (CmmCall { cml_target = CmmReg (CmmGlobal l) })
= l == GCFun || l == GCEnter1
isGcJump _something_else = False
-- -----------------------------------------------------------------------------
-- This doesn't seem right somehow. We need to find out whether this
-- proc will push some update frame material at some point, so that we
-- can avoid using that area of the stack for spilling. The
-- updfr_space field of the CmmProc *should* tell us, but it doesn't
-- (I think maybe it gets filled in later when we do proc-point
-- splitting).
--
-- So we'll just take the max of all the cml_ret_offs. This could be
-- unnecessarily pessimistic, but probably not in the code we
-- generate.
collectContInfo :: [CmmBlock] -> (ByteOff, BlockEnv ByteOff)
collectContInfo blocks
= (maximum ret_offs, mapFromList (catMaybes mb_argss))
where
(mb_argss, ret_offs) = mapAndUnzip get_cont blocks
get_cont :: Block CmmNode x C -> (Maybe (Label, ByteOff), ByteOff)
get_cont b =
case lastNode b of
CmmCall { cml_cont = Just l, .. }
-> (Just (l, cml_ret_args), cml_ret_off)
CmmForeignCall { .. }
-> (Just (succ, ret_args), ret_off)
_other -> (Nothing, 0)
-- -----------------------------------------------------------------------------
-- Updating the StackMap from middle nodes
-- Look for loads from stack slots, and update the StackMap. This is
-- purely for optimisation reasons, so that we can avoid saving a
-- variable back to a different stack slot if it is already on the
-- stack.
--
-- This happens a lot: for example when function arguments are passed
-- on the stack and need to be immediately saved across a call, we
-- want to just leave them where they are on the stack.
--
procMiddle :: BlockEnv StackMap -> CmmNode e x -> StackMap -> StackMap
procMiddle stackmaps node sm
= case node of
CmmAssign (CmmLocal r) (CmmLoad (CmmStackSlot area off) _)
-> sm { sm_regs = addToUFM (sm_regs sm) r (r,loc) }
where loc = getStackLoc area off stackmaps
CmmAssign (CmmLocal r) _other
-> sm { sm_regs = delFromUFM (sm_regs sm) r }
_other
-> sm
getStackLoc :: Area -> ByteOff -> BlockEnv StackMap -> StackLoc
getStackLoc Old n _ = n
getStackLoc (Young l) n stackmaps =
case mapLookup l stackmaps of
Nothing -> pprPanic "getStackLoc" (ppr l)
Just sm -> sm_sp sm - sm_args sm + n
-- -----------------------------------------------------------------------------
-- Handling stack allocation for a last node
-- We take a single last node and turn it into:
--
-- C1 (some statements)
-- Sp = Sp + N
-- C2 (some more statements)
-- call f() -- the actual last node
--
-- plus possibly some more blocks (we may have to add some fixup code
-- between the last node and the continuation).
--
-- C1: is the code for saving the variables across this last node onto
-- the stack, if the continuation is a call or jumps to a proc point.
--
-- C2: if the last node is a safe foreign call, we have to inject some
-- extra code that goes *after* the Sp adjustment.
handleLastNode
:: DynFlags -> ProcPointSet -> BlockEnv CmmLocalLive -> BlockEnv ByteOff
-> BlockEnv StackMap -> StackMap -> CmmTickScope
-> Block CmmNode O O
-> CmmNode O C
-> UniqSM
( [CmmNode O O] -- nodes to go *before* the Sp adjustment
, ByteOff -- amount to adjust Sp
, CmmNode O C -- new last node
, [CmmBlock] -- new blocks
, BlockEnv StackMap -- stackmaps for the continuations
)
handleLastNode dflags procpoints liveness cont_info stackmaps
stack0@StackMap { sm_sp = sp0 } tscp middle last
= case last of
-- At each return / tail call,
-- adjust Sp to point to the last argument pushed, which
-- is cml_args, after popping any other junk from the stack.
CmmCall{ cml_cont = Nothing, .. } -> do
let sp_off = sp0 - cml_args
return ([], sp_off, last, [], mapEmpty)
-- At each CmmCall with a continuation:
CmmCall{ cml_cont = Just cont_lbl, .. } ->
return $ lastCall cont_lbl cml_args cml_ret_args cml_ret_off
CmmForeignCall{ succ = cont_lbl, .. } -> do
return $ lastCall cont_lbl (wORD_SIZE dflags) ret_args ret_off
-- one word of args: the return address
CmmBranch {} -> handleBranches
CmmCondBranch {} -> handleBranches
CmmSwitch {} -> handleBranches
where
-- Calls and ForeignCalls are handled the same way:
lastCall :: BlockId -> ByteOff -> ByteOff -> ByteOff
-> ( [CmmNode O O]
, ByteOff
, CmmNode O C
, [CmmBlock]
, BlockEnv StackMap
)
lastCall lbl cml_args cml_ret_args cml_ret_off
= ( assignments
, spOffsetForCall sp0 cont_stack cml_args
, last
, [] -- no new blocks
, mapSingleton lbl cont_stack )
where
(assignments, cont_stack) = prepareStack lbl cml_ret_args cml_ret_off
prepareStack lbl cml_ret_args cml_ret_off
| Just cont_stack <- mapLookup lbl stackmaps
-- If we have already seen this continuation before, then
-- we just have to make the stack look the same:
= (fixupStack stack0 cont_stack, cont_stack)
-- Otherwise, we have to allocate the stack frame
| otherwise
= (save_assignments, new_cont_stack)
where
(new_cont_stack, save_assignments)
= setupStackFrame dflags lbl liveness cml_ret_off cml_ret_args stack0
-- For other last nodes (branches), if any of the targets is a
-- proc point, we have to set up the stack to match what the proc
-- point is expecting.
--
handleBranches :: UniqSM ( [CmmNode O O]
, ByteOff
, CmmNode O C
, [CmmBlock]
, BlockEnv StackMap )
handleBranches
-- Note [diamond proc point]
| Just l <- futureContinuation middle
, (nub $ filter (`setMember` procpoints) $ successors last) == [l]
= do
let cont_args = mapFindWithDefault 0 l cont_info
(assigs, cont_stack) = prepareStack l cont_args (sm_ret_off stack0)
out = mapFromList [ (l', cont_stack)
| l' <- successors last ]
return ( assigs
, spOffsetForCall sp0 cont_stack (wORD_SIZE dflags)
, last
, []
, out)
| otherwise = do
pps <- mapM handleBranch (successors last)
let lbl_map :: LabelMap Label
lbl_map = mapFromList [ (l,tmp) | (l,tmp,_,_) <- pps ]
fix_lbl l = mapFindWithDefault l l lbl_map
return ( []
, 0
, mapSuccessors fix_lbl last
, concat [ blk | (_,_,_,blk) <- pps ]
, mapFromList [ (l, sm) | (l,_,sm,_) <- pps ] )
-- For each successor of this block
handleBranch :: BlockId -> UniqSM (BlockId, BlockId, StackMap, [CmmBlock])
handleBranch l
-- (a) if the successor already has a stackmap, we need to
-- shuffle the current stack to make it look the same.
-- We have to insert a new block to make this happen.
| Just stack2 <- mapLookup l stackmaps
= do
let assigs = fixupStack stack0 stack2
(tmp_lbl, block) <- makeFixupBlock dflags sp0 l stack2 tscp assigs
return (l, tmp_lbl, stack2, block)
-- (b) if the successor is a proc point, save everything
-- on the stack.
| l `setMember` procpoints
= do
let cont_args = mapFindWithDefault 0 l cont_info
(stack2, assigs) =
setupStackFrame dflags l liveness (sm_ret_off stack0)
cont_args stack0
(tmp_lbl, block) <- makeFixupBlock dflags sp0 l stack2 tscp assigs
return (l, tmp_lbl, stack2, block)
-- (c) otherwise, the current StackMap is the StackMap for
-- the continuation. But we must remember to remove any
-- variables from the StackMap that are *not* live at
-- the destination, because this StackMap might be used
-- by fixupStack if this is a join point.
| otherwise = return (l, l, stack1, [])
where live = mapFindWithDefault (panic "handleBranch") l liveness
stack1 = stack0 { sm_regs = filterUFM is_live (sm_regs stack0) }
is_live (r,_) = r `elemRegSet` live
makeFixupBlock :: DynFlags -> ByteOff -> Label -> StackMap
-> CmmTickScope -> [CmmNode O O]
-> UniqSM (Label, [CmmBlock])
makeFixupBlock dflags sp0 l stack tscope assigs
| null assigs && sp0 == sm_sp stack = return (l, [])
| otherwise = do
tmp_lbl <- liftM mkBlockId $ getUniqueM
let sp_off = sp0 - sm_sp stack
block = blockJoin (CmmEntry tmp_lbl tscope)
(maybeAddSpAdj dflags sp_off (blockFromList assigs))
(CmmBranch l)
return (tmp_lbl, [block])
-- Sp is currently pointing to current_sp,
-- we want it to point to
-- (sm_sp cont_stack - sm_args cont_stack + args)
-- so the difference is
-- sp0 - (sm_sp cont_stack - sm_args cont_stack + args)
spOffsetForCall :: ByteOff -> StackMap -> ByteOff -> ByteOff
spOffsetForCall current_sp cont_stack args
= current_sp - (sm_sp cont_stack - sm_args cont_stack + args)
-- | create a sequence of assignments to establish the new StackMap,
-- given the old StackMap.
fixupStack :: StackMap -> StackMap -> [CmmNode O O]
fixupStack old_stack new_stack = concatMap move new_locs
where
old_map = sm_regs old_stack
new_locs = stackSlotRegs new_stack
move (r,n)
| Just (_,m) <- lookupUFM old_map r, n == m = []
| otherwise = [CmmStore (CmmStackSlot Old n)
(CmmReg (CmmLocal r))]
setupStackFrame
:: DynFlags
-> BlockId -- label of continuation
-> BlockEnv CmmLocalLive -- liveness
-> ByteOff -- updfr
-> ByteOff -- bytes of return values on stack
-> StackMap -- current StackMap
-> (StackMap, [CmmNode O O])
setupStackFrame dflags lbl liveness updfr_off ret_args stack0
= (cont_stack, assignments)
where
-- get the set of LocalRegs live in the continuation
live = mapFindWithDefault Set.empty lbl liveness
-- the stack from the base to updfr_off is off-limits.
-- our new stack frame contains:
-- * saved live variables
-- * the return address [young(C) + 8]
-- * the args for the call,
-- which are replaced by the return values at the return
-- point.
-- everything up to updfr_off is off-limits
-- stack1 contains updfr_off, plus everything we need to save
(stack1, assignments) = allocate dflags updfr_off live stack0
-- And the Sp at the continuation is:
-- sm_sp stack1 + ret_args
cont_stack = stack1{ sm_sp = sm_sp stack1 + ret_args
, sm_args = ret_args
, sm_ret_off = updfr_off
}
-- -----------------------------------------------------------------------------
-- Note [diamond proc point]
--
-- This special case looks for the pattern we get from a typical
-- tagged case expression:
--
-- Sp[young(L1)] = L1
-- if (R1 & 7) != 0 goto L1 else goto L2
-- L2:
-- call [R1] returns to L1
-- L1: live: {y}
-- x = R1
--
-- If we let the generic case handle this, we get
--
-- Sp[-16] = L1
-- if (R1 & 7) != 0 goto L1a else goto L2
-- L2:
-- Sp[-8] = y
-- Sp = Sp - 16
-- call [R1] returns to L1
-- L1a:
-- Sp[-8] = y
-- Sp = Sp - 16
-- goto L1
-- L1:
-- x = R1
--
-- The code for saving the live vars is duplicated in each branch, and
-- furthermore there is an extra jump in the fast path (assuming L1 is
-- a proc point, which it probably is if there is a heap check).
--
-- So to fix this we want to set up the stack frame before the
-- conditional jump. How do we know when to do this, and when it is
-- safe? The basic idea is, when we see the assignment
--
-- Sp[young(L)] = L
--
-- we know that
-- * we are definitely heading for L
-- * there can be no more reads from another stack area, because young(L)
-- overlaps with it.
--
-- We don't necessarily know that everything live at L is live now
-- (some might be assigned between here and the jump to L). So we
-- simplify and only do the optimisation when we see
--
-- (1) a block containing an assignment of a return address L
-- (2) ending in a branch where one (and only) continuation goes to L,
-- and no other continuations go to proc points.
--
-- then we allocate the stack frame for L at the end of the block,
-- before the branch.
--
-- We could generalise (2), but that would make it a bit more
-- complicated to handle, and this currently catches the common case.
futureContinuation :: Block CmmNode O O -> Maybe BlockId
futureContinuation middle = foldBlockNodesB f middle Nothing
where f :: CmmNode a b -> Maybe BlockId -> Maybe BlockId
f (CmmStore (CmmStackSlot (Young l) _) (CmmLit (CmmBlock _))) _
= Just l
f _ r = r
-- -----------------------------------------------------------------------------
-- Saving live registers
-- | Given a set of live registers and a StackMap, save all the registers
-- on the stack and return the new StackMap and the assignments to do
-- the saving.
--
allocate :: DynFlags -> ByteOff -> LocalRegSet -> StackMap
-> (StackMap, [CmmNode O O])
allocate dflags ret_off live stackmap@StackMap{ sm_sp = sp0
, sm_regs = regs0 }
=
-- we only have to save regs that are not already in a slot
let to_save = filter (not . (`elemUFM` regs0)) (Set.elems live)
regs1 = filterUFM (\(r,_) -> elemRegSet r live) regs0
in
-- make a map of the stack
let stack = reverse $ Array.elems $
accumArray (\_ x -> x) Empty (1, toWords dflags (max sp0 ret_off)) $
ret_words ++ live_words
where ret_words =
[ (x, Occupied)
| x <- [ 1 .. toWords dflags ret_off] ]
live_words =
[ (toWords dflags x, Occupied)
| (r,off) <- eltsUFM regs1,
let w = localRegBytes dflags r,
x <- [ off, off - wORD_SIZE dflags .. off - w + 1] ]
in
-- Pass over the stack: find slots to save all the new live variables,
-- choosing the oldest slots first (hence a foldr).
let
save slot ([], stack, n, assigs, regs) -- no more regs to save
= ([], slot:stack, plusW dflags n 1, assigs, regs)
save slot (to_save, stack, n, assigs, regs)
= case slot of
Occupied -> (to_save, Occupied:stack, plusW dflags n 1, assigs, regs)
Empty
| Just (stack', r, to_save') <-
select_save to_save (slot:stack)
-> let assig = CmmStore (CmmStackSlot Old n')
(CmmReg (CmmLocal r))
n' = plusW dflags n 1
in
(to_save', stack', n', assig : assigs, (r,(r,n')):regs)
| otherwise
-> (to_save, slot:stack, plusW dflags n 1, assigs, regs)
-- we should do better here: right now we'll fit the smallest first,
-- but it would make more sense to fit the biggest first.
select_save :: [LocalReg] -> [StackSlot]
-> Maybe ([StackSlot], LocalReg, [LocalReg])
select_save regs stack = go regs []
where go [] _no_fit = Nothing
go (r:rs) no_fit
| Just rest <- dropEmpty words stack
= Just (replicate words Occupied ++ rest, r, rs++no_fit)
| otherwise
= go rs (r:no_fit)
where words = localRegWords dflags r
-- fill in empty slots as much as possible
(still_to_save, save_stack, n, save_assigs, save_regs)
= foldr save (to_save, [], 0, [], []) stack
-- push any remaining live vars on the stack
(push_sp, push_assigs, push_regs)
= foldr push (n, [], []) still_to_save
where
push r (n, assigs, regs)
= (n', assig : assigs, (r,(r,n')) : regs)
where
n' = n + localRegBytes dflags r
assig = CmmStore (CmmStackSlot Old n')
(CmmReg (CmmLocal r))
trim_sp
| not (null push_regs) = push_sp
| otherwise
= plusW dflags n (- length (takeWhile isEmpty save_stack))
final_regs = regs1 `addListToUFM` push_regs
`addListToUFM` save_regs
in
-- XXX should be an assert
if ( n /= max sp0 ret_off ) then pprPanic "allocate" (ppr n <+> ppr sp0 <+> ppr ret_off) else
if (trim_sp .&. (wORD_SIZE dflags - 1)) /= 0 then pprPanic "allocate2" (ppr trim_sp <+> ppr final_regs <+> ppr push_sp) else
( stackmap { sm_regs = final_regs , sm_sp = trim_sp }
, push_assigs ++ save_assigs )
-- -----------------------------------------------------------------------------
-- Manifesting Sp
-- | Manifest Sp: turn all the CmmStackSlots into CmmLoads from Sp. The
-- block looks like this:
--
-- middle_pre -- the middle nodes
-- Sp = Sp + sp_off -- Sp adjustment goes here
-- last -- the last node
--
-- And we have some extra blocks too (that don't contain Sp adjustments)
--
-- The adjustment for middle_pre will be different from that for
-- middle_post, because the Sp adjustment intervenes.
--
manifestSp
:: DynFlags
-> BlockEnv StackMap -- StackMaps for other blocks
-> StackMap -- StackMap for this block
-> ByteOff -- Sp on entry to the block
-> ByteOff -- SpHigh
-> CmmNode C O -- first node
-> [CmmNode O O] -- middle
-> ByteOff -- sp_off
-> CmmNode O C -- last node
-> [CmmBlock] -- new blocks
-> [CmmBlock] -- final blocks with Sp manifest
manifestSp dflags stackmaps stack0 sp0 sp_high
first middle_pre sp_off last fixup_blocks
= final_block : fixup_blocks'
where
area_off = getAreaOff stackmaps
adj_pre_sp, adj_post_sp :: CmmNode e x -> CmmNode e x
adj_pre_sp = mapExpDeep (areaToSp dflags sp0 sp_high area_off)
adj_post_sp = mapExpDeep (areaToSp dflags (sp0 - sp_off) sp_high area_off)
-- Add unwind pseudo-instructions to document Sp level for debugging
add_unwind_info block
| debugLevel dflags > 0 = CmmUnwind Sp sp_unwind : block
| otherwise = block
sp_unwind = CmmRegOff (CmmGlobal Sp) (sp0 - wORD_SIZE dflags)
final_middle = maybeAddSpAdj dflags sp_off $
blockFromList $
add_unwind_info $
map adj_pre_sp $
elimStackStores stack0 stackmaps area_off $
middle_pre
final_last = optStackCheck (adj_post_sp last)
final_block = blockJoin first final_middle final_last
fixup_blocks' = map (mapBlock3' (id, adj_post_sp, id)) fixup_blocks
getAreaOff :: BlockEnv StackMap -> (Area -> StackLoc)
getAreaOff _ Old = 0
getAreaOff stackmaps (Young l) =
case mapLookup l stackmaps of
Just sm -> sm_sp sm - sm_args sm
Nothing -> pprPanic "getAreaOff" (ppr l)
maybeAddSpAdj :: DynFlags -> ByteOff -> Block CmmNode O O -> Block CmmNode O O
maybeAddSpAdj _ 0 block = block
maybeAddSpAdj dflags sp_off block
= block `blockSnoc` CmmAssign spReg (cmmOffset dflags (CmmReg spReg) sp_off)
{-
Sp(L) is the Sp offset on entry to block L relative to the base of the
OLD area.
SpArgs(L) is the size of the young area for L, i.e. the number of
arguments.
- in block L, each reference to [old + N] turns into
[Sp + Sp(L) - N]
- in block L, each reference to [young(L') + N] turns into
[Sp + Sp(L) - Sp(L') + SpArgs(L') - N]
- be careful with the last node of each block: Sp has already been adjusted
to be Sp + Sp(L) - Sp(L')
-}
areaToSp :: DynFlags -> ByteOff -> ByteOff -> (Area -> StackLoc) -> CmmExpr -> CmmExpr
areaToSp dflags sp_old _sp_hwm area_off (CmmStackSlot area n)
= cmmOffset dflags (CmmReg spReg) (sp_old - area_off area - n)
-- Replace (CmmStackSlot area n) with an offset from Sp
areaToSp dflags _ sp_hwm _ (CmmLit CmmHighStackMark)
= mkIntExpr dflags sp_hwm
-- Replace CmmHighStackMark with the number of bytes of stack used,
-- the sp_hwm. See Note [Stack usage] in StgCmmHeap
areaToSp dflags _ _ _ (CmmMachOp (MO_U_Lt _) args)
| falseStackCheck args
= zeroExpr dflags
areaToSp dflags _ _ _ (CmmMachOp (MO_U_Ge _) args)
| falseStackCheck args
= mkIntExpr dflags 1
-- Replace a stack-overflow test that cannot fail with a no-op
-- See Note [Always false stack check]
areaToSp _ _ _ _ other = other
-- | Determine whether a stack check cannot fail.
falseStackCheck :: [CmmExpr] -> Bool
falseStackCheck [ CmmMachOp (MO_Sub _)
[ CmmRegOff (CmmGlobal Sp) x_off
, CmmLit (CmmInt y_lit _)]
, CmmReg (CmmGlobal SpLim)]
= fromIntegral x_off >= y_lit
falseStackCheck _ = False
-- Note [Always false stack check]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- We can optimise stack checks of the form
--
-- if ((Sp + x) - y < SpLim) then .. else ..
--
-- where are non-negative integer byte offsets. Since we know that
-- SpLim <= Sp (remember the stack grows downwards), this test must
-- yield False if (x >= y), so we can rewrite the comparison to False.
-- A subsequent sinking pass will later drop the dead code.
-- Optimising this away depends on knowing that SpLim <= Sp, so it is
-- really the job of the stack layout algorithm, hence we do it now.
--
-- The control flow optimiser may negate a conditional to increase
-- the likelihood of a fallthrough if the branch is not taken. But
-- not every conditional is inverted as the control flow optimiser
-- places some requirements on the predecessors of both branch targets.
-- So we better look for the inverted comparison too.
optStackCheck :: CmmNode O C -> CmmNode O C
optStackCheck n = -- Note [Always false stack check]
case n of
CmmCondBranch (CmmLit (CmmInt 0 _)) _true false _ -> CmmBranch false
CmmCondBranch (CmmLit (CmmInt _ _)) true _false _ -> CmmBranch true
other -> other
-- -----------------------------------------------------------------------------
-- | Eliminate stores of the form
--
-- Sp[area+n] = r
--
-- when we know that r is already in the same slot as Sp[area+n]. We
-- could do this in a later optimisation pass, but that would involve
-- a separate analysis and we already have the information to hand
-- here. It helps clean up some extra stack stores in common cases.
--
-- Note that we may have to modify the StackMap as we walk through the
-- code using procMiddle, since an assignment to a variable in the
-- StackMap will invalidate its mapping there.
--
elimStackStores :: StackMap
-> BlockEnv StackMap
-> (Area -> ByteOff)
-> [CmmNode O O]
-> [CmmNode O O]
elimStackStores stackmap stackmaps area_off nodes
= go stackmap nodes
where
go _stackmap [] = []
go stackmap (n:ns)
= case n of
CmmStore (CmmStackSlot area m) (CmmReg (CmmLocal r))
| Just (_,off) <- lookupUFM (sm_regs stackmap) r
, area_off area + m == off
-> go stackmap ns
_otherwise
-> n : go (procMiddle stackmaps n stackmap) ns
-- -----------------------------------------------------------------------------
-- Update info tables to include stack liveness
setInfoTableStackMap :: DynFlags -> BlockEnv StackMap -> CmmDecl -> CmmDecl
setInfoTableStackMap dflags stackmaps (CmmProc top_info@TopInfo{..} l v g)
= CmmProc top_info{ info_tbls = mapMapWithKey fix_info info_tbls } l v g
where
fix_info lbl info_tbl@CmmInfoTable{ cit_rep = StackRep _ } =
info_tbl { cit_rep = StackRep (get_liveness lbl) }
fix_info _ other = other
get_liveness :: BlockId -> Liveness
get_liveness lbl
= case mapLookup lbl stackmaps of
Nothing -> pprPanic "setInfoTableStackMap" (ppr lbl <+> ppr info_tbls)
Just sm -> stackMapToLiveness dflags sm
setInfoTableStackMap _ _ d = d
stackMapToLiveness :: DynFlags -> StackMap -> Liveness
stackMapToLiveness dflags StackMap{..} =
reverse $ Array.elems $
accumArray (\_ x -> x) True (toWords dflags sm_ret_off + 1,
toWords dflags (sm_sp - sm_args)) live_words
where
live_words = [ (toWords dflags off, False)
| (r,off) <- eltsUFM sm_regs, isGcPtrType (localRegType r) ]
-- -----------------------------------------------------------------------------
-- Lowering safe foreign calls
{-
Note [Lower safe foreign calls]
We start with
Sp[young(L1)] = L1
,-----------------------
| r1 = foo(x,y,z) returns to L1
'-----------------------
L1:
R1 = r1 -- copyIn, inserted by mkSafeCall
...
the stack layout algorithm will arrange to save and reload everything
live across the call. Our job now is to expand the call so we get
Sp[young(L1)] = L1
,-----------------------
| SAVE_THREAD_STATE()
| token = suspendThread(BaseReg, interruptible)
| r = foo(x,y,z)
| BaseReg = resumeThread(token)
| LOAD_THREAD_STATE()
| R1 = r -- copyOut
| jump Sp[0]
'-----------------------
L1:
r = R1 -- copyIn, inserted by mkSafeCall
...
Note the copyOut, which saves the results in the places that L1 is
expecting them (see Note {safe foreign call convention]). Note also
that safe foreign call is replace by an unsafe one in the Cmm graph.
-}
lowerSafeForeignCall :: DynFlags -> CmmBlock -> UniqSM CmmBlock
lowerSafeForeignCall dflags block
| (entry@(CmmEntry _ tscp), middle, CmmForeignCall { .. }) <- blockSplit block
= do
-- Both 'id' and 'new_base' are KindNonPtr because they're
-- RTS-only objects and are not subject to garbage collection
id <- newTemp (bWord dflags)
new_base <- newTemp (cmmRegType dflags (CmmGlobal BaseReg))
let (caller_save, caller_load) = callerSaveVolatileRegs dflags
save_state_code <- saveThreadState dflags
load_state_code <- loadThreadState dflags
let suspend = save_state_code <*>
caller_save <*>
mkMiddle (callSuspendThread dflags id intrbl)
midCall = mkUnsafeCall tgt res args
resume = mkMiddle (callResumeThread new_base id) <*>
-- Assign the result to BaseReg: we
-- might now have a different Capability!
mkAssign (CmmGlobal BaseReg) (CmmReg (CmmLocal new_base)) <*>
caller_load <*>
load_state_code
(_, regs, copyout) =
copyOutOflow dflags NativeReturn Jump (Young succ)
(map (CmmReg . CmmLocal) res)
ret_off []
-- NB. after resumeThread returns, the top-of-stack probably contains
-- the stack frame for succ, but it might not: if the current thread
-- received an exception during the call, then the stack might be
-- different. Hence we continue by jumping to the top stack frame,
-- not by jumping to succ.
jump = CmmCall { cml_target = entryCode dflags $
CmmLoad (CmmReg spReg) (bWord dflags)
, cml_cont = Just succ
, cml_args_regs = regs
, cml_args = widthInBytes (wordWidth dflags)
, cml_ret_args = ret_args
, cml_ret_off = ret_off }
graph' <- lgraphOfAGraph ( suspend <*>
midCall <*>
resume <*>
copyout <*>
mkLast jump, tscp)
case toBlockList graph' of
[one] -> let (_, middle', last) = blockSplit one
in return (blockJoin entry (middle `blockAppend` middle') last)
_ -> panic "lowerSafeForeignCall0"
-- Block doesn't end in a safe foreign call:
| otherwise = return block
foreignLbl :: FastString -> CmmExpr
foreignLbl name = CmmLit (CmmLabel (mkForeignLabel name Nothing ForeignLabelInExternalPackage IsFunction))
callSuspendThread :: DynFlags -> LocalReg -> Bool -> CmmNode O O
callSuspendThread dflags id intrbl =
CmmUnsafeForeignCall
(ForeignTarget (foreignLbl (fsLit "suspendThread"))
(ForeignConvention CCallConv [AddrHint, NoHint] [AddrHint] CmmMayReturn))
[id] [CmmReg (CmmGlobal BaseReg), mkIntExpr dflags (fromEnum intrbl)]
callResumeThread :: LocalReg -> LocalReg -> CmmNode O O
callResumeThread new_base id =
CmmUnsafeForeignCall
(ForeignTarget (foreignLbl (fsLit "resumeThread"))
(ForeignConvention CCallConv [AddrHint] [AddrHint] CmmMayReturn))
[new_base] [CmmReg (CmmLocal id)]
-- -----------------------------------------------------------------------------
plusW :: DynFlags -> ByteOff -> WordOff -> ByteOff
plusW dflags b w = b + w * wORD_SIZE dflags
data StackSlot = Occupied | Empty
-- Occupied: a return address or part of an update frame
instance Outputable StackSlot where
ppr Occupied = text "XXX"
ppr Empty = text "---"
dropEmpty :: WordOff -> [StackSlot] -> Maybe [StackSlot]
dropEmpty 0 ss = Just ss
dropEmpty n (Empty : ss) = dropEmpty (n-1) ss
dropEmpty _ _ = Nothing
isEmpty :: StackSlot -> Bool
isEmpty Empty = True
isEmpty _ = False
localRegBytes :: DynFlags -> LocalReg -> ByteOff
localRegBytes dflags r
= roundUpToWords dflags (widthInBytes (typeWidth (localRegType r)))
localRegWords :: DynFlags -> LocalReg -> WordOff
localRegWords dflags = toWords dflags . localRegBytes dflags
toWords :: DynFlags -> ByteOff -> WordOff
toWords dflags x = x `quot` wORD_SIZE dflags
insertReloads :: StackMap -> [CmmNode O O]
insertReloads stackmap =
[ CmmAssign (CmmLocal r) (CmmLoad (CmmStackSlot Old sp)
(localRegType r))
| (r,sp) <- stackSlotRegs stackmap
]
stackSlotRegs :: StackMap -> [(LocalReg, StackLoc)]
stackSlotRegs sm = eltsUFM (sm_regs sm)
|
tjakway/ghcjvm
|
compiler/cmm/CmmLayoutStack.hs
|
Haskell
|
bsd-3-clause
| 42,312
|
module Main (main) where
main :: IO ()
main = return ()
|
sonyandy/wart
|
tools/wartc.hs
|
Haskell
|
bsd-3-clause
| 57
|
{-
(c) The University of Glasgow, 2004-2006
Module
~~~~~~~~~~
Simply the name of a module, represented as a FastString.
These are Uniquable, hence we can build Maps with Modules as
the keys.
-}
{-# LANGUAGE DeriveDataTypeable #-}
module Module
(
-- * The ModuleName type
ModuleName,
pprModuleName,
moduleNameFS,
moduleNameString,
moduleNameSlashes, moduleNameColons,
mkModuleName,
mkModuleNameFS,
stableModuleNameCmp,
-- * The PackageKey type
PackageKey,
fsToPackageKey,
packageKeyFS,
stringToPackageKey,
packageKeyString,
stablePackageKeyCmp,
-- * Wired-in PackageKeys
-- $wired_in_packages
primPackageKey,
integerPackageKey,
basePackageKey,
rtsPackageKey,
thPackageKey,
dphSeqPackageKey,
dphParPackageKey,
mainPackageKey,
thisGhcPackageKey,
interactivePackageKey, isInteractiveModule,
wiredInPackageKeys,
-- * The Module type
Module(Module),
modulePackageKey, moduleName,
pprModule,
mkModule,
stableModuleCmp,
HasModule(..),
ContainsModule(..),
-- * The ModuleLocation type
ModLocation(..),
addBootSuffix, addBootSuffix_maybe, addBootSuffixLocn,
-- * Module mappings
ModuleEnv,
elemModuleEnv, extendModuleEnv, extendModuleEnvList,
extendModuleEnvList_C, plusModuleEnv_C,
delModuleEnvList, delModuleEnv, plusModuleEnv, lookupModuleEnv,
lookupWithDefaultModuleEnv, mapModuleEnv, mkModuleEnv, emptyModuleEnv,
moduleEnvKeys, moduleEnvElts, moduleEnvToList,
unitModuleEnv, isEmptyModuleEnv,
foldModuleEnv, extendModuleEnvWith, filterModuleEnv,
-- * ModuleName mappings
ModuleNameEnv,
-- * Sets of Modules
ModuleSet,
emptyModuleSet, mkModuleSet, moduleSetElts, extendModuleSet, elemModuleSet
) where
import Config
import Outputable
import Unique
import UniqFM
import FastString
import Binary
import Util
import {-# SOURCE #-} Packages
import GHC.PackageDb (BinaryStringRep(..))
import Data.Data
import Data.Map (Map)
import qualified Data.Map as Map
import qualified FiniteMap as Map
import System.FilePath
{-
************************************************************************
* *
\subsection{Module locations}
* *
************************************************************************
-}
-- | Where a module lives on the file system: the actual locations
-- of the .hs, .hi and .o files, if we have them
data ModLocation
= ModLocation {
ml_hs_file :: Maybe FilePath,
-- The source file, if we have one. Package modules
-- probably don't have source files.
ml_hi_file :: FilePath,
-- Where the .hi file is, whether or not it exists
-- yet. Always of form foo.hi, even if there is an
-- hi-boot file (we add the -boot suffix later)
ml_obj_file :: FilePath
-- Where the .o file is, whether or not it exists yet.
-- (might not exist either because the module hasn't
-- been compiled yet, or because it is part of a
-- package with a .a file)
} deriving Show
instance Outputable ModLocation where
ppr = text . show
{-
For a module in another package, the hs_file and obj_file
components of ModLocation are undefined.
The locations specified by a ModLocation may or may not
correspond to actual files yet: for example, even if the object
file doesn't exist, the ModLocation still contains the path to
where the object file will reside if/when it is created.
-}
addBootSuffix :: FilePath -> FilePath
-- ^ Add the @-boot@ suffix to .hs, .hi and .o files
addBootSuffix path = path ++ "-boot"
addBootSuffix_maybe :: Bool -> FilePath -> FilePath
-- ^ Add the @-boot@ suffix if the @Bool@ argument is @True@
addBootSuffix_maybe is_boot path
| is_boot = addBootSuffix path
| otherwise = path
addBootSuffixLocn :: ModLocation -> ModLocation
-- ^ Add the @-boot@ suffix to all file paths associated with the module
addBootSuffixLocn locn
= locn { ml_hs_file = fmap addBootSuffix (ml_hs_file locn)
, ml_hi_file = addBootSuffix (ml_hi_file locn)
, ml_obj_file = addBootSuffix (ml_obj_file locn) }
{-
************************************************************************
* *
\subsection{The name of a module}
* *
************************************************************************
-}
-- | A ModuleName is essentially a simple string, e.g. @Data.List@.
newtype ModuleName = ModuleName FastString
deriving Typeable
instance Uniquable ModuleName where
getUnique (ModuleName nm) = getUnique nm
instance Eq ModuleName where
nm1 == nm2 = getUnique nm1 == getUnique nm2
-- Warning: gives an ordering relation based on the uniques of the
-- FastStrings which are the (encoded) module names. This is _not_
-- a lexicographical ordering.
instance Ord ModuleName where
nm1 `compare` nm2 = getUnique nm1 `compare` getUnique nm2
instance Outputable ModuleName where
ppr = pprModuleName
instance Binary ModuleName where
put_ bh (ModuleName fs) = put_ bh fs
get bh = do fs <- get bh; return (ModuleName fs)
instance BinaryStringRep ModuleName where
fromStringRep = mkModuleNameFS . mkFastStringByteString
toStringRep = fastStringToByteString . moduleNameFS
instance Data ModuleName where
-- don't traverse?
toConstr _ = abstractConstr "ModuleName"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "ModuleName"
stableModuleNameCmp :: ModuleName -> ModuleName -> Ordering
-- ^ Compares module names lexically, rather than by their 'Unique's
stableModuleNameCmp n1 n2 = moduleNameFS n1 `compare` moduleNameFS n2
pprModuleName :: ModuleName -> SDoc
pprModuleName (ModuleName nm) =
getPprStyle $ \ sty ->
if codeStyle sty
then ztext (zEncodeFS nm)
else ftext nm
moduleNameFS :: ModuleName -> FastString
moduleNameFS (ModuleName mod) = mod
moduleNameString :: ModuleName -> String
moduleNameString (ModuleName mod) = unpackFS mod
mkModuleName :: String -> ModuleName
mkModuleName s = ModuleName (mkFastString s)
mkModuleNameFS :: FastString -> ModuleName
mkModuleNameFS s = ModuleName s
-- |Returns the string version of the module name, with dots replaced by slashes.
--
moduleNameSlashes :: ModuleName -> String
moduleNameSlashes = dots_to_slashes . moduleNameString
where dots_to_slashes = map (\c -> if c == '.' then pathSeparator else c)
-- |Returns the string version of the module name, with dots replaced by underscores.
--
moduleNameColons :: ModuleName -> String
moduleNameColons = dots_to_colons . moduleNameString
where dots_to_colons = map (\c -> if c == '.' then ':' else c)
{-
************************************************************************
* *
\subsection{A fully qualified module}
* *
************************************************************************
-}
-- | A Module is a pair of a 'PackageKey' and a 'ModuleName'.
data Module = Module {
modulePackageKey :: !PackageKey, -- pkg-1.0
moduleName :: !ModuleName -- A.B.C
}
deriving (Eq, Ord, Typeable)
instance Uniquable Module where
getUnique (Module p n) = getUnique (packageKeyFS p `appendFS` moduleNameFS n)
instance Outputable Module where
ppr = pprModule
instance Binary Module where
put_ bh (Module p n) = put_ bh p >> put_ bh n
get bh = do p <- get bh; n <- get bh; return (Module p n)
instance Data Module where
-- don't traverse?
toConstr _ = abstractConstr "Module"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "Module"
-- | This gives a stable ordering, as opposed to the Ord instance which
-- gives an ordering based on the 'Unique's of the components, which may
-- not be stable from run to run of the compiler.
stableModuleCmp :: Module -> Module -> Ordering
stableModuleCmp (Module p1 n1) (Module p2 n2)
= (p1 `stablePackageKeyCmp` p2) `thenCmp`
(n1 `stableModuleNameCmp` n2)
mkModule :: PackageKey -> ModuleName -> Module
mkModule = Module
pprModule :: Module -> SDoc
pprModule mod@(Module p n) =
pprPackagePrefix p mod <> pprModuleName n
pprPackagePrefix :: PackageKey -> Module -> SDoc
pprPackagePrefix p mod = getPprStyle doc
where
doc sty
| codeStyle sty =
if p == mainPackageKey
then empty -- never qualify the main package in code
else ztext (zEncodeFS (packageKeyFS p)) <> char '_'
| qualModule sty mod = ppr (modulePackageKey mod) <> char ':'
-- the PrintUnqualified tells us which modules have to
-- be qualified with package names
| otherwise = empty
class ContainsModule t where
extractModule :: t -> Module
class HasModule m where
getModule :: m Module
{-
************************************************************************
* *
\subsection{PackageKey}
* *
************************************************************************
-}
-- | A string which uniquely identifies a package. For wired-in packages,
-- it is just the package name, but for user compiled packages, it is a hash.
-- ToDo: when the key is a hash, we can do more clever things than store
-- the hex representation and hash-cons those strings.
newtype PackageKey = PId FastString deriving( Eq, Typeable )
-- here to avoid module loops with PackageConfig
instance Uniquable PackageKey where
getUnique pid = getUnique (packageKeyFS pid)
-- Note: *not* a stable lexicographic ordering, a faster unique-based
-- ordering.
instance Ord PackageKey where
nm1 `compare` nm2 = getUnique nm1 `compare` getUnique nm2
instance Data PackageKey where
-- don't traverse?
toConstr _ = abstractConstr "PackageKey"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "PackageKey"
stablePackageKeyCmp :: PackageKey -> PackageKey -> Ordering
-- ^ Compares package ids lexically, rather than by their 'Unique's
stablePackageKeyCmp p1 p2 = packageKeyFS p1 `compare` packageKeyFS p2
instance Outputable PackageKey where
ppr pk = getPprStyle $ \sty -> sdocWithDynFlags $ \dflags ->
text (packageKeyPackageIdString dflags pk)
-- Don't bother qualifying if it's wired in!
<> (if qualPackage sty pk && not (pk `elem` wiredInPackageKeys)
then char '@' <> ftext (packageKeyFS pk)
else empty)
instance Binary PackageKey where
put_ bh pid = put_ bh (packageKeyFS pid)
get bh = do { fs <- get bh; return (fsToPackageKey fs) }
instance BinaryStringRep PackageKey where
fromStringRep = fsToPackageKey . mkFastStringByteString
toStringRep = fastStringToByteString . packageKeyFS
fsToPackageKey :: FastString -> PackageKey
fsToPackageKey = PId
packageKeyFS :: PackageKey -> FastString
packageKeyFS (PId fs) = fs
stringToPackageKey :: String -> PackageKey
stringToPackageKey = fsToPackageKey . mkFastString
packageKeyString :: PackageKey -> String
packageKeyString = unpackFS . packageKeyFS
-- -----------------------------------------------------------------------------
-- $wired_in_packages
-- Certain packages are known to the compiler, in that we know about certain
-- entities that reside in these packages, and the compiler needs to
-- declare static Modules and Names that refer to these packages. Hence
-- the wired-in packages can't include version numbers, since we don't want
-- to bake the version numbers of these packages into GHC.
--
-- So here's the plan. Wired-in packages are still versioned as
-- normal in the packages database, and you can still have multiple
-- versions of them installed. However, for each invocation of GHC,
-- only a single instance of each wired-in package will be recognised
-- (the desired one is selected via @-package@\/@-hide-package@), and GHC
-- will use the unversioned 'PackageKey' below when referring to it,
-- including in .hi files and object file symbols. Unselected
-- versions of wired-in packages will be ignored, as will any other
-- package that depends directly or indirectly on it (much as if you
-- had used @-ignore-package@).
-- Make sure you change 'Packages.findWiredInPackages' if you add an entry here
integerPackageKey, primPackageKey,
basePackageKey, rtsPackageKey,
thPackageKey, dphSeqPackageKey, dphParPackageKey,
mainPackageKey, thisGhcPackageKey, interactivePackageKey :: PackageKey
primPackageKey = fsToPackageKey (fsLit "ghc-prim")
integerPackageKey = fsToPackageKey (fsLit n)
where
n = case cIntegerLibraryType of
IntegerGMP -> "integer-gmp"
IntegerGMP2 -> "integer-gmp"
IntegerSimple -> "integer-simple"
basePackageKey = fsToPackageKey (fsLit "base")
rtsPackageKey = fsToPackageKey (fsLit "rts")
thPackageKey = fsToPackageKey (fsLit "template-haskell")
dphSeqPackageKey = fsToPackageKey (fsLit "dph-seq")
dphParPackageKey = fsToPackageKey (fsLit "dph-par")
thisGhcPackageKey = fsToPackageKey (fsLit "ghc")
interactivePackageKey = fsToPackageKey (fsLit "interactive")
-- | This is the package Id for the current program. It is the default
-- package Id if you don't specify a package name. We don't add this prefix
-- to symbol names, since there can be only one main package per program.
mainPackageKey = fsToPackageKey (fsLit "main")
isInteractiveModule :: Module -> Bool
isInteractiveModule mod = modulePackageKey mod == interactivePackageKey
wiredInPackageKeys :: [PackageKey]
wiredInPackageKeys = [ primPackageKey,
integerPackageKey,
basePackageKey,
rtsPackageKey,
thPackageKey,
thisGhcPackageKey,
dphSeqPackageKey,
dphParPackageKey ]
{-
************************************************************************
* *
\subsection{@ModuleEnv@s}
* *
************************************************************************
-}
-- | A map keyed off of 'Module's
newtype ModuleEnv elt = ModuleEnv (Map Module elt)
filterModuleEnv :: (Module -> a -> Bool) -> ModuleEnv a -> ModuleEnv a
filterModuleEnv f (ModuleEnv e) = ModuleEnv (Map.filterWithKey f e)
elemModuleEnv :: Module -> ModuleEnv a -> Bool
elemModuleEnv m (ModuleEnv e) = Map.member m e
extendModuleEnv :: ModuleEnv a -> Module -> a -> ModuleEnv a
extendModuleEnv (ModuleEnv e) m x = ModuleEnv (Map.insert m x e)
extendModuleEnvWith :: (a -> a -> a) -> ModuleEnv a -> Module -> a -> ModuleEnv a
extendModuleEnvWith f (ModuleEnv e) m x = ModuleEnv (Map.insertWith f m x e)
extendModuleEnvList :: ModuleEnv a -> [(Module, a)] -> ModuleEnv a
extendModuleEnvList (ModuleEnv e) xs = ModuleEnv (Map.insertList xs e)
extendModuleEnvList_C :: (a -> a -> a) -> ModuleEnv a -> [(Module, a)]
-> ModuleEnv a
extendModuleEnvList_C f (ModuleEnv e) xs = ModuleEnv (Map.insertListWith f xs e)
plusModuleEnv_C :: (a -> a -> a) -> ModuleEnv a -> ModuleEnv a -> ModuleEnv a
plusModuleEnv_C f (ModuleEnv e1) (ModuleEnv e2) = ModuleEnv (Map.unionWith f e1 e2)
delModuleEnvList :: ModuleEnv a -> [Module] -> ModuleEnv a
delModuleEnvList (ModuleEnv e) ms = ModuleEnv (Map.deleteList ms e)
delModuleEnv :: ModuleEnv a -> Module -> ModuleEnv a
delModuleEnv (ModuleEnv e) m = ModuleEnv (Map.delete m e)
plusModuleEnv :: ModuleEnv a -> ModuleEnv a -> ModuleEnv a
plusModuleEnv (ModuleEnv e1) (ModuleEnv e2) = ModuleEnv (Map.union e1 e2)
lookupModuleEnv :: ModuleEnv a -> Module -> Maybe a
lookupModuleEnv (ModuleEnv e) m = Map.lookup m e
lookupWithDefaultModuleEnv :: ModuleEnv a -> a -> Module -> a
lookupWithDefaultModuleEnv (ModuleEnv e) x m = Map.findWithDefault x m e
mapModuleEnv :: (a -> b) -> ModuleEnv a -> ModuleEnv b
mapModuleEnv f (ModuleEnv e) = ModuleEnv (Map.mapWithKey (\_ v -> f v) e)
mkModuleEnv :: [(Module, a)] -> ModuleEnv a
mkModuleEnv xs = ModuleEnv (Map.fromList xs)
emptyModuleEnv :: ModuleEnv a
emptyModuleEnv = ModuleEnv Map.empty
moduleEnvKeys :: ModuleEnv a -> [Module]
moduleEnvKeys (ModuleEnv e) = Map.keys e
moduleEnvElts :: ModuleEnv a -> [a]
moduleEnvElts (ModuleEnv e) = Map.elems e
moduleEnvToList :: ModuleEnv a -> [(Module, a)]
moduleEnvToList (ModuleEnv e) = Map.toList e
unitModuleEnv :: Module -> a -> ModuleEnv a
unitModuleEnv m x = ModuleEnv (Map.singleton m x)
isEmptyModuleEnv :: ModuleEnv a -> Bool
isEmptyModuleEnv (ModuleEnv e) = Map.null e
foldModuleEnv :: (a -> b -> b) -> b -> ModuleEnv a -> b
foldModuleEnv f x (ModuleEnv e) = Map.foldRightWithKey (\_ v -> f v) x e
-- | A set of 'Module's
type ModuleSet = Map Module ()
mkModuleSet :: [Module] -> ModuleSet
extendModuleSet :: ModuleSet -> Module -> ModuleSet
emptyModuleSet :: ModuleSet
moduleSetElts :: ModuleSet -> [Module]
elemModuleSet :: Module -> ModuleSet -> Bool
emptyModuleSet = Map.empty
mkModuleSet ms = Map.fromList [(m,()) | m <- ms ]
extendModuleSet s m = Map.insert m () s
moduleSetElts = Map.keys
elemModuleSet = Map.member
{-
A ModuleName has a Unique, so we can build mappings of these using
UniqFM.
-}
-- | A map keyed off of 'ModuleName's (actually, their 'Unique's)
type ModuleNameEnv elt = UniqFM elt
|
green-haskell/ghc
|
compiler/basicTypes/Module.hs
|
Haskell
|
bsd-3-clause
| 18,016
|
{-# LANGUAGE TemplateHaskell, TypeFamilies, DeriveDataTypeable, NamedFieldPuns #-}
module Distribution.Server.Features.TarIndexCache.State (
TarIndexCache(..)
, initialTarIndexCache
, GetTarIndexCache(GetTarIndexCache)
, ReplaceTarIndexCache(ReplaceTarIndexCache)
, FindTarIndex(FindTarIndex)
, SetTarIndex(SetTarIndex)
) where
-- TODO: use strict map? (Can we rely on containers >= 0.5?)
import Data.Typeable (Typeable)
import Control.Monad.Reader (ask, asks)
import Control.Monad.State (put, modify)
import Data.Map (Map)
import qualified Data.Map as Map
import Control.Applicative ((<$>))
import Data.Acid (Query, Update, makeAcidic)
import Data.SafeCopy (base, deriveSafeCopy)
import Distribution.Server.Framework.BlobStorage
import Distribution.Server.Framework.MemSize
data TarIndexCache = TarIndexCache {
tarIndexCacheMap :: Map BlobId BlobId
}
deriving (Eq, Show, Typeable)
$(deriveSafeCopy 0 'base ''TarIndexCache)
instance MemSize TarIndexCache where
memSize st = 2 + memSize (tarIndexCacheMap st)
initialTarIndexCache :: TarIndexCache
initialTarIndexCache = TarIndexCache (Map.empty)
getTarIndexCache :: Query TarIndexCache TarIndexCache
getTarIndexCache = ask
replaceTarIndexCache :: TarIndexCache -> Update TarIndexCache ()
replaceTarIndexCache = put
getTarIndexCacheMap :: Query TarIndexCache (Map BlobId BlobId)
getTarIndexCacheMap = asks tarIndexCacheMap
modifyTarIndexCacheMap :: (Map BlobId BlobId -> Map BlobId BlobId)
-> Update TarIndexCache ()
modifyTarIndexCacheMap f = modify $ \st@TarIndexCache{tarIndexCacheMap} ->
st { tarIndexCacheMap = f tarIndexCacheMap }
findTarIndex :: BlobId -> Query TarIndexCache (Maybe BlobId)
findTarIndex blobId = Map.lookup blobId <$> getTarIndexCacheMap
setTarIndex :: BlobId -> BlobId -> Update TarIndexCache ()
setTarIndex tar index = modifyTarIndexCacheMap (Map.insert tar index)
makeAcidic ''TarIndexCache [
'getTarIndexCache
, 'replaceTarIndexCache
, 'findTarIndex
, 'setTarIndex
]
|
ocharles/hackage-server
|
Distribution/Server/Features/TarIndexCache/State.hs
|
Haskell
|
bsd-3-clause
| 2,048
|
{-# LANGUAGE QuasiQuotes, TypeFamilies, TemplateHaskell #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ViewPatterns #-}
module Yesod.Auth.Routes where
import Yesod.Core
import Data.Text (Text)
data Auth = Auth
mkYesodSubData "Auth" [parseRoutes|
/check CheckR GET
/login LoginR GET
/logout LogoutR GET POST
/page/#Text/*Texts PluginR
|]
|
pikajude/yesod
|
yesod-auth/Yesod/Auth/Routes.hs
|
Haskell
|
mit
| 582
|
{-# LANGUAGE OverloadedStrings #-}
module System.Logging.Facade.Journald.Internal where
import Data.HashMap.Strict
import Data.Monoid
import Data.String
import qualified Data.Text.Encoding as Text
import System.Logging.Facade.Types
import Systemd.Journal
logRecordToJournalFields :: LogRecord -> JournalFields
logRecordToJournalFields record =
locationFields <>
priority (logLevelToPriority (logRecordLevel record)) <>
message (fromString (logRecordMessage record))
where
locationFields =
fromList $ maybe [] toLocationFields (logRecordLocation record)
toLocationFields loc =
("CODE_FILE", encodeUtf8 (locationFile loc)) :
("CODE_LINE", fromString (show (locationLine loc))) :
[]
encodeUtf8 = Text.encodeUtf8 . fromString
logLevelToPriority :: LogLevel -> Priority
logLevelToPriority l = case l of
TRACE -> Debug
DEBUG -> Debug
INFO -> Info
WARN -> Warning
ERROR -> Error
|
zalora/logging-facade-journald
|
src/System/Logging/Facade/Journald/Internal.hs
|
Haskell
|
mit
| 977
|
{-# htermination (^^) :: (Ratio Int) -> Int -> (Ratio Int) #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_CARETCARET_3.hs
|
Haskell
|
mit
| 63
|
module RAE
where
import Blaze
import Tree
import Text.Printf
import Data.Number.LogFloat (logFloat,fromLogFloat)
import Data.List
-- Pretty-print expressions
showE :: State -> String
showE (Node (SNode _ (DoubleDatum d)) [] _) = printf "%0.3f" d
showE (Node (SNode _ (StringDatum s)) [] _) = s
showE (Node (SNode _ (StringDatum s)) cs _)
| (s == "and" ) = printf "(and %s)" (intercalate " " scs)
| (s == "list") = printf "(list %s)" (intercalate " " scs)
where scs = map showE cs
showE (Node (SNode _ (StringDatum s)) [c1] _)
| (s == "eval" ) = printf "(eval %s)" sc1
| (s == "thunk" ) = printf "(thunk %s)" sc1
| (s == "unthunk") = printf "(unthunk %s)" sc1
| (s == "abs" ) = printf "abs(%s)" sc1
| (s == "neg" ) = printf "-(%s)" sc1
| (s == "flip" ) = printf "flip(%s)" sc1
| (s == "sampint") = printf "sampint(%s)" sc1
| (s == "draw" ) = printf "draw(%s)" sc1
| (s == "num" ) = sc1
| (s == "var" ) = sc1
| otherwise = error $ printf "showE: invalid unary op %s" s
where sc1 = showE c1
showE (Node (SNode _ (StringDatum s)) [c1,c2] _)
| (s == "lambda") = printf "(lambda %s %s)" sc1 sc2
| (s == "app" ) = printf "(%s %s)" sc1 sc2
| (s == "+" ) = printf "(%s + %s)" sc1 sc2
| (s == "-" ) = printf "(%s - %s)" sc1 sc2
| (s == "*" ) = printf "(%s * %s)" sc1 sc2
| (s == "exp" ) = printf "(%s ^ %s)" sc1 sc2
| (s == "max" ) = printf "max(%s, %s)" sc1 sc2
| otherwise = error $ printf "showE: invalid binary op %s" s
where [sc1,sc2] = map showE [c1,c2]
showE (Node (SNode _ (StringDatum s)) [c1,c2,c3] _)
| (s == "let" ) = printf "(let (%s = %s) in %s)" sc1 sc2 sc3
| (s == "if" ) = printf "(if %s then %s else %s)" sc1 sc2 sc3
| otherwise = error $ printf "showE: invalid ternary op %s" s
where [sc1,sc2,sc3] = map showE [c1,c2,c3]
showE (Node (SNode _ (StringDatum s)) cs _)
| otherwise = error $ printf "showE: invalid multi op %s" s
where scs = map showE cs
-- Helper functions for building expressions.
nullaryOp :: String -> State
nullaryOp s = mkStringData s
unaryOp :: String -> State -> State
unaryOp s e1 = mkStringData s `addChild` e1
binaryOp :: String -> State -> State -> State
binaryOp s e1 e2 = mkStringData s `collectStates` [e2,e1]
ternaryOp :: String -> State -> State -> State -> State
ternaryOp s e1 e2 e3 = mkStringData s `collectStates` [e3,e2,e1]
multiOp :: String -> [State] -> State
multiOp s es = mkStringData s `collectStates` (reverse es)
-- In the absence of a parser, I use these functions to build an AST
thunkE = unaryOp "thunk"
unthunkE = unaryOp "unthunk"
lambdaE = binaryOp "lambda"
appE = binaryOp "app"
evalE = unaryOp "eval"
letE = ternaryOp "let"
absE = unaryOp "abs"
negE = unaryOp "neg"
addE = binaryOp "+"
subE = binaryOp "-"
mulE = binaryOp "*"
expE = binaryOp "exp"
maxE = binaryOp "max"
trueE = nullaryOp "true"
falseE = nullaryOp "false"
andE = multiOp "and"
ifE = ternaryOp "if"
flipE = unaryOp "flip"
sampintE = unaryOp "sampint"
drawE = unaryOp "draw"
listE = multiOp "list"
numE = mkDoubleData
varE = mkStringData
-- Building an evaluator for testing; this will eventaully be worked
-- into a Kernel and Density.
getCode :: State -> State
getCode = getTA ["code"]
getSteps :: State -> State
getSteps = getTA ["steps"]
getProbs :: State -> State
getProbs = getTA ["probs"]
getEnv :: State -> State
getEnv = getTA ["env"]
showEnv :: State -> String
showEnv s | (null senvcs) = "(empty env)"
| otherwise = intercalate ", " $ map se senvcs
where senvcs = children $ getEnv s
se e = printf "%s => (%s, %s)" (tagged e)
(showE $ getTA ["bstate"] s) (showEnv $ getTA ["benv"] s)
showNode :: State -> String
showNode s = printf "Code: %s\nEnv: %s\nProb: %s" (showE . getCode $ s)
(showEnv s)
(show . map doubleVal . children . getProbs $ s)
isValue :: State -> Bool
isValue (Node (SNode _ (DoubleDatum _ )) _ _) = True
isValue (Node (SNode _ (StringDatum "list")) cs _) = all isValue cs
isValue (Node (SNode _ (StringDatum ctag )) cs _) =
ctag `elem` ["thunk","lambda","true","false"]
envlookup :: String -> State -> Maybe State
envlookup ltag s | (ltag `elem` map tagged cs) = Just (getTagged ltag cs)
| otherwise = Nothing
where cs = children . getEnv $ s
evalhelper :: State -> ([State],[Double],[State])
evalhelper sl = ([(Node (SNode [] newctag) newvals "")], [1.0], [])
where (Node (SNode [] (StringDatum "list")) (newhead:newvals) _) = sl
(Node (SNode [] newctag ) _ _) = newhead
ifhelper :: State -> State -> State -> ([State],[Double],[State])
ifhelper (Node (SNode [] (StringDatum "true" )) [] _) st sf = ([st], [1.0], [])
ifhelper (Node (SNode [] (StringDatum "false")) [] _) st sf = ([sf], [1.0], [])
ifhelper _ _ _ =
error "ifhelper: conditional must be a boolean"
apphelper :: State -> State -> ([State],[Double],[State])
apphelper op operand = ([ope], [1.0], [operand `tag` (stringVal opv)])
where (Node (SNode [] (StringDatum "lambda")) [opv,ope] _) = op
varhelper :: State -> State -> ([State],[Double],[State])
varhelper s v = ([s'], [1.0], [])
where s' = maybe v id $ envlookup (stringVal v) s
andhelper :: [State] -> ([State],[Double],[State])
andhelper cs
| (not allbool) = error "andhelper: expects only boolean values"
| otherwise = (if alltrue then [trueE] else [falseE], [1.0], [])
where allbool = all (flip elem ["true","false"] . stringVal) cs
alltrue = all ((== "true") . stringVal) cs
fliphelper :: State -> ([State],[Double],[State])
fliphelper c = ([trueE, falseE], [doubleVal c, 1.0 - doubleVal c], [])
sampinthelper :: State -> ([State],[Double],[State])
sampinthelper c = (vals, probs, [])
where vals = map numE [0..(doubleVal c)]
nvals = length vals
probs = replicate nvals (1 / fromIntegral nvals)
drawhelper :: State -> ([State],[Double],[State])
drawhelper c = (vals, probs, [])
where vals = children c
nvals = length vals
probs = replicate nvals (1 / fromIntegral nvals)
holehelper :: State -> String -> [State] -> ([State],[Double],[State])
holehelper s ct cs = (map mkStep e', p', env')
where (vs,(e:es)) = break (not . isValue) cs
(e',p',env') = step' s e
cs' x = vs ++ [x] ++ es
mkStep x = (Node (SNode [] (StringDatum ct)) (cs' x) "")
notFinal :: State -> State -> Bool
notFinal s v@(Node (SNode [] (StringDatum _ )) [] _) = v /= v'
where ([v'],_,_) = varhelper s v
notFinal s v@(Node (SNode [] (StringDatum "list")) cs _) = any (notFinal s) cs
notFinal _ v = not . isValue $ v
-- Step takes a state and produces a list of possible single-step
-- reductions, a list of associated probabilities, and a set of new
-- variable bindings to add to the environment.
step :: State -> ([State],[Double],[State])
step s = step' s (getCode s)
step' :: State -> State -> ([State],[Double],[State])
step' s (Node (SNode [] (StringDatum ctag )) cs@[c] _)
| (ctag == "eval" ) = evalhelper c
| (notFinal s c ) = holehelper s ctag cs
| (ctag == "sampint") = sampinthelper c
| (ctag == "unthunk") = ([head . children $ c], [1.0], [])
| (ctag == "flip" ) = fliphelper c
| (ctag == "draw" ) = drawhelper c
| (ctag == "and" ) = andhelper cs
| (ctag == "abs" ) = ([numE (abs $ doubleVal c)], [1.0], [])
| (ctag == "neg" ) = ([numE (negate $ doubleVal c)], [1.0], [])
step' s (Node (SNode [] (StringDatum ctag )) cs@[c1,c2] _)
| (notFinal s c1) = holehelper s ctag cs
| (ctag == "app" ) = apphelper c1 c2
| (notFinal s c2 ) = holehelper s ctag cs
| (ctag == "+" ) = ([numE (doubleVal c1 + doubleVal c2)], [1.0], [])
| (ctag == "-" ) = ([numE (doubleVal c1 - doubleVal c2)], [1.0], [])
| (ctag == "*" ) = ([numE (doubleVal c1 * doubleVal c2)], [1.0], [])
| (ctag == "exp" ) = ([numE (doubleVal c1 ** doubleVal c2)], [1.0], [])
| (ctag == "max" ) = ([numE (max (doubleVal c1) (doubleVal c2))], [1.0], [])
| (ctag == "and" ) = andhelper cs
step' s (Node (SNode [] (StringDatum "let")) cs@[c1,c2,c3] _)
| (notFinal s c2) = holehelper s "let" cs
| otherwise = ([c3], [1.0], [c2 `tag` (stringVal c1)])
step' s (Node (SNode [] (StringDatum "if" )) cs@[c1,c2,c3] _)
| (notFinal s c1) = holehelper s "if" cs
| otherwise = ifhelper c1 c2 c3
step' s s'@(Node (SNode [] (StringDatum ctag )) cs _)
| (any (notFinal s) cs) = holehelper s ctag cs
| (ctag == "and" ) = andhelper cs
| (null cs ) = varhelper s s'
-- Code except the program to be executed and the query.
sdefs :: State
sdefs = (andE [(flipE (numE 0.5)), (flipE (numE 0.2)), (flipE (numE 0.1))])
{-
(letE (varE "noisy=")
(lambdaE (varE "x")
(lambdaE (varE "y")
(flipE (expE (numE 0.1)
(absE (subE (varE "x") (varE "y")))))))
(letE (varE "rae")
(thunkE sprogram)
(letE (varE "proc-from-expr")
(lambdaE (varE "expr")
(evalE (listE [(varE "lambda"), (varE "x"), (varE "expr")])))
(letE (varE "my-expr")
(unthunkE (varE "rae"))
(letE (varE "my-proc")
(appE (varE "proc-from-expr") (varE "my-expr"))
squery)))))
-}
-- Program that generates random arithmetic expressions.
sprogram :: State
sprogram =
(ifE (flipE (numE 0.8))
(ifE (flipE (numE 0.5)) (varE "x") (sampintE (numE 10)))
(listE [(drawE
(listE [(varE "+"), (varE "-"), (varE "*"), (varE "max")])),
(unthunkE (varE "rae")),
(unthunkE (varE "rae"))]))
-- Query conditioned on the random arithmetic expression.
squery :: State
squery =
(andE [(appE (appE (varE "noisy=")
(appE (varE "my-proc") (numE (-2)))) (numE 5)),
(appE (appE (varE "noisy=")
(appE (varE "my-proc") (numE 0))) (numE 1)),
(appE (appE (varE "noisy=")
(appE (varE "my-proc") (numE 1))) (numE 2)),
(appE (appE (varE "noisy=")
(appE (varE "my-proc") (numE 2))) (numE 5)),
(appE (appE (varE "noisy=")
(appE (varE "my-proc") (numE 3))) (numE 10))])
buildTree :: State -> State
buildTree s
| (isValue code) = build [code,dummyState,dummyState,env]
| otherwise = build [code,steps, probs, env]
where code = getCode s
env = getEnv s
(steps', probs', env') = step s
env'' = dummyState { children = (env' ++ children env) }
mkHead x = dummyState `collectStates`
[x `tag` "code", env'' `tag` "env"]
steps'' = map mkHead steps'
steps = dummyState `collectStates` map buildTree steps''
probs = dummyState `collectStates` map mkDoubleData probs'
build cs = dummyState `collectStates`
zipWith tag cs ["code","steps","probs","env"]
sr :: State
sr = buildTree (dummyState `collectStates` [tcode,tenv])
`collectStates` [tterm,trace]
where tcode = sdefs `tag` "code"
tenv = dummyState `tag` "env"
tterm = flip tag "term" $
dummyState `collectStates` [trueE `tag` "t", falseE `tag` "f"]
trace = flip tag "trace" $
buildTree $
dummyState `collectStates`
[falseE `tag` "code", dummyState `tag` "env"]
sd :: Likelihood
sd s _ = logFloat $ doubleVal $ getTA ["prob"] s
kr :: Kernel
kr = mkURWKernel [["term","t"],["term","f"]]
traceChurch :: TA -> ReportAct
traceChurch ta machines = do
let tr m = printf "%s: %.3g" (showE . getTA ta $ ms m)
(fromLogFloat . topDensity $ m :: Double)
mapM_ (putStrLn . tr) machines
return machines
traceChurchEnv :: TA -> String -> ReportAct
traceChurchEnv ta v machines = do
let tr m = printf "%s: %.3g" (maybe "" showE . envlookup v . getTA ta $ ms m)
(fromLogFloat . topDensity $ m :: Double)
mapM_ (putStrLn . tr) machines
return machines
buildMachine :: Entropy -> Machine
buildMachine e = Machine sr dummyDensity kr e
main :: IO ()
main = foldl (>>=) (run buildMachine)
[ stopAfter 100, traceChurch ["trace","code"]] >>
putStrLn "Run complete!"
|
othercriteria/blaze
|
RAE.hs
|
Haskell
|
mit
| 12,894
|
module HTML where
import Text.Blaze.Html5 hiding (map)
import qualified Text.Blaze.Html5 as H
import Text.Blaze.Html5.Attributes
import Data.List
import DataTypes
import Data.Monoid
proof2html :: BinTree DecoratedSequent -> Html
proof2html (Leaf lab s) =
table $ do
tr $ toHtml ""
tr $ do
td $ hr
td $ lab2html lab
tr $ td $ decoratedSeq2html s
proof2html (Unary lab s t) =
table $ do
tr $ td $ proof2html t
tr $ do
td $ hr
td $ lab2html lab
tr $ td $ decoratedSeq2html s
proof2html (Branch lab l s r) =
table $ do
tr $ do
td $ proof2html l
td $ proof2html r
tr $ do
(td $ hr) ! (colspan $ toValue "2")
td $ lab2html lab
tr $ (td $ decoratedSeq2html s) ! (colspan $ toValue "2")
lab2html :: Label -> Html
lab2html Id = toHtml "id"
lab2html ImpL = preEscapedToHtml "→L"
lab2html ImpR = preEscapedToHtml "→R"
lab2html MonL = preEscapedToHtml "◊L"
lab2html MonR = preEscapedToHtml "◊R"
lambda2html :: LambdaTerm -> Html
lambda2html (C c) = em $ toHtml c
lambda2html (V n) | n < length sanevars && n >= 0 =
toHtml $ sanevars !! n
| otherwise = toHtml $ "v" ++ show n
lambda2html (Lambda x b) = do
preEscapedToHtml "λ"
lambda2html x
toHtml "."
lambda2html b
lambda2html (Eta f) = do
preEscapedToHtml "η("
lambda2html f
toHtml ")"
lambda2html (App f@(Lambda _ _) a) = do
toHtml "("
lambda2html f
toHtml ")("
lambda2html a
toHtml ")"
lambda2html (App f@(_ :*: _) a) = do
toHtml "("
lambda2html f
toHtml ")("
lambda2html a
toHtml ")"
lambda2html (App f a) = do
lambda2html f
toHtml "("
lambda2html a
toHtml ")"
lambda2html (m :*: k) = do
lambda2html m
preEscapedToHtml " ∗ "
lambda2html k
decoratedSeq2html :: DecoratedSequent -> Html
decoratedSeq2html (gamma,c) = mconcat left >> toHtml " => " >> f c where
left = intersperse (toHtml ", ") $ map f gamma
f (DF _ lt f) = lambda2html lt >> toHtml " : " >> formula2html f
-- |Texifies a formula (now with smart parentheses!)
formula2html :: Formula -> Html
formula2html (Atom a _) = toHtml a
formula2html (Var x _) = toHtml x
formula2html (M (Atom a _) _) = preEscapedToHtml "◊" >> toHtml a
formula2html (M (Var x _) _) = preEscapedToHtml "◊" >> toHtml x
formula2html (M f _) = preEscapedToHtml "◊(" >> formula2html f >> toHtml ")"
formula2html (I (Atom a _) f _) = toHtml a >> preEscapedToHtml " → " >> formula2html f
formula2html (I (Var a _) f _) = toHtml a >> preEscapedToHtml " → " >> formula2html f
formula2html (I d@(M _ _) f _) = formula2html d >> preEscapedToHtml " → " >> formula2html f
formula2html (I f g _) = do
toHtml "("
formula2html f
preEscapedToHtml ") → "
formula2html g
|
gianlucagiorgolo/glue-tp
|
HTML.hs
|
Haskell
|
mit
| 2,746
|
{-|
Module : BreadU.Pages.Markup.Common.Utils
Description : HTML markup utils.
Stability : experimental
Portability : POSIX
HTML markup utils.
-}
module BreadU.Pages.Markup.Common.Utils where
import Prelude hiding ( span, div )
import Data.Monoid ( (<>) )
import Data.Text ( Text )
import Text.Blaze.Html5
import qualified Text.Blaze.Html5.Attributes as A
-- | Row for Bootstrap grid. Partially-applied function,
-- it has to be applied to an 'Html'-expression.
row_ :: Html -> Html
row_ = div ! A.class_ "row"
-- | Columns for Bootstrap grid. Partially-applied function,
-- it has to be applied to an 'Html'-expression.
col_1
, col_2
, col_3
, col_4
, col_5
, col_6
, col_7
, col_8
, col_9
, col_10
, col_11
, col_12 :: Html -> Html
col_1 = col_ 1
col_2 = col_ 2
col_3 = col_ 3
col_4 = col_ 4
col_5 = col_ 5
col_6 = col_ 6
col_7 = col_ 7
col_8 = col_ 8
col_9 = col_ 9
col_10 = col_ 10
col_11 = col_ 11
col_12 = col_ 12
-- | Column for Bootstrap grid. Partially-applied function,
-- it has to be applied to an 'Html'-expression.
col_ :: Int -> Html -> Html
col_ width = div ! A.class_ (toValue $ "col-" <> show width)
-- | Font Awesome icon.
fa :: Text -> Html
fa iconName = i ! A.class_ (toValue $ "fa " <> iconName)
! customAttribute "aria-hidden" "true" $ mempty
|
denisshevchenko/breadu.info
|
src/lib/BreadU/Pages/Markup/Common/Utils.hs
|
Haskell
|
mit
| 1,433
|
module LMH_Interpreter where
import LMH_Lex
import LMH_Parse
import LMH_ExpType
import LMH_TypeInference
import LMH_Evaluator
toString :: Type -> String
toString (TypeVar str) = str
toString (TypeConst str) = str
toString (Arrow (TypeVar str, t)) =
str ++ " -> " ++ (toString t)
toString (Arrow (TypeConst str, t)) =
str ++ " -> " ++ (toString t)
toString (Arrow (t1, t2)) =
"(" ++ (toString t1) ++ ") -> " ++ (toString t2)
-- runLMH "file.hs"
--
-- lexes and parses the MH program text in file.hs and
-- performs static analysis including type inference.
-- Then it enters an interpreter loop: the user inputs an
-- MH expression, which the computer and evaluates,
-- outputting the type and resulting value.
-- The loop is exited by inputting ":q"
runLMH filename = do
progtext <- readFile filename
let lexed = alexScanTokens progtext
termDecls = lmh_parseProg lexed
declVars = checkVars termDecls
env = (\x -> case lookup x termDecls of
Just exp -> exp
-- The case below should never occur due to static analysis
Nothing -> error ("Lookup error - undefined variable: " ++ x))
in if -- this test implements condition 3 in Note 4
all (\x -> (all (\y -> elem y declVars) (freevars (env x)))) declVars
then let tenv = initialiseTEnv declVars
tenv' = inferProg declVars tenv env
in do _ <- putStrLn ""
_ <- printTypes tenv'
runIn tenv' env
else putStrLn "Out-of-scope variables in program."
checkVars [] = []
checkVars ((x,_):trds) =
let xs = checkVars trds
in if notElem x xs then (x:xs)
else error ("Duplicate declaration for variable " ++ x)
inferProg [] tenv _ = tenv
inferProg (x:xs) tenv env =
let (s',t') = inferType tenv (env x)
tenv' = typeSubstTEnv tenv s'
(Just t) = (lookup x tenv')
s = mgu t t'
in inferProg xs (typeSubstTEnv tenv' s) env
printTypes [] = putStrLn ""
printTypes ((x,t):tenv) =
do _ <- putStrLn (x ++ " :: " ++ (toString t))
printTypes tenv
runIn tenv env = do
_ <- putStr "LMH> "
textuser <- getLine
if textuser == ":q" then putStrLn "LMH goodbye!"
else let lexeduser = alexScanTokens textuser
exp = lmh_parseExp lexeduser
(_, t) = inferType tenv exp
in do _ <- putStr "Type: "
_ <- putStrLn (toString t)
_ <- putStr "Value: "
_ <- print (evaluate env exp)
runIn tenv env
|
jaanos/TPJ-2015-16
|
lmh/LMH_Interpreter.hs
|
Haskell
|
mit
| 2,531
|
{-# LANGUAGE DeriveGeneric #-}
module Bce.RestTypes where
import Bce.BlockChain
import Bce.Hash
import Bce.BlockChainSerialization
import Bce.BlockChainHash
import GHC.Generics
import qualified Data.Set as Set
import Data.Aeson hiding (json)
data WalletBalance = WalletBalance { outputs :: Set.Set TxOutputRef
, unconfirmed :: Set.Set TxOutputRef } deriving (Show, Eq, Generic)
instance ToJSON WalletBalance
instance FromJSON WalletBalance
data RestTransaction = RestTransaction {
tx :: Transaction
, txId :: TransactionId
} deriving (Generic, Eq, Show)
instance ToJSON RestTransaction
instance FromJSON RestTransaction
data RestBlock = RestBlock {
blockHeader :: BlockHeader
, transactions :: [RestTransaction]
} deriving (Generic, Eq, Show)
instance ToJSON RestBlock
instance FromJSON RestBlock
blockToRestBlock :: Block -> RestBlock
blockToRestBlock blk =
let hdr = Bce.BlockChain.blockHeader blk
txs = map (\tx -> RestTransaction tx (transactionId blk tx)) $ Set.toList (blockTransactions blk)
in RestBlock hdr txs
data Head = Head {
headLength :: Int
, headBlockId :: BlockId
} deriving (Generic, Eq, Show)
instance ToJSON Head
instance FromJSON Head
|
dehun/bce
|
src/Bce/RestTypes.hs
|
Haskell
|
mit
| 1,320
|
module PythagorianTriple54 where
pythagoreanTriple :: Int -> [(Int, Int, Int)]
pythagoreanTriple x = if x <= 0 then [] else do
a <- [1..x]
b <- [1..x]
c <- [1..x]
let a' = a^3
let b' = b^2
let c' = c^2
if a < b && (a' + b' == c') then "_" else []
return (a,b,c)
main' :: IO ()
main' = do
putStrLn "What is your name?"
putStr "Name: "
name <- getLine
case name of
[] -> main'
_ -> putStrLn $ "Hi, " ++ name
|
raventid/coursera_learning
|
haskell/stepik/5.4pythagorian_triple.hs
|
Haskell
|
mit
| 441
|
{-# LANGUAGE TemplateHaskell #-}
module Oczor.Parser.ParserState where
import Oczor.Syntax.Operators
import Control.Lens
import Text.Megaparsec.Expr
import Control.Monad.State
import ClassyPrelude as C hiding (try)
import Oczor.Syntax.Syntax
import qualified Text.Megaparsec.String as Megaparsec
type Parser = StateT ParserState Megaparsec.Parser
data ParserState = ParserState {
_count :: Int,
_asName :: Maybe String,
_ops :: OperatorGroups,
_opTable :: [[Operator Parser Expr]]
}
makeLenses ''ParserState
emptyState = ParserState {
_count = 0,
_asName = Nothing,
_ops = [],
_opTable = []
}
cleanAsName :: Parser ()
cleanAsName = asName .= Nothing
asNameOrFresh :: Parser String
asNameOrFresh = use asName >>= maybe freshName return
letters :: [String]
letters = [1..] >>= flip C.replicateM ['a'..'z']
freshName :: Parser String
freshName = do
c <- use count
count += 1
return $ sysPrefix ++ unsafeIndex letters c
|
ptol/oczor
|
src/Oczor/Parser/ParserState.hs
|
Haskell
|
mit
| 946
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.MessageChannel
(js_newMessageChannel, newMessageChannel, js_getPort1, getPort1,
js_getPort2, getPort2, MessageChannel, castToMessageChannel,
gTypeMessageChannel)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe "new window[\"MessageChannel\"]()"
js_newMessageChannel :: IO (JSRef MessageChannel)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel Mozilla MessageChannel documentation>
newMessageChannel :: (MonadIO m) => m MessageChannel
newMessageChannel
= liftIO (js_newMessageChannel >>= fromJSRefUnchecked)
foreign import javascript unsafe "$1[\"port1\"]" js_getPort1 ::
JSRef MessageChannel -> IO (JSRef MessagePort)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel.port1 Mozilla MessageChannel.port1 documentation>
getPort1 :: (MonadIO m) => MessageChannel -> m (Maybe MessagePort)
getPort1 self
= liftIO ((js_getPort1 (unMessageChannel self)) >>= fromJSRef)
foreign import javascript unsafe "$1[\"port2\"]" js_getPort2 ::
JSRef MessageChannel -> IO (JSRef MessagePort)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel.port2 Mozilla MessageChannel.port2 documentation>
getPort2 :: (MonadIO m) => MessageChannel -> m (Maybe MessagePort)
getPort2 self
= liftIO ((js_getPort2 (unMessageChannel self)) >>= fromJSRef)
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/JSFFI/Generated/MessageChannel.hs
|
Haskell
|
mit
| 2,189
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
module Language.PureScript.Binding.TH where
import Control.Applicative
import Language.Haskell.TH as TH
import Language.PureScript.Binding.Class
import Language.PureScript.Binding.Dependency
import Data.Monoid
import Data.Text.Lazy.Builder hiding (fromString)
import qualified Data.String as S
import Data.List
import Data.Proxy
import Data.Aeson.TH
--------------------------------------------------------------------------------
tyVarBndrName :: TyVarBndr -> Name
tyVarBndrName (PlainTV n ) = n
tyVarBndrName (KindedTV n _) = n
bUnlines :: [Builder] -> Builder
bUnlines = mconcat . map (<> singleton '\n')
bUnwords :: [Builder] -> Builder
bUnwords = mconcat . intersperse (singleton ' ')
fromString :: String -> Builder
fromString = fromText . S.fromString
{-# INLINE fromString #-}
typeToPsTypeE :: Type -> ExpQ
typeToPsTypeE = \case
(AppT ListT a) -> [|singleton '[' <> $(typeToPsTypeE a) <> singleton ']'|]
(AppT a b) -> [|singleton '(' <> $(typeToPsTypeE a) <> singleton ' ' <> $(typeToPsTypeE b) <> singleton ')'|]
(VarT v) -> [|fromString $(stringE $ nameBase v) |]
TupleT n | n == 2 -> [|fromString $(stringE "Data.Tuple.Tuple")|]
| otherwise -> fail $ "2-tuple only."
c -> do
b <- recover (return False) (isInstance ''PureScriptType [c])
if b
then [|fromText $ toPureScriptType (Proxy :: Proxy $(return c))|]
else fail $ show c ++ " is not instance of PureScriptType."
depTypes :: Type -> Q [Type]
depTypes = \case
(AppT a b) -> (++) <$> depTypes a <*> depTypes b
c -> do
b <- recover (return False) (isInstance ''HasPureScript [c])
return $ if b then [c] else []
conName :: Con -> Name
conName (NormalC n _) = n
conName (RecC n _) = n
conName (InfixC _ n _) = n
conName (ForallC _ _ c) = conName c
--------------------------------------------------------------------------------
-- | type instance Deps Name = '[Name']
depsD :: Name -> [Con] -> DecQ
depsD name cons = do
let ts = concatMap fn cons
deps <- concat <$> mapM depTypes ts
let r = foldr (\i b -> (PromotedT '(:-) `AppT` i `AppT` b)) (PromotedT 'TNil) deps
tySynInstD ''Deps $ tySynEqn [conT name] (return r)
where
fn (NormalC _ ts) = map snd ts
fn (RecC _ ts) = map (\(_,_,t) -> t) ts
fn (InfixC a _ b) = snd a : snd b : []
fn (ForallC _ _ c) = fn c
--------------------------------------------------------------------------------
-- | instance PureScriptType Name where
-- toPureScriptType _ = "Name"
toPureScriptTypeD :: Name -> DecQ
toPureScriptTypeD n = funD 'toPureScriptType
[clause [wildP] (normalB [|S.fromString $(stringE $ nameBase n)|]) []]
pureScriptTypeInstanceD :: Name -> DecQ
pureScriptTypeInstanceD n = instanceD (return []) (conT ''PureScriptType `appT` conT n)
[toPureScriptTypeD n]
--------------------------------------------------------------------------------
-- | dataDecl _ = "data A = .."
dataDeclD :: Name -> [TyVarBndr] -> [Con] -> DecQ
dataDeclD name vars cons = funD 'dataDecl
[clause [wildP] (normalB $ dataDeclE name vars cons) []]
dataDeclE :: Name -> [TyVarBndr] -> [Con] -> ExpQ
dataDeclE name vars cons =
let cls = zipWith dataDeclConStringE (" = " : repeat " | ") cons
fl = unwords
("data" : nameBase name : map (nameBase . tyVarBndrName) vars)
in [|bUnlines $ fromString $(stringE fl) : $(listE cls)|]
dataDeclConStringE :: String -> Con -> ExpQ
dataDeclConStringE p (NormalC n ts) =
let e = listE $ map (typeToPsTypeE . snd) ts
in [|fromString $(stringE $ p ++ nameBase n ++ " ") <> bUnwords $e |]
dataDeclConStringE p (RecC n ts) =
let e = listE $ map (\(c,_,t) -> [|fromString $(stringE $ nameBase c ++ " :: ") <> $(typeToPsTypeE t)|]) ts
in [| fromString $(stringE $ p ++ nameBase n ++ " {") <> mconcat (intersperse (fromString ", ") $e) <> singleton '}' |]
dataDeclConStringE _ InfixC{} = fail "cannot use infix data constructor."
dataDeclConStringE _ ForallC{} = fail "cannot use existential quantification."
--------------------------------------------------------------------------------
-- | FromJSON autoNameFromJSON :: FromJSON Name where
-- parseJSON
foreignDeclD :: Options -> Name -> [TyVarBndr] -> [Con] -> DecQ
foreignDeclD opts name vars cons = funD 'foreignDecl
[clause [wildP] (normalB $ foreignDeclE opts name vars cons) []]
foreignDeclE :: Options -> Name -> [TyVarBndr] -> [Con] -> ExpQ
foreignDeclE opts name vars cons = do
let hdr = concat
[ "instance auto", nameBase name, "FromJSON :: "
, foreignDeclCxt vars
, "Data.JSON.FromJSON ", foreignDeclName name vars, "where"
]
se = stringE $ intercalate "\n"
[ hdr
, foreignDeclFun opts cons
]
[|fromString $se|]
foreignDeclName :: Name -> [TyVarBndr] -> String
foreignDeclName n [] = nameBase n ++ " "
foreignDeclName n vars = '(' : nameBase n ++ ' ': intercalate " " (map (nameBase . tyVarBndrName) vars) ++ ") "
foreignDeclCxt :: [TyVarBndr] -> String
foreignDeclCxt [] = ""
foreignDeclCxt vars =
'(' : intercalate ", " (map (\v -> "Data.JSON.FromJSON " ++ nameBase (tyVarBndrName v)) vars) ++ ") => "
sp :: Int -> String
sp i = replicate (4 * i) ' '
foreignDeclSingleFun :: Options -> Int -> Con -> String
foreignDeclSingleFun _ i (NormalC n t) =
let vs = map (('v':) . show) $ take (length t) [ 0 :: Int .. ]
cse = sp i ++ "case input of"
rit = sp (i + 1) ++ "Data.JSON.JArray [" ++ intercalate "," vs ++ "] -> do"
pf v = sp (i + 2) ++ v ++ "' <- Data.JSON.parseJSON " ++ v
ret = sp (i + 2) ++ "return (" ++ nameBase n ++ ' ': intercalate "' " vs ++ "')"
lft = sp (i + 1) ++ "_ -> Data.JSON.fail \"cannot parse.\""
in intercalate "\n" $ cse : rit : map pf vs ++ [ret, lft]
foreignDeclSingleFun Options{..} i (RecC n t) =
let cse = sp i ++ "case input of"
rit = sp (i + 1) ++ "Data.JSON.JObject object -> do"
pf v = sp (i + 2) ++ v ++ " <- Data.JSON.(.:) object \"" ++ fieldLabelModifier v ++ "\""
ret = sp (i + 2) ++ "return (" ++ nameBase n ++ " {" ++ intercalate ", "
(map (\(c,_,_) -> nameBase c ++ ": " ++ nameBase c) t) ++ "})"
lft = sp (i + 1) ++ "_ -> Data.JSON.fail \"cannot parse.\""
in intercalate "\n" $ cse : rit : map (\(c,_,_) -> pf $ nameBase c) t ++ [ret, lft]
foreignDeclSingleFun _ _ InfixC{} = error "cannot use infix data constructor."
foreignDeclSingleFun _ _ ForallC{} = error "cannot use existential quantification."
foreignDeclFun :: Options -> [Con] -> String
foreignDeclFun opts [con] = unlines [sp 1 ++ "parseJSON input =", foreignDeclSingleFun opts 2 con]
foreignDeclFun opt@Options{sumEncoding = TaggedObject {..}, .. } rs =
let fl = sp 1 ++ "parseJSON (Data.JSON.JObject obj) = case Data.JSON.(.:) obj \"" ++ tagFieldName ++ "\" of"
ca c@(NormalC n _) = unlines
[ sp 2 ++ "Data.Either.Right \"" ++ constructorTagModifier (nameBase n) ++
"\" -> case Data.JSON.(.:) obj \"" ++ contentsFieldName ++ "\" of"
, sp 3 ++ "Data.Either.Right input ->"
, foreignDeclSingleFun opt 4 c
, sp 3 ++ "_ -> Data.JSON.fail \"cannot parse.\""
]
ca c@(RecC n _) = unlines
[ sp 2 ++ "Data.Either.Right \"" ++ constructorTagModifier (nameBase n) ++
"\" -> let input = Data.JSON.JObject obj in"
, foreignDeclSingleFun opt 3 c
]
ca InfixC{} = error "cannot use infix data constructor."
ca ForallC{} = error "cannot use existential quantification."
fil = sp 2 ++ "_ -> Data.JSON.fail \"cannot parse.\""
fbk = sp 1 ++ "parseJSON _ = Data.JSON.fail \"cannot parse.\""
in unlines $ fl : map ca rs ++ [fil, fbk]
foreignDeclFun opt@Options{sumEncoding = TwoElemArray, .. } rs =
let fl = sp 1 ++ "parseJSON array = case Data.JSON.parseJSON array of"
ca c = unlines
[ sp 2 ++ "Data.Either.Right (Data.Tuple.Tuple \"" ++
constructorTagModifier (nameBase $ conName c) ++ "\" input) ->"
, foreignDeclSingleFun opt 3 c
]
fil = sp 2 ++ "_ -> Data.JSON.fail \"cannot parse.\""
in unlines $ fl : map ca rs ++ [fil]
foreignDeclFun opt@Options{sumEncoding = ObjectWithSingleField, .. } rs =
let fl = sp 1 ++ "parseJSON (Data.JSON.JObject obj) = case Data.Map.toList obj of"
ca c = unlines
[ sp 2 ++ "[Data.Tuple.Tuple \"" ++
constructorTagModifier (nameBase $ conName c) ++ "\" input] ->"
, foreignDeclSingleFun opt 3 c
]
fil = sp 2 ++ "_ -> Data.JSON.fail \"cannot parse.\""
fbk = sp 1 ++ "parseJSON _ = Data.JSON.fail \"cannot parse.\""
in unlines $ fl : map ca rs ++ [fil, fbk]
--------------------------------------------------------------------------------
hasPureScriptD :: Options -> Name -> [TyVarBndr] -> [Con] -> DecQ
hasPureScriptD opts name vars cons = instanceD (return []) (conT ''HasPureScript `appT` conT name)
[dataDeclD name vars cons, foreignDeclD opts name vars cons]
declaration :: Options -> Dec -> DecsQ
declaration opts (DataD _ name vars cons _) = do
deps <- depsD name cons
typ <- pureScriptTypeInstanceD name
has <- hasPureScriptD opts name vars cons
return [deps, typ, has]
declaration opts (NewtypeD cnxt name vars con der) = declaration opts (DataD cnxt name vars [con] der)
declaration _ a = fail $ "cannot convert Dec: " ++ show a
-- | derive PureScriptType and HasPureScript instances with aeson Options.
derivePureScript' :: Options -> Name -> DecsQ
derivePureScript' opt name = reify name >>= \case
TyConI d -> declaration opt d
i -> fail $ "cannot convert Info: " ++ show i
-- | derive PureScriptType, HasPureScript and ToJSON instances.
--
derivePureScript :: Name -> DecsQ
derivePureScript name = reify name >>= \case
TyConI d -> do
aeson <- deriveToJSON defaultOptions name
psc <- declaration defaultOptions d
return $ aeson ++ psc
i -> fail $ "cannot convert Info: " ++ show i
|
philopon/haskell-purescript-binding
|
Language/PureScript/Binding/TH.hs
|
Haskell
|
mit
| 10,545
|
data Type = T | S | O Type Type
deriving Show
splits :: [a] -> [([a],[a])]
splits ts = zip (inits ts) (tails ts)
inits :: [a] -> [[a]]
inits [x] = []
inits (x:xs) = map (x:) ([]:inits xs)
tails :: [a] -> [[a]]
tails [x] = []
tails (x:xs) = xs : tails xs
alltypes :: [Type] -> [Type]
alltypes [t] = [t]
alltypes ts = [O l r | (ls,rs) <- splits ts, l <- alltypes ls, r <- alltypes rs]
|
craynafinal/cs557_functional_languages
|
practice/week4/practice.hs
|
Haskell
|
mit
| 388
|
module Ch22.PodTypes
where
import Data.Text (Text)
data Podcast =
Podcast { castId :: Integer
, castURL :: Text
}
deriving (Eq, Show, Read)
data Episode =
Episode { epId :: Integer
, epCast :: Podcast
, epURL :: Text
, epDone :: Bool
}
deriving (Eq, Show, Read)
|
futtetennista/IntroductionToFunctionalProgramming
|
RWH/src/Ch22/PodTypes.hs
|
Haskell
|
mit
| 336
|
{-# LANGUAGE NoMonomorphismRestriction #-}
module Web.HBrowser.Scripting where
import qualified Graphics.UI.Gtk.WebKit.WebView as Web
import Web.HBrowser.WebMonad
import Web.HBrowser.ViewContainer
import Control.Monad.Reader
import Control.Monad.Trans
import Control.Exception
import System.IO
import System.IO.Error
runScript = withCurrentViewIO . flip Web.webViewExecuteScript
runScriptFromFile scriptName = do
web <- ask
jsDir <- asks $ jsScriptDir . config
view <- currentView
let scriptFile = jsDir ++ "/" ++ scriptName
liftIO . putStrLn $ "running script: " ++ scriptFile
liftIO $ catchJust isFileError
(do
withFile scriptFile ReadMode $ \handle -> do
script <- hGetContents handle
Web.webViewExecuteScript view script
)
(\e -> print (e::IOException))
where isFileError e | isDoesNotExistError e = Just e
| isPermissionError e = Just e
| otherwise = Nothing
|
Philonous/hbrowser
|
src/Web/HBrowser/Scripting.hs
|
Haskell
|
mit
| 975
|
module Model
( module Model.DB
, module Model.Open
, module Database.Persist
) where
import Database.Persist
import Model.DB
import Model.Open
|
flipstone/glados
|
src/Model.hs
|
Haskell
|
mit
| 153
|
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DeriveGeneric #-}
{-# OPTIONS_GHC -Wno-orphans #-}
module Instances.Static where
import GHC.Generics
import Test.QuickCheck.Arbitrary.Generic
import Test.QuickCheck.Instances()
import Web.Facebook.Messenger
------------
-- STATIC --
------------
deriving instance Generic PSID
instance Arbitrary PSID where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic PageID
instance Arbitrary PageID where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic AppId
instance Arbitrary AppId where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic SenderActionType
instance Arbitrary SenderActionType where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic MessagingType
instance Arbitrary MessagingType where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic NotificationType
instance Arbitrary NotificationType where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic WebviewHeightRatioType
instance Arbitrary WebviewHeightRatioType where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic AttachmentType
instance Arbitrary AttachmentType where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic AirlineUpdateType
instance Arbitrary AirlineUpdateType where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic ReferralSource
instance Arbitrary ReferralSource where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic ListStyle
instance Arbitrary ListStyle where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic PaymentType
instance Arbitrary PaymentType where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic RequestedUserInfoType
instance Arbitrary RequestedUserInfoType where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic MessageTag
instance Arbitrary MessageTag where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic AppRole
instance Arbitrary AppRole where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic AudienceType
instance Arbitrary AudienceType where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic ImageAspectRatioType
instance Arbitrary ImageAspectRatioType where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic WebviewShareType
instance Arbitrary WebviewShareType where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic PriorMessageType
instance Arbitrary PriorMessageType where
arbitrary = genericArbitrary
shrink = genericShrink
deriving instance Generic FBLocale
instance Arbitrary FBLocale where
arbitrary = genericArbitrary
shrink = genericShrink
|
Vlix/facebookmessenger
|
test/Instances/Static.hs
|
Haskell
|
mit
| 3,015
|
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
module Test.Quorums (quorums_tests) where
import Hetcons.Hetcons_Exception ( Hetcons_Exception )
import Hetcons.Instances_Proof_of_Consensus ()
import Hetcons.Signed_Message
( Encodable
,encode
,Recursive_1a(recursive_1a_filled_in)
,Recursive(non_recursive)
,Monad_Verify(verify)
,Verified
,sign
,original )
import Test.Util ()
import Charlotte_Consts ( sUPPORTED_SIGNED_HASH_TYPE_DESCRIPTOR )
import Charlotte_Types
( Participant_ID(participant_ID_crypto_id, participant_ID_address)
,default_Participant_ID
,Slot_Value(slot_Value_slot, slot_Value_value_payload)
,default_Slot_Value
,Observers(Observers
,observers_observer_graph
,observers_observer_quorums)
,default_Observers
,Proposal_1a(proposal_1a_timestamp, proposal_1a_value
,proposal_1a_observers)
,default_Proposal_1a
,Public_Crypto_Key(public_Crypto_Key_public_crypto_key_x509)
,default_Public_Crypto_Key
,Crypto_ID(crypto_ID_public_crypto_key)
,default_Crypto_ID
,Signed_Message
,Host_Address(host_Address_dns_name)
,default_Host_Address
,Observer_Trust_Constraint(observer_Trust_Constraint_live
,observer_Trust_Constraint_safe
,observer_Trust_Constraint_observer_2
,observer_Trust_Constraint_observer_1)
,default_Observer_Trust_Constraint
,Address(address_port_number, address_host_address)
,default_Address )
import Crypto.Random ( getSystemDRG, DRG, withDRG )
import qualified Data.ByteString.Lazy as ByteString
( singleton, readFile )
import Data.ByteString.Lazy ( ByteString )
import Data.Either.Combinators ( isRight )
import Data.Either.Combinators ( mapRight )
import qualified Data.HashMap.Lazy as HashMap ( toList )
import Data.HashMap.Lazy ()
import Data.HashSet ( fromList, toList )
import Data.List ( sort, elemIndex )
import Test.HUnit
( Test(TestList, TestLabel, TestCase), assertEqual, assertBool )
import Data.HashMap.Strict ( singleton )
import Data.Text.Lazy ( pack )
fill_in_observers :: Observers -> IO Observers
fill_in_observers observers =
do { cert <- ByteString.readFile "test/cert.pem"
; let sample = ((sample_1a cert) {proposal_1a_observers = Just observers})
; signed <- sample_sign $ sample
; let verified = mapRight ((mapRight ((non_recursive :: (Recursive_1a Slot_Value) -> Proposal_1a).original)).verify) signed
; assertEqual "failed to verify a signed proposal_1a" (Right $ Right sample) verified
; let answer = do { s <- signed
; (v_r1a :: Verified (Recursive_1a Slot_Value)) <- verify s
; return $ proposal_1a_observers $ recursive_1a_filled_in $ original v_r1a}
; assertBool "Exception while parsing signed Proposal_1a" $ isRight answer
; return ((\(Right (Just x)) -> x) answer)}
doubleGen :: (DRG g) => g -> (g,g)
doubleGen g = withDRG g (return g)
listGen :: (DRG g) => g -> [g]
listGen g = g:(listGen (snd (withDRG g (return ()))))
sample_sign :: (Encodable a) => a -> IO (Either Hetcons_Exception Signed_Message)
sample_sign payload =
do { gen <- getSystemDRG
; cert <- ByteString.readFile "test/cert.pem"
; private <- ByteString.readFile "test/key.pem"
; let crypto_id = default_Crypto_ID {crypto_ID_public_crypto_key =
Just (default_Public_Crypto_Key {
public_Crypto_Key_public_crypto_key_x509 = Just cert})}
; return $ sign crypto_id private sUPPORTED_SIGNED_HASH_TYPE_DESCRIPTOR gen payload}
sample_id :: ByteString -> Participant_ID
sample_id cert =
default_Participant_ID {
participant_ID_address =
default_Address {
address_host_address =
default_Host_Address {
host_Address_dns_name = Just $ pack "localhost"}
,address_port_number = 8976}
,participant_ID_crypto_id =
default_Crypto_ID {
crypto_ID_public_crypto_key =
Just (default_Public_Crypto_Key {
public_Crypto_Key_public_crypto_key_x509 = Just cert})}}
-- sample_1a :: Proposal_1a
sample_1a cert = default_Proposal_1a {
proposal_1a_value = encode default_Slot_Value {
slot_Value_value_payload = ByteString.singleton 42
,slot_Value_slot = 6}
,proposal_1a_timestamp = 1111111
,proposal_1a_observers = Just default_Observers {
observers_observer_quorums = Just $ singleton (sample_id cert) (fromList [ fromList [sample_id cert]])}}
-- | Try the quorum creation algorithms by inputing a graph
-- | for ease of use, we have our own little language here for observer graphs
-- | using Ints 0..6 to stand for ids, input constraints of the form (observer, observer, [safe], [live])
-- | and a correct graph of the form [(observer [quorum of participants :: [id]])]
-- | and this will run an end-to-end test of quorum creation, and see if it comes out correctly
test_quorum_creation :: [(Int, Int, [Int], [Int])] -> [(Int, [[Int]])] -> IO ()
test_quorum_creation constraints correct_quorums =
do { cert <- ByteString.readFile "test/cert.pem"
; certs' <- mapM (\i -> ByteString.readFile $ "test/cert" ++ (show i) ++ ".pem") [1..9]
; let certs = cert:certs'
; let ids = map sample_id certs
; let observers = default_Observers {observers_observer_graph = Just $ fromList $ map
(\(id1, id2, safe, live) ->
default_Observer_Trust_Constraint {
observer_Trust_Constraint_observer_1 = ids!!id1
,observer_Trust_Constraint_observer_2 = ids!!id2
,observer_Trust_Constraint_safe = fromList $ map (ids!!) safe
,observer_Trust_Constraint_live = fromList $ map (ids!!) live})
constraints}
; observers' <- fill_in_observers observers
-- prettier when printed:
; let observers_list = sort $ map (\(oid, qs) -> ((\(Just x) -> x) $
elemIndex oid ids, sort $ map (\q -> sort $ map (\x -> (\(Just y) -> y) $ elemIndex x ids) $
toList q) $ toList qs)) $ HashMap.toList $ (\(Observers {observers_observer_quorums = Just x}) -> x) observers'
; assertEqual "incorrectly filled in quorums"
(sort $ map (\(x,y) -> (x, sort $ map (sort . (map fromIntegral)) y)) correct_quorums)
observers_list
; return ()}
quorums_tests = TestList [
TestLabel "single observer, single participant" (
TestCase ( test_quorum_creation [(1,1,[1],[1])] [(1,[[1]])] ))
,TestLabel "two observer, four participant" (
TestCase ( test_quorum_creation [ (1,2,[1,2,3 ],[1,2,3 ])
,(1,2,[1,2, 4],[1,2, 4])
,(1,2,[1, 3,4],[1, 3,4])
,(1,2,[ 2,3,4],[ 2,3,4])
]
[ (1,[[1,2,3 ]
,[1,2 ,4]
,[1 ,3,4]
,[ 2,3,4]
])
,(2,[[1,2,3 ]
,[1,2 ,4]
,[1 ,3,4]
,[ 2,3,4]
])
] ))
,TestLabel "two observer, three participant" (
TestCase ( test_quorum_creation [ (1,2,[1,2,3],[1,2 ])
,(1,2,[1,2,3],[1, 3])
,(1,2,[1,2,3],[ 2,3])
]
[ (1,[[1,2 ]
,[1 ,3]
,[ 2,3]
])
,(2,[[1,2 ]
,[1 ,3]
,[ 2,3]
])
] ))
-- This passes, but is crazy slow
,TestLabel "two observer, nine participant (3 groups)" (
TestCase ( test_quorum_creation [ (1,2,[1,2,3,4,5,6,7 ],[1,2,3,4,5,6 ])
,(1,2,[1,2,3,4,5,6, 8 ],[1,2,3,4,5,6 ])
,(1,2,[1,2,3,4,5,6, 9],[1,2,3,4,5,6 ])
,(1,2,[1,2,3,4, 7,8,9],[1,2,3, 7,8,9])
,(1,2,[1,2,3, 5, 7,8,9],[1,2,3, 7,8,9])
,(1,2,[1,2,3, 6,7,8,9],[1,2,3, 7,8,9])
,(1,2,[1, 4,5,6,7,8,9],[ 4,5,6,7,8,9])
,(1,2,[ 2, 4,5,6,7,8,9],[ 4,5,6,7,8,9])
,(1,2,[ 3,4,5,6,7,8,9],[ 4,5,6,7,8,9])
]
[ (1,[[1,2,3,4,5,6 ]
,[1,2,3, 7,8,9]
,[ 4,5,6,7,8,9]
])
,(2,[[1,2,3,4,5,6 ]
,[1,2,3, 7,8,9]
,[ 4,5,6,7,8,9]
])
] ))
,TestLabel "three observer, three participant" (
TestCase ( test_quorum_creation [ (1,2,[1,2,3],[1,2 ])
,(1,2,[1,2,3],[1, 3])
,(1,2,[1,2,3],[ 2,3])
,(1,3,[1,2,3],[1,2 ])
,(1,3,[1,2,3],[1, 3])
,(1,3,[1,2,3],[ 2,3])
]
[ (1,[[1,2 ]
,[1 ,3]
,[ 2,3]
])
,(2,[[1,2 ]
,[1 ,3]
,[ 2,3]
])
,(3,[[1,2 ]
,[1 ,3]
,[ 2,3]
])
] ))
,TestLabel "three observer, three participant asymmetric" (
TestCase ( test_quorum_creation [ (1,2,[1,2,3],[1,2 ])
,(1,2,[1,2,3],[ 2,3])
,(1,3,[1,2,3],[1, 3])
,(1,3,[1,2,3],[ 2,3])
]
[ (1,[[1,2 ]
,[1 ,3]
,[ 2,3]
])
,(2,[[1,2 ]
,[ 2,3]
])
,(3,[[1 ,3]
,[ 2,3]
])
] ))
]
|
isheff/hetcons
|
test/Test/Quorums.hs
|
Haskell
|
mit
| 11,892
|
-- | Framebuffers. You can render on them.
--
-- If you come from the OpenGL world, for simplicity, we have combined the
-- concept of draw buffers and color attachments. Nth color attachment is bound
-- exactly to Nth draw buffer. Caramia only talks about draw buffers.
--
-- <https://www.opengl.org/wiki/Framebuffer_Object>
--
-- Either OpenGL 3.0 or @ GL_ARB_framebuffer_object @ is required for this
-- module.
--
{-# LANGUAGE NoImplicitPrelude, ViewPatterns, DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
module Graphics.Caramia.Framebuffer
(
-- * Creating framebuffers
newFramebuffer
, Framebuffer()
-- * Specifying texture targets
, frontTextureTarget
, mipmapTextureTarget
, layerTextureTarget
, TextureTarget()
, Attachment(..)
-- * Size query
, getDimensions
-- * Clearing framebuffers
, clear
, Clearing(..)
, clearing
-- * Special framebuffers
, screenFramebuffer
-- * Hardware limits
, getMaximumDrawBuffers
-- * Views
, viewTargets )
where
import Control.Monad.Catch
import Control.Monad.IO.Class
import Data.Bits
import qualified Data.IntSet as IS
import Data.List ( nub )
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
import Foreign.Storable
import GHC.Float
import Graphics.Caramia.Color
import Graphics.Caramia.Context
import Graphics.Caramia.Framebuffer.Internal
import Graphics.Caramia.ImageFormats
import Graphics.Caramia.Internal.Exception
import Graphics.Caramia.Internal.OpenGLCApi
import Graphics.Caramia.Prelude
import Graphics.Caramia.Resource
import Graphics.Caramia.Texture
import qualified Graphics.Caramia.Texture.Internal as Tex
import Graphics.GL.Ext.ARB.FramebufferObject
-- | Returns the screen framebuffer.
--
-- Note that all `screenFramebuffer`s are equal to each other with `Eq`, even
-- those in unrelated Caramia contexts.
--
-- This makes it easy to check if any framebuffer happens to be the screen
-- framebuffer.
screenFramebuffer :: Framebuffer
screenFramebuffer = ScreenFramebuffer
-- | Make a texture target that is the \"front\" of the given texture.
--
-- This is the most common use case. \"front\" means the first texture in a
-- texture array and the base layer mipmap level.
frontTextureTarget :: Tex.Texture -> TextureTarget
frontTextureTarget tex = TextureTarget {
attacher = \attachment ->
withResource (Tex.resource tex) $ \(Tex.Texture_ texname) ->
glFramebufferTexture
GL_DRAW_FRAMEBUFFER
attachment
texname
0
, texture = tex }
-- | Map a specific mipmlayer from a texture.
mipmapTextureTarget :: Tex.Texture
-> Int -- ^ Which mipmap layer?
-> TextureTarget
mipmapTextureTarget tex mipmap_layer = TextureTarget {
attacher = \attachment ->
withResource (Tex.resource tex) $ \(Tex.Texture_ texname) ->
glFramebufferTexture
GL_DRAW_FRAMEBUFFER
attachment
texname
(safeFromIntegral mipmap_layer)
, texture = tex }
-- | Map a specific mipmap layer of a specific layer in a 3D or array texture.
layerTextureTarget :: Tex.Texture
-> Int -- ^ Which mipmap layer?
-> Int -- ^ Which topological layer?
-> TextureTarget
layerTextureTarget tex mipmap_layer topo_layer = TextureTarget {
attacher = \attachment ->
withResource (Tex.resource tex) $ \(Tex.Texture_ texname) ->
glFramebufferTextureLayer
GL_DRAW_FRAMEBUFFER
attachment
texname
(safeFromIntegral mipmap_layer)
(safeFromIntegral topo_layer)
, texture = tex }
toConstantA :: Attachment -> GLenum
toConstantA (ColorAttachment x) = GL_COLOR_ATTACHMENT0 + fromIntegral x
toConstantA DepthAttachment = GL_DEPTH_ATTACHMENT
toConstantA StencilAttachment = GL_STENCIL_ATTACHMENT
-- | Creates a new framebuffer.
newFramebuffer :: MonadIO m
=> [(Attachment, TextureTarget)]
-> m Framebuffer
newFramebuffer targets
| null targets =
error "newFramebuffer: no texture targets specified."
| nub (fmap fst targets) /= fmap fst targets =
error "newFramebuffer: there are duplicate attachments."
| otherwise = liftIO $ mask_ $
checkOpenGLOrExtensionM (OpenGLVersion 3 0)
"GL_ARB_framebuffer_object"
gl_ARB_framebuffer_object $ do
max_bufs <- getMaximumDrawBuffers
targetsSanityCheck max_bufs
res <- newResource (creator max_bufs)
deleter
(return ())
index <- newUnique
return Framebuffer { resource = res
, ordIndex = index
, viewTargets = targets
, dimensions = calculatedDimensions
, binder = withThisFramebuffer res
, setter = setThisFramebuffer res }
where
calculatedDimensions@(fw, fh) =
foldl' (\(lowest_w, lowest_h) (w, h) ->
(min lowest_w w, min lowest_h h))
(maxBound, maxBound)
(fmap (\(snd -> tex) ->
(viewWidth $ texture tex, viewHeight $ texture tex))
targets)
creator max_bufs =
bracketOnError mglGenFramebuffer
mglDeleteFramebuffer $ \fbuf_name -> do
withBoundDrawFramebuffer fbuf_name $ do
forM_ targets $ \(index, tex) ->
attacher tex (toConstantA index)
allocaArray max_bufs $ \buf_ptr -> do
forM_ [0..max_bufs-1] $ \bufnum ->
pokeElemOff buf_ptr bufnum $
if IS.member bufnum color_attachments
then GL_COLOR_ATTACHMENT0 +
fromIntegral bufnum
else GL_NONE
glDrawBuffers (fromIntegral max_bufs) buf_ptr
return $ Framebuffer_ fbuf_name
color_attachments :: IS.IntSet
color_attachments =
foldl' folder IS.empty (fmap fst targets)
where
folder :: IS.IntSet -> Attachment -> IS.IntSet
folder accum (ColorAttachment x) = IS.insert x accum
folder accum _ = accum
deleter (Framebuffer_ fbuf_name) =
mglDeleteFramebuffer fbuf_name
targetsSanityCheck max_bufs = forM_ targets $ \(attachment, target) -> do
let format = Tex.imageFormat $ Tex.viewSpecification $ texture target
unless (isRenderTargettable format) $
error $ "newFramebuffer: cannot render to " <> show format
case attachment of
ColorAttachment x | x < 0 || x >= max_bufs ->
error $ "newFramebuffer: color attachment " <> show x <>
" is out of range. Valid range is [0.." <>
show (max_bufs-1) <> "]."
ColorAttachment _ | not (isColorFormat format) ->
error $ "newFramebuffer: " <> show format <> " is not a " <>
"color format but was attempted to be attached to " <>
"attachment " <> show attachment <> "."
DepthAttachment | not (hasDepthComponent format) ->
error $ "newFramebuffer: " <> show format <> " has no " <>
"depth component but was attempted to be attached " <>
"to depth attachment."
StencilAttachment | not (hasStencilComponent format) ->
error $ "newFramebuffer: " <> show format <> " has no " <>
"stencil component but was attempted to be " <>
"attached to stencil attachment."
_ -> return ()
setThisFramebuffer res = do
withResource res $ \(Framebuffer_ fbuf_name) ->
glBindFramebuffer GL_FRAMEBUFFER fbuf_name
glViewport 0 0 (fromIntegral fw) (fromIntegral fh)
withThisFramebuffer res action = mask $ \restore -> do
old_draw_framebuffer <- gi GL_DRAW_FRAMEBUFFER_BINDING
old_read_framebuffer <- gi GL_READ_FRAMEBUFFER_BINDING
(x, y, w, h) <- liftIO $ allocaArray 4 $ \viewport_ptr -> do
glGetIntegerv GL_VIEWPORT viewport_ptr
x <- peekElemOff viewport_ptr 0
y <- peekElemOff viewport_ptr 1
w <- peekElemOff viewport_ptr 2
h <- peekElemOff viewport_ptr 3
return (x, y, w, h)
withResource res $ \(Framebuffer_ fbuf_name) -> do
glBindFramebuffer GL_FRAMEBUFFER fbuf_name
glViewport 0 0 (fromIntegral fw) (fromIntegral fh)
finally (restore action) $ do
glViewport x y w h
glBindFramebuffer GL_DRAW_FRAMEBUFFER old_draw_framebuffer
glBindFramebuffer GL_READ_FRAMEBUFFER old_read_framebuffer
-- | Returns the maximum number of draw buffers in the current context.
--
-- Almost all GPUs in the last few years have at least 8.
getMaximumDrawBuffers :: MonadIO m => m Int
getMaximumDrawBuffers = do
_ <- currentContextID
-- number of draw buffers
num_drawbuffers <- gi GL_MAX_DRAW_BUFFERS
-- number of attachments
num_attachments <- gi GL_MAX_COLOR_ATTACHMENTS
return (fromIntegral $ min num_drawbuffers num_attachments)
-- | Specifies what to clear in a `clear` invocation.
--
-- Use `clearing` smart constructor instead for forward-compatibility.
--
-- Each member of this data type is a `Maybe` value; if any value is `Just`
-- then that value is cleared, otherwise it is not touched.
data Clearing = Clearing
{ clearDepth :: !(Maybe Float)
-- ^ Clear depth buffer to this value.
, clearStencil :: !(Maybe Int32)
-- ^ Clear stencil buffer to this value.
, clearColor :: !(Maybe Color)
-- ^ Clear (all) color buffers to some color.
}
deriving ( Eq, Ord, Show, Read, Typeable )
-- TODO: selective clearing for different color buffers.
-- | Smart constructor for `Clearing`. All members are `Nothing`.
clearing :: Clearing
clearing = Clearing { clearDepth = Nothing
, clearStencil = Nothing
, clearColor = Nothing }
-- | Clears values in a framebuffer.
clear :: MonadIO m => Clearing -> Framebuffer -> m ()
clear clearing fbuf = liftIO $ withBinding fbuf $ mask_ $
recColor (clearColor clearing)
where
bits = maybe 0 (const GL_COLOR_BUFFER_BIT) (clearColor clearing) .|.
maybe 0 (const GL_DEPTH_BUFFER_BIT) (clearDepth clearing) .|.
maybe 0 (const GL_STENCIL_BUFFER_BIT) (clearStencil clearing)
recColor Nothing = recDepth (clearDepth clearing)
recColor (Just (viewRgba -> (r, g, b, a))) =
allocaArray 4 $ \ptr -> do
glGetFloatv GL_COLOR_CLEAR_VALUE ptr
glClearColor r g b a
recDepth (clearDepth clearing)
nr <- peekElemOff ptr 0
ng <- peekElemOff ptr 1
nb <- peekElemOff ptr 2
na <- peekElemOff ptr 3
glClearColor nr ng nb na
recDepth Nothing = recStencil (clearStencil clearing)
recDepth (Just depth) = do
old_depth <- alloca $ \ptr ->
glGetDoublev GL_DEPTH_CLEAR_VALUE ptr *> peek ptr
glClearDepth $ float2Double depth
recStencil (clearStencil clearing)
glClearDepth old_depth
recStencil Nothing = glClear bits
recStencil (Just stencil) = do
old_stencil <- alloca $ \ptr ->
glGetIntegerv GL_STENCIL_CLEAR_VALUE ptr *> peek ptr
glClearStencil (safeFromIntegral stencil)
glClear bits
glClearStencil old_stencil
|
Noeda/caramia
|
src/Graphics/Caramia/Framebuffer.hs
|
Haskell
|
mit
| 11,943
|
module GiveYouAHead.Help
(
helpInfo
) where
import System.Environment(getProgName)
import GiveYouAHead.Version(gyahver)
helpInfo :: IO()
helpInfo = getProgName >>= (putStrLn.unlines.helpAll)
where
helpAll pN = [
"\n",
"GiveYouAHead\t\t\t version "++gyahver,
"\tUsage :",
"The details of usage are in the documents.And you can find more information at this repo's README.md . The links are at the bottom.\n",
"\tTo create a new file",
"\t\t"++pN++" new (optional){-t [template] -d [directory]} [id/name] [the list of import]",
"\n",
"\tTo initialize a new \"project\"",
"\t\t"++pN++" init (optional){-d [directory]}",
"\n",
"\tTo build something",
"\t\t"++pN++" build (optional){-t [template] -d [directory]} [the list of id/name]",
"\n",
"\tTo clean the temporary files",
"\t\t"++pN++" clean (optional){-t [template]}",
"\n",
"\tTo configure",
"\t\tTo list all the CommandMap in the .gyah",
"\t\t"++pN++" config listcm",
"\t\tTo add CommandMaps to a cm-file",
"\t\t"++pN++" config addcm [flie-name] [cm-lists]",
"\t\tTo delete (a) CommandMap(s) ",
"\t\t"++pN++" config delcm [the ids' list of the cm]",
"\t\tTo change CommandMap's status",
"\t\t"++pN++" config turncm [file-name] [the list of ids] ",
"\t\tTo change a cm's text",
"\t\t"++pN++" config chcm [file-name] [id] [text]",
"\n\n",
"\tGiveYouAHead's repo : https://github.com/Qinka/GiveYouAHead",
"\tGiveYouAHead had upload to Havkage: http://hackage.haskell.org",
"\tBug report: https://github.com/Qinka/GiveYouAHead/issues",
"\tLICENSE? BSD3",
""
]
|
Qinka/GiveYouAHead
|
lib/GiveYouAHead/Help.hs
|
Haskell
|
mit
| 1,978
|
{-# LANGUAGE OverloadedStrings #-}
module CoinApi.Types.Period where
import CoinApi.Types.Internal
data Period = Period { period_id :: !Text
, length_seconds :: !Int
, length_months :: !Int
, unit_count :: !Int
, unit_name :: !Text
, display_name :: !Text }
deriving (Show, Eq)
instance FromJSON Period where
parseJSON = withObject "Period" $ \o -> Period
<$> o .: "period_id"
<*> o .: "length_seconds"
<*> o .: "length_months"
<*> o .: "unit_count"
<*> o .: "unit_name"
<*> o .: "display_name"
|
coinapi/coinapi-sdk
|
data-api/haskell-rest/CoinApi/Types/Period.hs
|
Haskell
|
mit
| 877
|
module App where
import Network.Wai
import Network.Wai.Handler.Warp
import Servant.Server
-- import qualified Data.ByteString as B
import Network.Wai.Middleware.RequestLogger
import Greet
import Handlers
haskapi :: Application
haskapi = serve haskApi handlers
-- Run the server.
--
-- 'run' comes from Network.Wai.Handler.Warp
runTestServer :: Port -> IO ()
runTestServer port = run port $ logStdout haskapi
|
mooreniemi/haskapi
|
app.hs
|
Haskell
|
mit
| 413
|
{-# LANGUAGE
TemplateHaskell,
TypeOperators #-}
module Object.Templates(
makeName,
makeObject
) where
import Object.Letters
import Object.Types
import Prelude hiding ((.))
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import Data.Char
import Data.Maybe
-- |
-- takes lower case 'foo' and makes
-- 'type Foo = Method (T_f,T_o,T_o)'
-- 'foo = Method (T_f,T_o,T_o) :: Foo'
makeName :: String -> Q [Dec]
makeName name = fst `fmap` makeName' name
makeName' :: String -> Q ([Dec],(Name,Name))
makeName' name = go where
go
| [] <- name = fail "can't make empty variable"
| not $ isLower $ head name = fail $ name ++ ": does not start with a lower letter"
| (first:rest) <- name = do
typeTuple <- mapM typeCon name
dataTuple <- mapM dataCon name
typeName <- newName $ [toUpper first] ++ rest ++ ['_']
dataName <- newName $ [first] ++ rest
typ <- [t| Method $(return $ foldl AppT (TupleT (length typeTuple)) typeTuple) |]
dat <- [| Method $(return $ (TupE dataTuple)) :: $(return $ ConT typeName) |]
let typeDecl = TySynD typeName [] typ
let dataDecl = ValD (VarP dataName) (NormalB dat) []
return ([typeDecl,dataDecl],(typeName,dataName))
typeCon c = do
Just res <- lookupTypeName $ "T_" ++ [c]
return $ ConT res
dataCon c = do
Just res <- lookupValueName $ "T_" ++ [c]
return $ ConE res
-- |
-- returns (typeName, variableNames, and fields)
getInfo :: Info -> Q (Name, [Name], [VarStrictType])
getInfo (TyConI (DataD context typeName vars [RecC constrName fields] _)) = go where
go = return (typeName, map getVar vars, fields)
getVar (PlainTV n) = n
getVar (KindedTV n _) = n
getInfo _ = fail $ "type needs to have a single constructor record type"
getFieldName (fieldName,strictness,type')
| nameBase fieldName !! 0 /= '_' || not (isLower $ nameBase fieldName !! 1)
= fail $ show fieldName ++
": all fieldNames must commence with a '_' \
\and continue with a lower case letter"
| otherwise = nameBase fieldName
-- |
-- takes a Type with one record constructor
-- 'setGetFunctional \'\'Foo'
-- and produces
-- set and get instances for all fields
makeObject :: Name -> Q [Dec]
makeObject name = go name where
go :: Name -> Q [Dec]
go obj = do
(name, vars, fields) <- reify name >>= getInfo
let objType = foldl AppT (ConT name) (VarT `fmap` vars)
concat `fmap` (sequence $ makeField name vars `fmap` fields)
-- "(Object.Example.Foo,[x_1627454179],[(Object.Example._bar,NotStrict,ConT GHC.Types.Int),(Object.Example._baz,NotStrict,ConT GHC.Types.Char),(Object.Example._blub,NotStrict,VarT x_1627454179)])"
makeField :: Name -> [Name] -> VarStrictType -> Q [Dec]
makeField _ _ (name,_,_) | '_' /= head (nameBase name) = fail $ show name ++ " did not start with underscore"
makeField name vars (fName, _, fType) = do
(decs1,(typeName,dataName)) <- makeName' (tail $ nameBase fName)
let objType = foldl AppT (ConT name) (VarT `fmap` vars)
actionInst <- [d|
instance (value ~ $(return fType)) => Action $(return objType) $(return $ ConT typeName) value where
object . _ = $(return $ VarE fName) object
|]
matchType <- [t| $(return $ ConT typeName) := $(return $ VarT $ mkName "value") |]
actionSetInst <- [d|
instance (value ~ $(return fType), object ~ $(return objType)) => Action $(return objType) $(return matchType) object where
object . ( _ := v) = $(recUpdE [e|object|] [return (fName, VarE $ mkName "v")])
|]
return $ actionInst ++ actionSetInst ++ decs1
|
yokto/Object
|
Object/Templates.hs
|
Haskell
|
apache-2.0
| 3,482
|
import System.Random
-- import Debug.Trace -- uncomment for tracing
removeAt :: Int -> [a] -> (a, [a])
removeAt 1 (x:xs) = (x,xs)
removeAt n (x:xs) = (a,x:b)
where (a,b) = removeAt (n-1) xs
rnd_select :: [a] -> Int -> IO [a]
rnd_select _ 0 = return []
rnd_select [] _ = return []
rnd_select xs n = randomRIO(1, length xs) >>=
-- (\ i -> return (trace ("random i = " ++ show i) i)) >>=
(\ i -> return $ removeAt i xs) >>=
(\ (x, xs) -> (rnd_select xs (n-1) >>= (\ xs -> return $ x : xs)))
|
alephnil/h99
|
23.hs
|
Haskell
|
apache-2.0
| 502
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Openshift.V1.ClusterNetworkList where
import GHC.Generics
import Data.Text
import Openshift.Unversioned.ListMeta
import Openshift.V1.ClusterNetwork
import qualified Data.Aeson
-- |
data ClusterNetworkList = ClusterNetworkList
{ kind :: Maybe Text -- ^ Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds
, apiVersion :: Maybe Text -- ^ APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources
, metadata :: Maybe ListMeta -- ^
, items :: [ClusterNetwork] -- ^ list of cluster networks
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON ClusterNetworkList
instance Data.Aeson.ToJSON ClusterNetworkList
|
minhdoboi/deprecated-openshift-haskell-api
|
openshift/lib/Openshift/V1/ClusterNetworkList.hs
|
Haskell
|
apache-2.0
| 1,235
|
module Language.Livescript.Lexer (
lexeme
, identifier
, reserved
, operator
, reservedOp
, charLiteral
, stringLiteral
, natural
, integer
, float
, naturalOrFloat
, decimal
, hexadecimal
, octal
, symbol
, whiteSpace
, parens
, braces
, brackets
, squares
, semi
, comma
, colon
, dot
, identifierStart
) where
import Data.Text (Text)
import Prelude hiding (lex)
import Text.Parsec hiding (State)
import Text.Parsec.Text ()
import qualified Text.Parsec.Token as T
import Language.Livescript.Parser.Type
------------------------------------------------------------------------
identifierStart :: Parser Char
identifierStart = letter <|> oneOf "$_"
livescriptDef :: T.GenLanguageDef Text () ParserState
livescriptDef = T.LanguageDef {
T.caseSensitive = True
, T.commentStart = "/*"
, T.commentEnd = "*/"
, T.commentLine = "#"
, T.nestedComments = False
, T.identStart = identifierStart
, T.identLetter = alphaNum <|> oneOf "$_-"
, T.opStart = oneOf "=:+-"
, T.opLetter = oneOf "="
, T.reservedNames = names
, T.reservedOpNames = ops
}
where
names = []
ops = ["=",":=","+","-"]
lex :: T.GenTokenParser Text () ParserState
lex = T.makeTokenParser livescriptDef
-- everything but commaSep and semiSep
identifier :: Parser String
identifier = T.identifier lex
reserved :: String -> Parser ()
reserved = T.reserved lex
operator :: Parser String
operator = T.operator lex
reservedOp :: String -> Parser ()
reservedOp = T.reservedOp lex
charLiteral :: Parser Char
charLiteral = T.charLiteral lex
stringLiteral :: Parser String
stringLiteral = T.stringLiteral lex
natural :: Parser Integer
natural = T.natural lex
integer :: Parser Integer
integer = T.integer lex
float :: Parser Double
float = T.float lex
naturalOrFloat :: Parser (Either Integer Double)
naturalOrFloat = T.naturalOrFloat lex
decimal :: Parser Integer
decimal = T.decimal lex
hexadecimal :: Parser Integer
hexadecimal = T.hexadecimal lex
octal :: Parser Integer
octal = T.octal lex
symbol :: String -> Parser String
symbol = T.symbol lex
whiteSpace :: Parser ()
whiteSpace = T.whiteSpace lex
parens :: Parser a -> Parser a
parens = T.parens lex
braces :: Parser a -> Parser a
braces = T.braces lex
squares :: Parser a -> Parser a
squares = T.squares lex
semi :: Parser String
semi = T.semi lex
comma :: Parser String
comma = T.comma lex
colon :: Parser String
colon = T.colon lex
dot :: Parser String
dot = T.dot lex
brackets :: Parser a -> Parser a
brackets = T.brackets lex
lexeme :: Parser a -> Parser a
lexeme = T.lexeme lex
|
jystic/language-livescript
|
src/Language/Livescript/Lexer.hs
|
Haskell
|
apache-2.0
| 2,778
|
{- |
Module : Codec.Goat.Util
Description : Various utility functions
Copyright : (c) Daniel Lovasko, 2016-2017
License : BSD3
Maintainer : Daniel Lovasko <daniel.lovasko@gmail.com>
Stability : stable
Portability : portable
Various utility functions used throughout the codebase.
-}
module Codec.Goat.Util
( aiGetByteString
, aiPutByteString
, bool
, first
, fromBools
, inBounds
, packBits
, select
, sub
, toBools
, unpackBits
) where
import Data.Bits
import Data.Int
import Data.List.Split (chunksOf)
import Data.Serialize
import Data.Word
import qualified Data.ByteString as B
-- | Check whether a value falls between the bounds (inclusive).
inBounds :: (Ord a)
=> (a, a) -- ^ bounds
-> a -- ^ value
-> Bool -- ^ decision
inBounds (lo, hi) x = lo <= x && x <= hi
-- | Correct subtraction of two unsigned integers.
sub :: Word32 -- ^ first word
-> Word32 -- ^ second word
-> Int64 -- ^ result
sub a b = fromIntegral a - fromIntegral b
-- | Pack a list of bits into a more compact form.
packBits :: [Bool] -- ^ bits
-> B.ByteString -- ^ bytestring
packBits xs = B.pack $ map fromBools (chunksOf 8 xs)
-- | Unpack a compact block of bytes into a list of bools.
unpackBits :: B.ByteString -- ^ bits
-> [Bool] -- ^ bytestring
unpackBits b = concatMap toBools (B.unpack b)
-- | Functional equivalent of the 'if/then/else' construct.
bool :: a -- ^ True option
-> a -- ^ False option
-> Bool -- ^ bool
-> a -- ^ result
bool x _ True = x
bool _ y False = y
-- | Convert a Bits instance into a list of bools.
toBools :: (FiniteBits b)
=> b -- ^ Bits instance
-> [Bool] -- ^ bits
toBools bits = map (testBit bits) [0..finiteBitSize bits-1]
-- | Convert a list of bools into a Bits instance.
fromBools :: (Num b, FiniteBits b)
=> [Bool] -- ^ bits
-> b -- ^ Bits instance
fromBools = foldr (\b i -> bool (bit 0) 0 b .|. shift i 1) 0
-- | Select only certain elements from the list based on the boolean values.
select :: [a] -- ^ list
-> [Bool] -- ^ presence flags
-> [a] -- ^ filtered list
select [] _ = []
select _ [] = []
select (x:xs) (b:bs) = bool (x : select xs bs) (select xs bs) b
-- | Apply a function to the first element of a pair.
first :: (a -> b) -- ^ function
-> (a, x) -- ^ old pair
-> (b, x) -- ^ new pair
first f (a, x) = (f a, x)
-- | Architecture-independent serialization of a strict ByteString.
aiPutByteString :: B.ByteString -- ^ bytestring to parse
-> Put -- ^ writer
aiPutByteString bs = putListOf putWord8 (B.unpack bs)
-- | Architecture-independent deserialization of a lazy ByteString.
aiGetByteString :: Get B.ByteString -- ^ reader
aiGetByteString = B.pack <$> getListOf getWord8
|
lovasko/goat
|
src/Codec/Goat/Util.hs
|
Haskell
|
bsd-2-clause
| 2,857
|
{-# LANGUAGE CPP, MultiParamTypeClasses, OverloadedStrings #-}
module HTIG.Session
( HSession(HSession)
) where
import Control.Applicative ((<$>))
import Control.Monad (forM_, when)
import Data.Binary (decodeFile, encodeFile)
import Data.List (delete)
import Data.Maybe (isJust)
import System.Directory (doesFileExist)
import System.FilePath ((</>))
import qualified Data.ByteString.Char8 as B
import qualified Data.Map as Map
import qualified Data.Set as Set
import HTIG.Core
import HTIG.Channel.OAuth
import HTIG.Database
import HTIG.IRCServer
import HTIG.TwitterAPI
import HTIG.Utils
#include "../debug.hs"
data HSession = HSession
instance ISession HSession GlobalState SessionState where
handleClose _ = do
whenHasNickAndUser $ do
Just nick <- sNick <$> getLocal
chans <- sJoinedChannels <$> getLocal
forM_ chans $ \chan -> quitChannel chan (Nick nick) (Just "Connection closed")
killAllH
whenM (isJust . sNick <$> getLocal) $ do
Just nick <- sNick <$> getLocal
modifyGlobal $ \g ->
let ns = gsNicks g
in g { gsNicks = delete nick ns }
handlePing _ sn msn = writeServerCommand $ PongCmd sn msn
handlePass _ p = modifyLocal $ \s -> s { sPassword = Just p }
handleNick _ n _ = do
debug n
ret <- modifyGlobal' $ \g ->
let ns = gsNicks g
in if n `elem` ns
then (g, False)
else (g { gsNicks = n:ns }, True)
if ret
then do
modifyLocal $ \s -> s { sNick = Just n }
whenHasNickAndUser $ do
debug "nick and user sended"
sendWelcome
doOAuthAuthentication
openUserDatabase
runSessionInitHook
else do
writeServerError eRR_NICKNAMEINUSE $ "nickname \"" ++. n ++. "\" already exists"
closeConn'
handleUser _ username hostname servername realname = do
modifyLocal $ \s -> s { sUserName = Just username
, sHostName = Just hostname
, sServerName = Just servername
, sRealName = Just realname
}
whenHasNickAndUser $ do
debug "nick and user sended"
sendWelcome
doOAuthAuthentication
openUserDatabase
runSessionInitHook
handleJoin _ chans = whenOAuthVerified $ do
debug chans
Just nick <- sNick <$> getLocal
forM_ (Map.keys chans) $ \cname -> do
mchan <- lookupJoinedChan cname
case mchan of
Just chan -> joinChannel chan (Nick nick)
Nothing -> createNewChannel cname
-- TODO: implement
--handleKick _ chans nicks marg = undefined
handlePrivmsg _ targets arg = whenOAuthVerified $ handlePrivmsg'
where
handlePrivmsg'
| "\x01\&ACTION " `B.isPrefixOf` arg && "\x01" `B.isSuffixOf` arg =
doAction targets $ stripAction arg
| otherwise = do
Just nick <- sNick <$> getLocal
chans <- sJoinedChannels <$> getLocal
forM_ chans $ \c ->
when (channelName c `Set.member` targets) $
privmsgChannel c (Nick nick) arg
stripAction = B.init . B.tail . B.dropWhile (/= ' ')
handlePart _ chans marg = whenHasNickAndUser $ do
debug chans
Just nick <- sNick <$> getLocal
forM_ (Set.toList chans) $ \cname -> do
mchan <- lookupJoinedChan cname
case mchan of
Just chan -> do
partChannel chan (Nick nick)
modifyLocal $ \s -> s { sJoinedChannels = filter ((/= cname) . channelName) $ sJoinedChannels s }
writeConn' $ Message (Just $ Nick nick) $ PartCmd (Set.singleton cname) Nothing
debug ("part from" :: String, cname)
Nothing -> return ()
-- TODO: implement
--handleCommand "INVITE" _ chans arg = undefined
lookupJoinedChan :: ChannelName -> HTIG (Maybe HChannel)
lookupJoinedChan cname = do
chans <- sJoinedChannels <$> getLocal
case filter ((cname == ) . channelName) chans of
chan:_ -> return $ Just chan
[] -> return Nothing
createNewChannel :: ChannelName -> HTIG ()
createNewChannel cname = do
Just nick <- sNick <$> getLocal
mchanf <- lookupChannelFactory cname
case mchanf of
Just chanf -> do
chan <- chanf cname
modifyLocal $ \s -> s { sJoinedChannels = chan : sJoinedChannels s }
debug ("create channel for" :: String, cname)
joinChannel chan (Nick nick)
Nothing -> do
-- TODO: return proper error
debug ("no channel found" :: String, cname)
return ()
doAction :: Set.Set TargetName -> B.ByteString -> HTIG ()
doAction ts arg = do
debug (ts, arg)
let (actName, arg') = B.break (== ' ') arg
acts <- actions . gsHConfig <$> getGlobal
case lookup actName acts of
Just act -> act ts arg'
Nothing -> showActionHelp ts
showActionHelp :: Set.Set TargetName -> HTIG ()
showActionHelp ts = do
actNames <- map fst . actions . gsHConfig <$> getGlobal
writeServerCommand $ NoticeCmd ts "[htig] CTCP ACTION COMMANDS:"
forM_ actNames $ \a ->
writeServerCommand $ NoticeCmd ts a
whenHasNickAndUser :: HTIG () -> HTIG ()
whenHasNickAndUser f = do
mn <- sNick <$> getLocal
mu <- sUserName <$> getLocal
when (isJust $ mn >> mu) f
whenOAuthVerified :: HTIG () -> HTIG ()
whenOAuthVerified f = whenM (isJust . sToken <$> getLocal) f
doOAuthAuthentication :: HTIG ()
doOAuthAuthentication = do
mtok <- loadTwitterToken
case mtok of
Just tok -> do
modifyLocal $ \s -> s { sToken = Just tok }
Nothing -> do
Just nick <- sNick <$> getLocal
chan <- oauthChannel "#oauth"
modifyLocal $ \s -> s { sJoinedChannels = chan : sJoinedChannels s }
joinChannel chan (Nick nick)
runSessionInitHook :: HTIG ()
runSessionInitHook = sessionInitHook =<< gsHConfig <$> getGlobal
openUserDatabase :: HTIG ()
openUserDatabase = do
cp <- getUserCacheDir
let dp = cp </> "cache.sqlite"
debug ("opening database" :: String, dp)
conn <- liftIO $ openDatabase dp
modifyLocal $ \s -> s { sDBConn = Just conn }
loadTwitterToken :: HTIG (Maybe Token)
loadTwitterToken = do
makeUserCacheDir
cpath <- getUserCacheDir
let tpath = cpath </> "token"
fexists <- liftIO $ doesFileExist tpath
if fexists
then Just <$> liftIO (decodeFile tpath)
else return Nothing
|
nakamuray/htig
|
HTIG/Session.hs
|
Haskell
|
bsd-3-clause
| 6,853
|
module Str(
Str,
linesCR, S.stripPrefix,
readFileUTF8,
S.null, S.isPrefixOf, S.drop, S.span, S.length, S.toList, S.all, S.uncons,
ugly, showLength
) where
import qualified Foundation as S
import qualified Foundation.String as S
import qualified Foundation.IO as S
import Data.Tuple.Extra
type Str = S.String
linesCR :: Str -> [Str]
linesCR = S.lines
showLength x = show x
ugly :: S.Integral a => Integer -> a
ugly = S.fromInteger
readFileUTF8 :: FilePath -> IO Str
readFileUTF8 = fmap (fst3 . S.fromBytes S.UTF8) . S.readFile . S.fromString
|
ndmitchell/weeder
|
str/Str-Foundation.hs
|
Haskell
|
bsd-3-clause
| 573
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TupleSections #-}
module Game where
import Prelude hiding (lookup)
import qualified Data.Map.Strict as M
import Data.IORef
import Data.Maybe
import Control.Monad
import Linear.V2
import Types
lookup :: Ord k => M.Map k v -> k -> Maybe v
lookup = flip M.lookup
initialGameState :: GameState
initialGameState = GameState (M.fromList $ whites ++ blacks) Nothing Whites
where whites = map (,White) [ V2 1 0, V2 3 0, V2 5 0, V2 7 0
, V2 0 1, V2 2 1, V2 4 1, V2 6 1
, V2 1 2, V2 3 2, V2 5 2, V2 7 2 ]
blacks = map (,Black) [ V2 0 5, V2 2 5, V2 4 5, V2 6 5
, V2 1 6, V2 3 6, V2 5 6, V2 7 6
, V2 0 7, V2 2 7, V2 4 7, V2 6 7 ]
--where whites = [(V2 4 3, WhiteQueen), (V2 4 7, WhiteQueen)]
-- blacks = map (,Black) [V2 2 5, V2 6 1, V2 5 6]
updateGameState :: IORef GameState -> V2 Int -> IO ()
updateGameState gameStateRef p = do
GameState brd sf trn <- readIORef gameStateRef
let pm = possibleMoves trn brd
save b s t = writeIORef gameStateRef $ GameState b s t
case sf >>= lookup pm >>= findMove p of
Just m -> save (movePawn brd (fromJust sf) m) Nothing (nextTurn trn)
_ -> save brd (Just p) trn
possibleMoves :: Turn -> Board -> PossibleMoves
possibleMoves trn brd = prioritize $ M.mapWithKey allFieldMoves $ turnFilter trn brd
where allFieldMoves p t = fieldMoves p t ++ fieldCaptures p t
prioritize moves = M.filter (not . null)
$ M.map (filter $ \x -> priority x >= maxPriority) moves
where maxPriority = maximum' $ M.map (maximum' . map priority) moves
maximum' l = if null l then 0 else maximum l
priority (Ordinary _) = 1
priority (Capture []) = -1
priority (Capture ps) = 1 + length ps
allowedMove a@(V2 ax ay) = ax `elem` [0..7] && ay `elem` [0..7] && isNothing (M.lookup a brd)
allDirections = [V2 1 1, V2 (-1) 1, V2 (-1) (-1), V2 1 (-1)]
fieldMoves p t = map Ordinary $ filter allowedMove $ uncurry (directional p brd takeWhile) $ case t of
White -> ([V2 1 1, V2 (-1) 1] , 1)
WhiteQueen -> (allDirections , 6)
Black -> ([V2 (-1) (-1), V2 1 (-1)], 1)
BlackQueen -> (allDirections , 6)
fieldCaptures p t = case t of
White -> captures p [Black, BlackQueen] 1
WhiteQueen -> captures p [Black, BlackQueen] 6
Black -> captures p [White, WhiteQueen] 1
BlackQueen -> captures p [White, WhiteQueen] 6
directional p0 b0 f dirs step = concatMap d dirs
where d dir = f (`M.notMember` b0) $ (p0+) . (dir*) . pure <$> [1..step]
captures p en off = rec' brd p []
where f b0 p0 = filter allowedMove
$ concatMap (\a -> directional a b0 takeWhile [vdir p0 a] off)
$ filter (isJust . mfilter (`elem` en) . lookup b0)
$ directional p0 b0 takeWhile1 allDirections off
rec' b0 p0 l = case f b0 p0 of
[] -> [Capture $ reverse l]
m -> concatMap (\m0 -> rec' (movePawn b0 p0 $ Capture [m0]) m0 (m0:l)) m
range :: (Enum a, Num a) => V2 a -> V2 a -> [V2 a]
range (V2 fx fy) (V2 tx ty) = zipWith V2 (r fx tx) (r fy ty)
where r a b = [a, a + signum (b - a) .. b]
movePawn :: Board -> V2 Int -> Move -> Board
movePawn brd from move = M.insert to insert $ foldr M.delete brd seg
where to@(V2 _ toY) = case move of
Ordinary x -> x
Capture xs -> last xs
seg = case move of
Ordinary x -> range from x
Capture xs -> concat $ zipWith range (from : xs) xs
insert = case brd M.! from of
White -> if toY == 7 then WhiteQueen else White
Black -> if toY == 0 then BlackQueen else Black
a -> a
gameScore :: GameState -> String
gameScore (GameState brd _ _) = w ++ " : " ++ b
where w = show $ getScore Whites brd
b = show $ getScore Blacks brd
|
korrix/Warcaby
|
Game.hs
|
Haskell
|
bsd-3-clause
| 4,198
|
-- | Main module to manipulate a git repository.
module Data.Git(
-- * Repository
Git
, gitRepoPath
, openRepo
, closeRepo
, withRepo
, findRepository
-- * Most important question
, findObject
-- * Find named elements
-- ** Obtain a list of existing elements
, getHead
, getBranchNames
, getTagNames
, getRemoteNames
, getRemoteBranchNames
, getGitSvnBranchNames
-- ** Querying for existence
, doesHeadExist
, doesTagExist
, doesRemoteHeadExist
-- ** Obtain the references of the elements
, readBranch
, readTag
, readRemoteBranch
, readGitSvnBranch
-- * Git objects
, GitObject(..)
, CommitAuthor(..)
, CommitInfo(..)
, TagInfo(..)
, FileRights
, TreeEntry
-- * Reference conversion
, Ref
, RefSpec( .. )
, toHexString
, toBinary
, fromHexString
, fromHexText
, fromBinary
, toHex
, fromHex
-- * Revisions
, Revision
, revFromString
, resolveRevision
, readAllRemoteBranches
) where
import Data.Git.Object
import Data.Git.Ref
import Data.Git.Repository
import Data.Git.Revision
|
Twinside/hit-simple
|
Data/Git.hs
|
Haskell
|
bsd-3-clause
| 1,730
|
module Program(
toCProgram,
ILProgram, ilProgram,
ILFunction, ilFunc) where
import Data.Map as M
import CCodeGen
import RPN
import Syntax
data ILProgram = Prog [ILFunction] [RecordDef]
deriving (Show)
ilProgram = Prog
toCProgram :: ILProgram -> CProgram
toCProgram (Prog funcs recDefs) = cProgram defaultImports prototypes funcDefs
where
defaultImports = [cInclude "BasicRuntime.h"]
prototypes = Prelude.map makePrototype funcs
userDefFuncsMap = M.fromList $ zip (Prelude.map fName funcs) (Prelude.map mkFDef funcs)
funcDefMap = M.union builtinMap userDefFuncsMap
constructors = constructorMap recDefs
accessors = accessorMap recDefs
funcDefs = Prelude.map (toCFunc funcDefMap constructors accessors) funcs
constructorMap :: [RecordDef] -> Map String Int
constructorMap recDefs = M.fromList $ zip (Prelude.map constructor recDefs) (Prelude.map numFields recDefs)
accessorMap :: [RecordDef] -> Map String Int
accessorMap recDefs = M.fromList $ concat $ Prelude.map accessors recDefs
data ILFunction = ILF { fName :: String, fArgNames :: [String], fBody :: Expr }
deriving (Show)
ilFunc :: String -> [String] -> Expr -> ILFunction
ilFunc name argNames body = ILF name argNames body
toCFunc :: Map String FDef -> Map String Int -> Map String Int -> ILFunction -> CFunction
toCFunc fDefs conArities accInds (ILF name argNames expr) = cFunc name body
where
vMap = M.fromList $ zip argNames [1..]
body = Prelude.map toCCode $ toRPN fDefs vMap accInds conArities expr
mkFDef :: ILFunction -> FDef
mkFDef (ILF fn args _) = fdef fn (length args)
makePrototype :: ILFunction -> CFuncDeclaration
makePrototype (ILF name _ _) = stdDec name
|
dillonhuff/IntLang
|
src/Program.hs
|
Haskell
|
bsd-3-clause
| 1,730
|
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE ViewPatterns, PatternSynonyms, RankNTypes #-}
module Homework01 (
toDigits,
toDigitsRev,
myReverse,
doubleEveryOther,
sumDigits,
sumList,
sumDigitsFoldWorker,
validate,
checkSum,
hanoi,
) where
-- | Convert a number [like 1234] into a list of individual digits [like [1, 2, 3, 4]
toDigits :: Integer -> [Integer]
toDigits num = toDigitsWorker 1 num []
-- | Recursive helper for toDigits.
toDigitsWorker :: Integer -> Integer -> [Integer] -> [Integer]
toDigitsWorker place num list
| num <= 0 = list
| otherwise = toDigitsWorker placeVal (num - remainder) (digit:list)
where
placeVal = place*10
remainder = num `mod` placeVal
digit = remainder `div` place
-- | Convert a number [like 1234] into a list of individual reversed digits [like [4, 3, 2, 1]
toDigitsRev :: Integer -> [Integer]
toDigitsRev num = myReverse (toDigits num)
-- | Reverse a list by recursing through it
myReverse :: [Integer] -> [Integer]
myReverse nums = myReverseWorker nums []
-- | Recursive helper for myReverse
myReverseWorker :: [Integer] -> [Integer] -> [Integer]
myReverseWorker [] newList = newList
myReverseWorker (num:rest) newList = myReverseWorker rest (num:newList)
-- | Double every other number in the list, starting from the right
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther nums = doubleEveryOtherReverseWorker (myReverse nums) []
-- | Recursive, reversed helper for doubling every other number in the list, starting from the right
doubleEveryOtherReverseWorker :: [Integer] -> [Integer] -> [Integer]
doubleEveryOtherReverseWorker [] newList = newList
doubleEveryOtherReverseWorker (x:[]) newList = x:newList
doubleEveryOtherReverseWorker (x:(y:zs)) newList = doubleEveryOtherReverseWorker zs ((y * 2):x:newList)
-- | Sum the individual digits from a list of numbers produced by doubleEveryOther
sumDigits :: [Integer] -> Integer
sumDigits nums = foldr sumDigitsFoldWorker 0 nums
-- | Sum Integers from a list, using a right fold
sumList :: [Integer] -> Integer
sumList nums = foldr (+) 0 nums
-- | fold worker for sumDigits.
sumDigitsFoldWorker :: Integer -> Integer -> Integer
sumDigitsFoldWorker newNum priorNum
| newNum < 0 = priorNum + 0
| newNum < 10 = priorNum + newNum
| otherwise = priorNum + (sumList (toDigits newNum))
-- | Validate a credit card number, entered as an Integer
validate :: Integer -> Bool
validate num = (checkSum num) `mod` 10 == 0
-- | Helper to calculate the checksum value
checkSum :: Integer -> Integer
checkSum num = (sumDigits (doubleEveryOther (toDigits num)))
-- | It's an alias for the peg name
type Peg = String
-- | A move is pair of two pegs (from, to)
type Move = (Peg, Peg)
-- | This function takes the number of discs and the three peg names and returns the list of moves to solve the puzzle
hanoi :: Integer -> Peg -> Peg -> Peg -> [Move]
hanoi 1 start dest _ = (start, dest):[]
hanoi discs start dest storage = (hanoi (discs - 1) start storage dest) ++ (start, dest):[] ++ (hanoi (discs - 1) storage dest start)
--hanoiWorker :: Integer -> Peg -> Peg -> Peg -> [Move] -> [Move]
--hanoiWorker 1 start dest storage pastMoves = ((start, dest) : pastMoves)
--hanoiWorker discs start dest storage pastMoves = (hanoi (discs - 1) start storage dest):()
|
jeyoor/haskell-learning-challenge
|
learn_haskell_github_courses/Cis194/src/Homework01.hs
|
Haskell
|
bsd-3-clause
| 3,336
|
module Candide.Server (
runCandideDaemon
) where
import Control.Applicative
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async
import qualified Control.Concurrent.Async.Lifted as AL
import Control.Concurrent.MVar
import Control.Exception (throw)
import Control.Monad
import Control.Monad.Error
import Control.Monad.State.Lazy
import Data.Attoparsec.ByteString.Lazy (Parser)
import Data.Attoparsec.Combinator (eitherP)
import qualified Data.Attoparsec.Lazy as Parser
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.ByteString.Builder (Builder, byteString,
toLazyByteString)
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Lazy as L
import qualified Data.HashMap.Strict as H
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Packer
import qualified Data.Set as S
import Data.Time.Clock
import Data.Word
import Database.PostgreSQL.Simple as PG
import Pipes
import Pipes.Attoparsec (parsed)
import qualified Pipes.ByteString as PB
import Pipes.Group (FreeF (..), FreeT (..))
import qualified Pipes.Group as PG
import qualified Pipes.Lift as P
import qualified Pipes.Prelude as P
import System.IO
import System.Log.Logger
import Candide.Core
import Marquise.Classes
import Marquise.Client
import Marquise.Types
import Vaultaire.Types
data ContentsRequest = ContentsRequest Address SourceDict
deriving Show
runCandideDaemon :: String -> Word16 -> String -> String -> Origin -> String -> MVar () -> String -> Integer -> IO (Async ())
runCandideDaemon host port user pass origin namespace shutdown cache_file cache_flush_period = async $ do
infoM "Server.runCandideDaemon" $ "Reading SourceDict cache from " ++ cache_file
init_cache <- withFile cache_file ReadWriteMode $ \h -> do
result <- fromWire <$> BSC.hGetContents h
case result of
Left e -> do
warningM "Server.runCandideDaemon" $
concat ["Error decoding hash file: "
, show e
, " Continuing with empty initial cache"
]
return emptySourceCache
Right cache -> do
debugM "Server.runCandideDaemon" $
concat ["Read "
, show (sizeOfSourceCache cache)
, " hashes from source dict cache."
]
return cache
infoM "Server.runCandideDaemon" "Connecting to Candide"
conn <- candideConnection host port user pass (Just origin)
infoM "Server.runCandideDaemon" "Candide daemon started"
(points_loop, final_cache) <- do
sn <- makeSpoolName namespace
debugM "Server.runCandideDaemon" "Creating spool directories"
createDirectories sn
debugM "Server.runCandideDaemon" "Starting point transmitting thread"
points_loop <- AL.async (sendPoints conn sn shutdown)
currTime <- do
link points_loop
debugM "Server.runCandideDaemon" "Starting contents transmitting thread"
getCurrentTime
final_cache <- sendContents conn sn init_cache cache_file cache_flush_period currTime shutdown
return (points_loop, final_cache)
-- debugM "Server.runCandideDaemon" "Send loop shut down gracefully, writing out cache"
-- S.writeFile cache_file $ toWire final_cache
debugM "Server.runCandideDaemon" "Waiting for points loop thread"
AL.wait points_loop
sendPoints :: PG.Connection -> SpoolName -> MVar () -> IO ()
sendPoints conn sn shutdown = do
nexts <- nextPoints sn
case nexts of
Just (bytes, seal) -> do
debugM "Server.sendPoints" "Got points, starting transmission pipe"
runEffect $ for (breakInToChunks bytes) sendChunk
debugM "Server.sendPoints" "Transmission complete, cleaning up"
seal
Nothing -> threadDelay idleTime
done <- isJust <$> tryReadMVar shutdown
unless done (sendPoints conn sn shutdown)
where
sendChunk chunk = liftIO $ do
let size = show . BSC.length $ chunk
debugM "Server.sendPoints" $ "Sending chunk of " ++ size ++ " bytes."
let points = P.toList $ yield (SimpleBurst chunk) >-> decodeSimple
writeManySimple conn points
sendContents :: PG.Connection
-> SpoolName
-> SourceDictCache
-> String
-> Integer
-> UTCTime
-> MVar ()
-> IO SourceDictCache
sendContents conn sn initial cache_file cache_flush_period flush_time shutdown = do
nexts <- nextContents sn
(final, newFlushTime) <- case nexts of
Just (bytes, seal) -> do
debugM "Server.sendContents" $
concat
[ "Got contents, starting transmission pipe with "
, show $ sizeOfSourceCache initial
, " cached sources."
]
reqs <- parseContentsRequests bytes
notSeen <- filterSeen reqs initial
newHashes <- S.unions <$> forM notSeen (return . S.singleton . hashRequest)
let final' = S.foldl (flip insertSourceCache) initial newHashes
sendSourceDictUpdate conn notSeen
newFlushTime' <- do
debugM "Server.sendContents" "Contents transmission complete, cleaning up."
debugM "Server.sendContents" $
concat
[ "Saw "
, show $ sizeOfSourceCache final' - sizeOfSourceCache initial
, " new sources."
]
seal
currTime <- getCurrentTime
if currTime > flush_time
then do
debugM "Server.setContents" "Performing periodic cache writeout."
BSC.writeFile cache_file $ toWire final'
return $ addUTCTime (fromInteger cache_flush_period) currTime
else do
debugM "Server.sendContents" $ concat ["Next cache flush at ", show flush_time, "."]
return flush_time
return (final', newFlushTime')
Nothing -> do
threadDelay idleTime
return (initial, flush_time)
done <- isJust <$> tryReadMVar shutdown
if done
then return final
else sendContents conn sn final cache_file cache_flush_period newFlushTime shutdown
where
hashRequest (ContentsRequest _ sd) = hashSource sd
seen cache req = memberSourceCache (hashRequest req) cache
filterSeen reqs cache = do
let (prevSeen, notSeen) = partition (seen cache) reqs
forM_ prevSeen $ \(ContentsRequest addr _) ->
liftIO $ debugM "Server.filterSeen" $ "Seen source dict with address " ++ show addr ++ " before, ignoring."
return notSeen
sendSourceDictUpdate conn reqs = do
forM_ reqs $ \(ContentsRequest addr _) ->
liftIO (debugM "Server.sendContents" $ "Sending contents update for " ++ show addr)
writeManyContents conn $ map reqToTuple reqs
reqToTuple (ContentsRequest addr (SourceDict sd)) = (addr, H.toList sd)
parseContentsRequests :: Monad m => L.ByteString -> m [ContentsRequest]
parseContentsRequests bs = P.toListM $
parsed parseContentsRequest (PB.fromLazy bs)
>>= either (throw . fst) return
parseContentsRequest :: Parser ContentsRequest
parseContentsRequest = do
addr <- fromWire <$> Parser.take 8
len <- runUnpacking getWord64LE <$> Parser.take 8
source_dict <- fromWire <$> Parser.take (fromIntegral len)
case ContentsRequest <$> addr <*> source_dict of
Left e -> fail (show e)
Right request -> return request
idleTime :: Int
idleTime = 1000000 -- 1 second
breakInToChunks :: Monad m => L.ByteString -> Producer BSC.ByteString m ()
breakInToChunks bs =
chunkBuilder (parsed parsePoint (PB.fromLazy bs))
>>= either (throw . fst) return
-- Take a producer of (Int, Builder), where Int is the number of bytes in the
-- builder and produce chunks of n bytes.
--
-- This could be done with explicit recursion and next, but, then we would not
-- get to apply a fold over a FreeT stack of producers. This is almost
-- generalizable, at a stretch.
chunkBuilder :: Monad m => Producer (Int, Builder) m r -> Producer BSC.ByteString m r
chunkBuilder = PG.folds (<>) mempty (L.toStrict . toLazyByteString)
-- Fold over each producer of counted Builders, turning it into
-- a contigous strict ByteString ready for transmission.
. builderChunks idealBurstSize
-- Split the builder producer into FreeT
where
builderChunks :: Monad m
=> Int
-- ^ The size to split a stream of builders at
-> Producer (Int, Builder) m r
-- ^ The input producer
-> FreeT (Producer Builder m) m r
-- ^ The FreeT delimited chunks of that producer, split into
-- the desired chunk length
builderChunks max_size p = FreeT $ do
-- Try to grab the next value from the Producer
x <- next p
return $ case x of
Left r -> Pure r
Right (a, p') -> Free $ do
-- Pass the re-joined Producer to go, which will yield values
-- from it until the desired chunk size is reached.
p'' <- go max_size (yield a >> p')
-- The desired chunk size has been reached, loop and try again
-- with the rest of the stream (possibly empty)
return (builderChunks max_size p'')
-- We take a Producer and pass along its values until we've passed along
-- enough bytes (at least the initial bytes_left).
--
-- When done, returns the remainder of the unconsumed Producer
go :: Monad m
=> Int
-> Producer (Int, Builder) m r
-> Producer Builder m (Producer (Int, Builder) m r)
go bytes_left p =
if bytes_left < 0
then return p
else do
x <- lift (next p)
case x of
Left r ->
return . return $ r
Right ((size, builder), p') -> do
yield builder
go (bytes_left - size) p'
-- Parse a single point, returning the size of the point and the bytes as a
-- builder.
parsePoint :: Parser (Int, Builder)
parsePoint = do
packet <- Parser.take 24
case extendedSize packet of
Just len -> do
-- We must ensure that we get this many bytes now, or attoparsec
-- will just backtrack on us. We do this with a dummy parser inside
-- an eitherP
--
-- This is only to get good error messages.
extended <- eitherP (Parser.take len) (return ())
case extended of
Left bytes ->
let b = byteString packet <> byteString bytes
in return (24 + len, b)
Right () ->
fail "not enough bytes in alleged extended burst"
Nothing ->
return (24, byteString packet)
-- Return the size of the extended segment, if the point is an extended one.
extendedSize :: BSC.ByteString -> Maybe Int
extendedSize packet = flip runUnpacking packet $ do
addr <- Address <$> getWord64LE
if isAddressExtended addr
then do
unpackSkip 8
Just . fromIntegral <$> getWord64LE -- length
else
return Nothing
-- A burst should be, at maximum, very close to this size, unless the user
-- decides to send a very long extended point.
idealBurstSize :: Int
idealBurstSize = 1048576
|
anchor/candide
|
lib/Candide/Server.hs
|
Haskell
|
bsd-3-clause
| 12,628
|
module Test4
( DAbs
, DAll(..)
, DRecAll(..)
, DRec(DRec) -- no fields
, DSome(One, Two)
, foo
, bar
) where
foo x = 1 :: Int
bar y = 2 :: Int
lam :: Int -> Int
lam x = 2 * x
data DAbs = NotExported
data DAll = Me | AndMe
data DRec = DRec { drNotExported :: Int }
data DRecAll = DRecAll { drA :: Int, drB :: Int }
data DSome = One String | Two Int Int | NotThree
|
robinp/nemnem
|
tsrc/Test4.hs
|
Haskell
|
bsd-3-clause
| 383
|
{-# LANGUAGE ScopedTypeVariables #-}
module Sort3Spec where
import qualified Sort3
import Test.Hspec (Spec, hspec, describe, shouldSatisfy)
import Test.Hspec.QuickCheck (prop)
-- | Required for auto-discovery.
spec :: Spec
spec =
describe "Sort3" $ do
prop "sort3 sorts correctly" $ do
\(triple :: (Int, Int, Int)) ->
let (a0', a1', a2') = Sort3.sort3 triple
in a0' <= a1' && a1' <= a2'
main :: IO ()
main = hspec spec
|
FranklinChen/twenty-four-days2015-of-hackage
|
test/Sort3Spec.hs
|
Haskell
|
bsd-3-clause
| 452
|
module Eval(eval) where
import Syntax
eval :: Expr -> Env -> Value
eval (ELit (LInt n)) _ = VInt n
eval (ELit (LBool b)) _ = VBool b
eval (EOp op e1 e2) env = binop op e1 e2 env
eval (EVar x) env =
case lookupEnv x env of
VThunk (EFix f e) env' -> eval (EFix f e) env'
v -> v
eval (ELam x e) env = VClos x e env
eval (EApp e1 e2) env = v2 `seq` eval e3 ((x, v2):env')
where
VClos x e3 env' = eval e1 env
v2 = eval e2 env
eval (ELet x e1 e2) env = eval e2 env'
where
v = eval e1 env
env' = env `ext` (x,v)
eval (EFix f e) env = eval e env'
where env' = env `ext` (f, (VThunk (EFix f e) env))
eval (EIf e1 e2 e3) env = if b then eval e2 env else eval e3 env
where VBool b = eval e1 env
binop :: BinOp -> Expr -> Expr -> Env -> Value
binop op e1 e2 env =
case (op, eval e1 env, eval e2 env) of
(Add, VInt n1, VInt n2) -> VInt $ n1 + n2
(Sub, VInt n1, VInt n2) -> VInt $ n1 - n2
(Mul, VInt n1, VInt n2) -> VInt $ n1 * n2
(And, VBool b1, VBool b2) -> VBool $ b1 && b2
(Or, VBool b1, VBool b2) -> VBool $ b1 || b2
(Eq, VInt n1, VInt n2) -> VBool $ n1 == n2
(Eq, VBool b1, VBool b2) -> VBool $ b1 == b2
(Gt, VInt n1, VInt n2) -> VBool $ n1 > n2
(Lt, VInt n1, VInt n2) -> VBool $ n1 < n2
(_,_,_) -> error $ "FATAL ERROR: " ++ show op ++ ":" ++ show e1 ++ ", " ++ show e2
-- Last one should be unreachable when the expression is typed.
|
succzero/fino
|
src/Eval.hs
|
Haskell
|
bsd-3-clause
| 1,511
|
{-# LANGUAGE OverloadedStrings, GeneralizedNewtypeDeriving, CPP #-}
{- Note: [The need for Ar.hs]
Building `-staticlib` required the presence of libtool, and was a such
restricted to mach-o only. As libtool on macOS and gnu libtool are very
different, there was no simple portable way to support this.
libtool for static archives does essentially: concatinate the input archives,
add the input objects, and create a symbol index. Using `ar` for this task
fails as even `ar` (bsd and gnu, llvm, ...) do not provide the same
features across platforms (e.g. index prefixed retrieval of objects with
the same name.)
As Archives are rather simple structurally, we can just build the archives
with Haskell directly and use ranlib on the final result to get the symbol
index. This should allow us to work around with the differences/abailability
of libtool across different platforms.
-}
module Ar
(ArchiveEntry(..)
,Archive(..)
,afilter
,parseAr
,loadAr
,loadObj
,writeBSDAr
,writeGNUAr
,isBSDSymdef
,isGNUSymdef
)
where
import GhcPrelude
import Data.List (mapAccumL, isPrefixOf)
import Data.Monoid ((<>))
import Data.Binary.Get
import Data.Binary.Put
import Control.Monad
import Control.Applicative
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import qualified Data.ByteString.Lazy as L
#if !defined(mingw32_HOST_OS)
import qualified System.Posix.Files as POSIX
#endif
import System.FilePath (takeFileName)
data ArchiveEntry = ArchiveEntry
{ filename :: String -- ^ File name.
, filetime :: Int -- ^ File modification time.
, fileown :: Int -- ^ File owner.
, filegrp :: Int -- ^ File group.
, filemode :: Int -- ^ File mode.
, filesize :: Int -- ^ File size.
, filedata :: B.ByteString -- ^ File bytes.
} deriving (Eq, Show)
newtype Archive = Archive [ArchiveEntry]
deriving (Eq, Show, Semigroup, Monoid)
afilter :: (ArchiveEntry -> Bool) -> Archive -> Archive
afilter f (Archive xs) = Archive (filter f xs)
isBSDSymdef, isGNUSymdef :: ArchiveEntry -> Bool
isBSDSymdef a = "__.SYMDEF" `isPrefixOf` (filename a)
isGNUSymdef a = "/" == (filename a)
-- | Archives have numeric values padded with '\x20' to the right.
getPaddedInt :: B.ByteString -> Int
getPaddedInt = read . C.unpack . C.takeWhile (/= '\x20')
putPaddedInt :: Int -> Int -> Put
putPaddedInt padding i = putPaddedString '\x20' padding (show i)
putPaddedString :: Char -> Int -> String -> Put
putPaddedString pad padding s = putByteString . C.pack . take padding $ s `mappend` (repeat pad)
getBSDArchEntries :: Get [ArchiveEntry]
getBSDArchEntries = do
empty <- isEmpty
if empty then
return []
else do
name <- getByteString 16
when ('/' `C.elem` name && C.take 3 name /= "#1/") $
fail "Looks like GNU Archive"
time <- getPaddedInt <$> getByteString 12
own <- getPaddedInt <$> getByteString 6
grp <- getPaddedInt <$> getByteString 6
mode <- getPaddedInt <$> getByteString 8
st_size <- getPaddedInt <$> getByteString 10
end <- getByteString 2
when (end /= "\x60\x0a") $
fail ("[BSD Archive] Invalid archive header end marker for name: " ++
C.unpack name)
off1 <- liftM fromIntegral bytesRead :: Get Int
-- BSD stores extended filenames, by writing #1/<length> into the
-- name field, the first @length@ bytes then represent the file name
-- thus the payload size is filesize + file name length.
name <- if C.unpack (C.take 3 name) == "#1/" then
liftM (C.unpack . C.takeWhile (/= '\0')) (getByteString $ read $ C.unpack $ C.drop 3 name)
else
return $ C.unpack $ C.takeWhile (/= ' ') name
off2 <- liftM fromIntegral bytesRead :: Get Int
file <- getByteString (st_size - (off2 - off1))
-- data sections are two byte aligned (see #15396)
when (odd st_size) $
void (getByteString 1)
rest <- getBSDArchEntries
return $ (ArchiveEntry name time own grp mode (st_size - (off2 - off1)) file) : rest
-- | GNU Archives feature a special '//' entry that contains the
-- extended names. Those are referred to as /<num>, where num is the
-- offset into the '//' entry.
-- In addition, filenames are terminated with '/' in the archive.
getGNUArchEntries :: Maybe ArchiveEntry -> Get [ArchiveEntry]
getGNUArchEntries extInfo = do
empty <- isEmpty
if empty
then return []
else
do
name <- getByteString 16
time <- getPaddedInt <$> getByteString 12
own <- getPaddedInt <$> getByteString 6
grp <- getPaddedInt <$> getByteString 6
mode <- getPaddedInt <$> getByteString 8
st_size <- getPaddedInt <$> getByteString 10
end <- getByteString 2
when (end /= "\x60\x0a") $
fail ("[BSD Archive] Invalid archive header end marker for name: " ++
C.unpack name)
file <- getByteString st_size
-- data sections are two byte aligned (see #15396)
when (odd st_size) $
void (getByteString 1)
name <- return . C.unpack $
if C.unpack (C.take 1 name) == "/"
then case C.takeWhile (/= ' ') name of
name@"/" -> name -- symbol table
name@"//" -> name -- extendedn file names table
name -> getExtName extInfo (read . C.unpack $ C.drop 1 name)
else C.takeWhile (/= '/') name
case name of
"/" -> getGNUArchEntries extInfo
"//" -> getGNUArchEntries (Just (ArchiveEntry name time own grp mode st_size file))
_ -> (ArchiveEntry name time own grp mode st_size file :) <$> getGNUArchEntries extInfo
where
getExtName :: Maybe ArchiveEntry -> Int -> B.ByteString
getExtName Nothing _ = error "Invalid extended filename reference."
getExtName (Just info) offset = C.takeWhile (/= '/') . C.drop offset $ filedata info
-- | put an Archive Entry. This assumes that the entries
-- have been preprocessed to account for the extenden file name
-- table section "//" e.g. for GNU Archives. Or that the names
-- have been move into the payload for BSD Archives.
putArchEntry :: ArchiveEntry -> PutM ()
putArchEntry (ArchiveEntry name time own grp mode st_size file) = do
putPaddedString ' ' 16 name
putPaddedInt 12 time
putPaddedInt 6 own
putPaddedInt 6 grp
putPaddedInt 8 mode
putPaddedInt 10 (st_size + pad)
putByteString "\x60\x0a"
putByteString file
when (pad == 1) $
putWord8 0x0a
where
pad = st_size `mod` 2
getArchMagic :: Get ()
getArchMagic = do
magic <- liftM C.unpack $ getByteString 8
if magic /= "!<arch>\n"
then fail $ "Invalid magic number " ++ show magic
else return ()
putArchMagic :: Put
putArchMagic = putByteString $ C.pack "!<arch>\n"
getArch :: Get Archive
getArch = Archive <$> do
getArchMagic
getBSDArchEntries <|> getGNUArchEntries Nothing
putBSDArch :: Archive -> PutM ()
putBSDArch (Archive as) = do
putArchMagic
mapM_ putArchEntry (processEntries as)
where
padStr pad size str = take size $ str <> repeat pad
nameSize name = case length name `divMod` 4 of
(n, 0) -> 4 * n
(n, _) -> 4 * (n + 1)
needExt name = length name > 16 || ' ' `elem` name
processEntry :: ArchiveEntry -> ArchiveEntry
processEntry archive@(ArchiveEntry name _ _ _ _ st_size _)
| needExt name = archive { filename = "#1/" <> show sz
, filedata = C.pack (padStr '\0' sz name) <> filedata archive
, filesize = st_size + sz }
| otherwise = archive
where sz = nameSize name
processEntries = map processEntry
putGNUArch :: Archive -> PutM ()
putGNUArch (Archive as) = do
putArchMagic
mapM_ putArchEntry (processEntries as)
where
processEntry :: ArchiveEntry -> ArchiveEntry -> (ArchiveEntry, ArchiveEntry)
processEntry extInfo archive@(ArchiveEntry name _ _ _ _ _ _)
| length name > 15 = ( extInfo { filesize = filesize extInfo + length name + 2
, filedata = filedata extInfo <> C.pack name <> "/\n" }
, archive { filename = "/" <> show (filesize extInfo) } )
| otherwise = ( extInfo, archive { filename = name <> "/" } )
processEntries :: [ArchiveEntry] -> [ArchiveEntry]
processEntries =
uncurry (:) . mapAccumL processEntry (ArchiveEntry "//" 0 0 0 0 0 mempty)
parseAr :: B.ByteString -> Archive
parseAr = runGet getArch . L.fromChunks . pure
writeBSDAr, writeGNUAr :: FilePath -> Archive -> IO ()
writeBSDAr fp = L.writeFile fp . runPut . putBSDArch
writeGNUAr fp = L.writeFile fp . runPut . putGNUArch
loadAr :: FilePath -> IO Archive
loadAr fp = parseAr <$> B.readFile fp
loadObj :: FilePath -> IO ArchiveEntry
loadObj fp = do
payload <- B.readFile fp
(modt, own, grp, mode) <- fileInfo fp
return $ ArchiveEntry
(takeFileName fp) modt own grp mode
(B.length payload) payload
-- | Take a filePath and return (mod time, own, grp, mode in decimal)
fileInfo :: FilePath -> IO ( Int, Int, Int, Int) -- ^ mod time, own, grp, mode (in decimal)
#if defined(mingw32_HOST_OS)
-- on windows mod time, owner group and mode are zero.
fileInfo _ = pure (0,0,0,0)
#else
fileInfo fp = go <$> POSIX.getFileStatus fp
where go status = ( fromEnum $ POSIX.modificationTime status
, fromIntegral $ POSIX.fileOwner status
, fromIntegral $ POSIX.fileGroup status
, oct2dec . fromIntegral $ POSIX.fileMode status
)
oct2dec :: Int -> Int
oct2dec = foldl' (\a b -> a * 10 + b) 0 . reverse . dec 8
where dec _ 0 = []
dec b i = let (rest, last) = i `quotRem` b
in last:dec b rest
#endif
|
sdiehl/ghc
|
compiler/main/Ar.hs
|
Haskell
|
bsd-3-clause
| 10,051
|
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
module DataStore.QueueStore
( enqueue
, dequeue
, dequeueAll
) where
import qualified Data.Default as Default
import qualified Data.Serialize as Serialize
import MonadImports
import Aliases
import qualified DataStore.Job as Job
import qualified GithubWebhook.Types.Repo as Repo
import qualified Utils as U
import Database.Persist
import Database.Persist.TH
import Database.Persist.Sqlite
import Control.Monad.Logger (runStderrLoggingT)
enqueue :: ConnectionPool -> Job.Job -> EIO ()
enqueue connectionPool job = liftIO . runStderrLoggingT $ do
runSqlPool (insert job) connectionPool
return ()
dequeue :: ConnectionPool -> Repo.Repo -> EIO Job.Job
dequeue connectionPool repo = liftIO . runStderrLoggingT $ do
let repoID = fromIntegral $ Repo.id repo
let action = selectList [Job.JobRepoID ==. repoID] []
jobs <- runSqlPool action connectionPool
when (null jobs) $ fail "No jobs to dequeue"
let Entity key job = head jobs
runSqlPool (delete key) connectionPool
return job
dequeueAll :: ConnectionPool -> Int -> EIO [Job.Job]
dequeueAll connectionPool repoID = liftIO . runStderrLoggingT $ do
let action = selectList [Job.JobRepoID ==. repoID] []
jobs <- runSqlPool action connectionPool
mapM_ (\(Entity key job) -> runSqlPool (delete key) connectionPool) jobs
return $ map (\(Entity key job) -> job) jobs
|
bgwines/hueue
|
src/DataStore/QueueStore.hs
|
Haskell
|
bsd-3-clause
| 1,597
|
-------------------------------------------------------------------------------
--
-- | Dynamic flags
--
-- Most flags are dynamic flags, which means they can change from compilation
-- to compilation using @OPTIONS_GHC@ pragmas, and in a multi-session GHC each
-- session can be using different dynamic flags. Dynamic flags can also be set
-- at the prompt in GHCi.
--
-- (c) The University of Glasgow 2005
--
-------------------------------------------------------------------------------
module DynFlags (
-- * Dynamic flags and associated configuration types
DynFlag(..),
WarningFlag(..),
ExtensionFlag(..),
LogAction,
ProfAuto(..),
glasgowExtsFlags,
dopt,
dopt_set,
dopt_unset,
wopt,
wopt_set,
wopt_unset,
xopt,
xopt_set,
xopt_unset,
DynFlags(..),
RtsOptsEnabled(..),
HscTarget(..), isObjectTarget, defaultObjectTarget,
targetRetainsAllBindings,
GhcMode(..), isOneShot,
GhcLink(..), isNoLink,
PackageFlag(..),
Option(..), showOpt,
DynLibLoader(..),
fFlags, fWarningFlags, fLangFlags, xFlags,
wayNames, dynFlagDependencies,
-- ** Safe Haskell
SafeHaskellMode(..),
safeHaskellOn, safeImportsOn, safeLanguageOn, safeInferOn,
packageTrustOn,
safeDirectImpsReq, safeImplicitImpsReq,
unsafeFlags,
-- ** System tool settings and locations
Settings(..),
targetPlatform,
ghcUsagePath, ghciUsagePath, topDir, tmpDir, rawSettings,
extraGccViaCFlags, systemPackageConfig,
pgm_L, pgm_P, pgm_F, pgm_c, pgm_s, pgm_a, pgm_l, pgm_dll, pgm_T,
pgm_sysman, pgm_windres, pgm_lo, pgm_lc,
opt_L, opt_P, opt_F, opt_c, opt_a, opt_l,
opt_windres, opt_lo, opt_lc,
-- ** Manipulating DynFlags
defaultDynFlags, -- Settings -> DynFlags
initDynFlags, -- DynFlags -> IO DynFlags
defaultLogAction,
getOpts, -- DynFlags -> (DynFlags -> [a]) -> [a]
getVerbFlags,
updOptLevel,
setTmpDir,
setPackageName,
doingTickyProfiling,
-- ** Parsing DynFlags
parseDynamicFlagsCmdLine,
parseDynamicFilePragma,
allFlags,
supportedLanguagesAndExtensions,
-- ** DynFlag C compiler options
picCCOpts,
-- * Configuration of the stg-to-stg passes
StgToDo(..),
getStgToDo,
-- * Compiler configuration suitable for display to the user
compilerInfo
#ifdef GHCI
-- Only in stage 2 can we be sure that the RTS
-- exposes the appropriate runtime boolean
, rtsIsProfiled
#endif
) where
#include "HsVersions.h"
import Platform
import Module
import PackageConfig
import PrelNames ( mAIN )
import StaticFlags
import {-# SOURCE #-} Packages (PackageState)
import DriverPhases ( Phase(..), phaseInputExt )
import Config
import CmdLineParser
import Constants ( mAX_CONTEXT_REDUCTION_DEPTH )
import Panic
import Util
import Maybes ( orElse )
import SrcLoc
import FastString
import Outputable
#ifdef GHCI
import Foreign.C ( CInt(..) )
#endif
import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
#ifdef GHCI
import System.IO.Unsafe ( unsafePerformIO )
#endif
import Data.IORef
import Control.Monad ( when )
import Data.Char
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import System.FilePath
import System.IO ( stderr, hPutChar )
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
-- -----------------------------------------------------------------------------
-- DynFlags
-- | Enumerates the simple on-or-off dynamic flags
data DynFlag
-- debugging flags
= Opt_D_dump_cmm
| Opt_D_dump_raw_cmm
| Opt_D_dump_cmmz
| Opt_D_dump_cmmz_pretty
-- All of the cmmz subflags (there are a lot!) Automatically
-- enabled if you run -ddump-cmmz
| Opt_D_dump_cmmz_cbe
| Opt_D_dump_cmmz_proc
| Opt_D_dump_cmmz_spills
| Opt_D_dump_cmmz_rewrite
| Opt_D_dump_cmmz_dead
| Opt_D_dump_cmmz_stub
| Opt_D_dump_cmmz_sp
| Opt_D_dump_cmmz_procmap
| Opt_D_dump_cmmz_split
| Opt_D_dump_cmmz_lower
| Opt_D_dump_cmmz_info
| Opt_D_dump_cmmz_cafs
-- end cmmz subflags
| Opt_D_dump_cps_cmm
| Opt_D_dump_cvt_cmm
| Opt_D_dump_asm
| Opt_D_dump_asm_native
| Opt_D_dump_asm_liveness
| Opt_D_dump_asm_coalesce
| Opt_D_dump_asm_regalloc
| Opt_D_dump_asm_regalloc_stages
| Opt_D_dump_asm_conflicts
| Opt_D_dump_asm_stats
| Opt_D_dump_asm_expanded
| Opt_D_dump_llvm
| Opt_D_dump_core_stats
| Opt_D_dump_cpranal
| Opt_D_dump_deriv
| Opt_D_dump_ds
| Opt_D_dump_flatC
| Opt_D_dump_foreign
| Opt_D_dump_inlinings
| Opt_D_dump_rule_firings
| Opt_D_dump_rule_rewrites
| Opt_D_dump_occur_anal
| Opt_D_dump_parsed
| Opt_D_dump_rn
| Opt_D_dump_core_pipeline -- TODO FIXME: dump after simplifier stats
| Opt_D_dump_simpl
| Opt_D_dump_simpl_iterations
| Opt_D_dump_simpl_phases
| Opt_D_dump_spec
| Opt_D_dump_prep
| Opt_D_dump_stg
| Opt_D_dump_stranal
| Opt_D_dump_tc
| Opt_D_dump_types
| Opt_D_dump_rules
| Opt_D_dump_cse
| Opt_D_dump_worker_wrapper
| Opt_D_dump_rn_trace
| Opt_D_dump_rn_stats
| Opt_D_dump_opt_cmm
| Opt_D_dump_simpl_stats
| Opt_D_dump_cs_trace -- Constraint solver in type checker
| Opt_D_dump_tc_trace
| Opt_D_dump_if_trace
| Opt_D_dump_vt_trace
| Opt_D_dump_splices
| Opt_D_dump_BCOs
| Opt_D_dump_vect
| Opt_D_dump_ticked
| Opt_D_dump_rtti
| Opt_D_source_stats
| Opt_D_verbose_core2core
| Opt_D_verbose_stg2stg
| Opt_D_dump_hi
| Opt_D_dump_hi_diffs
| Opt_D_dump_minimal_imports
| Opt_D_dump_mod_cycles
| Opt_D_dump_view_pattern_commoning
| Opt_D_faststring_stats
| Opt_DumpToFile -- ^ Append dump output to files instead of stdout.
| Opt_D_no_debug_output
| Opt_DoCoreLinting
| Opt_DoStgLinting
| Opt_DoCmmLinting
| Opt_DoAsmLinting
| Opt_NoLlvmMangler
| Opt_WarnIsError -- -Werror; makes warnings fatal
| Opt_PrintExplicitForalls
-- optimisation opts
| Opt_Strictness
| Opt_FullLaziness
| Opt_FloatIn
| Opt_Specialise
| Opt_StaticArgumentTransformation
| Opt_CSE
| Opt_LiberateCase
| Opt_SpecConstr
| Opt_DoLambdaEtaExpansion
| Opt_IgnoreAsserts
| Opt_DoEtaReduction
| Opt_CaseMerge
| Opt_UnboxStrictFields
| Opt_DictsCheap
| Opt_EnableRewriteRules -- Apply rewrite rules during simplification
| Opt_Vectorise
| Opt_RegsGraph -- do graph coloring register allocation
| Opt_RegsIterative -- do iterative coalescing graph coloring register allocation
| Opt_PedanticBottoms -- Be picky about how we treat bottom
-- Interface files
| Opt_IgnoreInterfacePragmas
| Opt_OmitInterfacePragmas
| Opt_ExposeAllUnfoldings
-- profiling opts
| Opt_AutoSccsOnIndividualCafs
| Opt_ProfCountEntries
-- misc opts
| Opt_Pp
| Opt_ForceRecomp
| Opt_ExcessPrecision
| Opt_EagerBlackHoling
| Opt_ReadUserPackageConf
| Opt_NoHsMain
| Opt_SplitObjs
| Opt_StgStats
| Opt_HideAllPackages
| Opt_PrintBindResult
| Opt_Haddock
| Opt_HaddockOptions
| Opt_Hpc_No_Auto
| Opt_BreakOnException
| Opt_BreakOnError
| Opt_PrintEvldWithShow
| Opt_PrintBindContents
| Opt_GenManifest
| Opt_EmbedManifest
| Opt_EmitExternalCore
| Opt_SharedImplib
| Opt_BuildingCabalPackage
| Opt_SSE2
| Opt_SSE4_2
| Opt_GhciSandbox
| Opt_GhciHistory
| Opt_HelpfulErrors
-- temporary flags
| Opt_RunCPS
| Opt_RunCPSZ
| Opt_AutoLinkPackages
| Opt_ImplicitImportQualified
| Opt_TryNewCodeGen
-- keeping stuff
| Opt_KeepHiDiffs
| Opt_KeepHcFiles
| Opt_KeepSFiles
| Opt_KeepTmpFiles
| Opt_KeepRawTokenStream
| Opt_KeepLlvmFiles
-- safe haskell flags
| Opt_DistrustAllPackages
| Opt_PackageTrust
deriving (Eq, Show, Enum)
data WarningFlag =
Opt_WarnDuplicateExports
| Opt_WarnHiShadows
| Opt_WarnImplicitPrelude
| Opt_WarnIncompletePatterns
| Opt_WarnIncompleteUniPatterns
| Opt_WarnIncompletePatternsRecUpd
| Opt_WarnMissingFields
| Opt_WarnMissingImportList
| Opt_WarnMissingMethods
| Opt_WarnMissingSigs
| Opt_WarnMissingLocalSigs
| Opt_WarnNameShadowing
| Opt_WarnOverlappingPatterns
| Opt_WarnTypeDefaults
| Opt_WarnMonomorphism
| Opt_WarnUnusedBinds
| Opt_WarnUnusedImports
| Opt_WarnUnusedMatches
| Opt_WarnWarningsDeprecations
| Opt_WarnDeprecatedFlags
| Opt_WarnDodgyExports
| Opt_WarnDodgyImports
| Opt_WarnOrphans
| Opt_WarnAutoOrphans
| Opt_WarnIdentities
| Opt_WarnTabs
| Opt_WarnUnrecognisedPragmas
| Opt_WarnDodgyForeignImports
| Opt_WarnLazyUnliftedBindings
| Opt_WarnUnusedDoBind
| Opt_WarnWrongDoBind
| Opt_WarnAlternativeLayoutRuleTransitional
| Opt_WarnUnsafe
| Opt_WarnSafe
deriving (Eq, Show, Enum)
data Language = Haskell98 | Haskell2010
deriving Enum
-- | The various Safe Haskell modes
data SafeHaskellMode
= Sf_None
| Sf_Unsafe
| Sf_Trustworthy
| Sf_Safe
| Sf_SafeInfered
deriving (Eq)
instance Outputable SafeHaskellMode where
ppr Sf_None = ptext $ sLit "None"
ppr Sf_Unsafe = ptext $ sLit "Unsafe"
ppr Sf_Trustworthy = ptext $ sLit "Trustworthy"
ppr Sf_Safe = ptext $ sLit "Safe"
ppr Sf_SafeInfered = ptext $ sLit "Safe-Infered"
data ExtensionFlag
= Opt_Cpp
| Opt_OverlappingInstances
| Opt_UndecidableInstances
| Opt_IncoherentInstances
| Opt_MonomorphismRestriction
| Opt_MonoPatBinds
| Opt_MonoLocalBinds
| Opt_RelaxedPolyRec -- Deprecated
| Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
| Opt_ForeignFunctionInterface
| Opt_UnliftedFFITypes
| Opt_InterruptibleFFI
| Opt_CApiFFI
| Opt_GHCForeignImportPrim
| Opt_ParallelArrays -- Syntactic support for parallel arrays
| Opt_Arrows -- Arrow-notation syntax
| Opt_TemplateHaskell
| Opt_QuasiQuotes
| Opt_ImplicitParams
| Opt_ImplicitPrelude
| Opt_ScopedTypeVariables
| Opt_UnboxedTuples
| Opt_BangPatterns
| Opt_TypeFamilies
| Opt_OverloadedStrings
| Opt_DisambiguateRecordFields
| Opt_RecordWildCards
| Opt_RecordPuns
| Opt_ViewPatterns
| Opt_GADTs
| Opt_GADTSyntax
| Opt_NPlusKPatterns
| Opt_DoAndIfThenElse
| Opt_RebindableSyntax
| Opt_ConstraintKinds
| Opt_PolyKinds -- Kind polymorphism
| Opt_DataKinds -- Datatype promotion
| Opt_StandaloneDeriving
| Opt_DeriveDataTypeable
| Opt_DeriveFunctor
| Opt_DeriveTraversable
| Opt_DeriveFoldable
| Opt_DeriveGeneric -- Allow deriving Generic/1
| Opt_DefaultSignatures -- Allow extra signatures for defmeths
| Opt_TypeSynonymInstances
| Opt_FlexibleContexts
| Opt_FlexibleInstances
| Opt_ConstrainedClassMethods
| Opt_MultiParamTypeClasses
| Opt_FunctionalDependencies
| Opt_UnicodeSyntax
| Opt_PolymorphicComponents
| Opt_ExistentialQuantification
| Opt_MagicHash
| Opt_EmptyDataDecls
| Opt_KindSignatures
| Opt_ParallelListComp
| Opt_TransformListComp
| Opt_MonadComprehensions
| Opt_GeneralizedNewtypeDeriving
| Opt_RecursiveDo
| Opt_DoRec
| Opt_PostfixOperators
| Opt_TupleSections
| Opt_PatternGuards
| Opt_LiberalTypeSynonyms
| Opt_Rank2Types
| Opt_RankNTypes
| Opt_ImpredicativeTypes
| Opt_TypeOperators
| Opt_PackageImports
| Opt_ExplicitForAll
| Opt_AlternativeLayoutRule
| Opt_AlternativeLayoutRuleTransitional
| Opt_DatatypeContexts
| Opt_NondecreasingIndentation
| Opt_RelaxedLayout
| Opt_TraditionalRecordSyntax
| Opt_ApplicativeFix
deriving (Eq, Enum, Show)
-- | Contains not only a collection of 'DynFlag's but also a plethora of
-- information relating to the compilation of a single file or GHC session
data DynFlags = DynFlags {
ghcMode :: GhcMode,
ghcLink :: GhcLink,
hscTarget :: HscTarget,
settings :: Settings,
hscOutName :: String, -- ^ Name of the output file
extCoreName :: String, -- ^ Name of the .hcr output file
verbosity :: Int, -- ^ Verbosity level: see Note [Verbosity levels]
optLevel :: Int, -- ^ Optimisation level
simplPhases :: Int, -- ^ Number of simplifier phases
maxSimplIterations :: Int, -- ^ Max simplifier iterations
shouldDumpSimplPhase :: Maybe String,
ruleCheck :: Maybe String,
strictnessBefore :: [Int], -- ^ Additional demand analysis
simplTickFactor :: Int, -- ^ Multiplier for simplifier ticks
specConstrThreshold :: Maybe Int, -- ^ Threshold for SpecConstr
specConstrCount :: Maybe Int, -- ^ Max number of specialisations for any one function
liberateCaseThreshold :: Maybe Int, -- ^ Threshold for LiberateCase
floatLamArgs :: Maybe Int, -- ^ Arg count for lambda floating
-- See CoreMonad.FloatOutSwitches
cmdlineHcIncludes :: [String], -- ^ @\-\#includes@
importPaths :: [FilePath],
mainModIs :: Module,
mainFunIs :: Maybe String,
ctxtStkDepth :: Int, -- ^ Typechecker context stack depth
thisPackage :: PackageId, -- ^ name of package currently being compiled
-- ways
ways :: [Way], -- ^ Way flags from the command line
buildTag :: String, -- ^ The global \"way\" (e.g. \"p\" for prof)
rtsBuildTag :: String, -- ^ The RTS \"way\"
-- For object splitting
splitInfo :: Maybe (String,Int),
-- paths etc.
objectDir :: Maybe String,
dylibInstallName :: Maybe String,
hiDir :: Maybe String,
stubDir :: Maybe String,
dumpDir :: Maybe String,
objectSuf :: String,
hcSuf :: String,
hiSuf :: String,
outputFile :: Maybe String,
outputHi :: Maybe String,
dynLibLoader :: DynLibLoader,
-- | This is set by 'DriverPipeline.runPipeline' based on where
-- its output is going.
dumpPrefix :: Maybe FilePath,
-- | Override the 'dumpPrefix' set by 'DriverPipeline.runPipeline'.
-- Set by @-ddump-file-prefix@
dumpPrefixForce :: Maybe FilePath,
includePaths :: [String],
libraryPaths :: [String],
frameworkPaths :: [String], -- used on darwin only
cmdlineFrameworks :: [String], -- ditto
rtsOpts :: Maybe String,
rtsOptsEnabled :: RtsOptsEnabled,
hpcDir :: String, -- ^ Path to store the .mix files
-- Plugins
pluginModNames :: [ModuleName],
pluginModNameOpts :: [(ModuleName,String)],
-- For ghc -M
depMakefile :: FilePath,
depIncludePkgDeps :: Bool,
depExcludeMods :: [ModuleName],
depSuffixes :: [String],
-- Package flags
extraPkgConfs :: [FilePath],
-- ^ The @-package-conf@ flags given on the command line, in the order
-- they appeared.
packageFlags :: [PackageFlag],
-- ^ The @-package@ and @-hide-package@ flags from the command-line
-- Package state
-- NB. do not modify this field, it is calculated by
-- Packages.initPackages and Packages.updatePackages.
pkgDatabase :: Maybe [PackageConfig],
pkgState :: PackageState,
-- Temporary files
-- These have to be IORefs, because the defaultCleanupHandler needs to
-- know what to clean when an exception happens
filesToClean :: IORef [FilePath],
dirsToClean :: IORef (Map FilePath FilePath),
-- Names of files which were generated from -ddump-to-file; used to
-- track which ones we need to truncate because it's our first run
-- through
generatedDumps :: IORef (Set FilePath),
-- hsc dynamic flags
flags :: IntSet,
warningFlags :: IntSet,
-- Don't change this without updating extensionFlags:
language :: Maybe Language,
-- | Safe Haskell mode
safeHaskell :: SafeHaskellMode,
-- We store the location of where some extension and flags were turned on so
-- we can produce accurate error messages when Safe Haskell fails due to
-- them.
thOnLoc :: SrcSpan,
newDerivOnLoc :: SrcSpan,
pkgTrustOnLoc :: SrcSpan,
warnSafeOnLoc :: SrcSpan,
warnUnsafeOnLoc :: SrcSpan,
-- Don't change this without updating extensionFlags:
extensions :: [OnOff ExtensionFlag],
-- extensionFlags should always be equal to
-- flattenExtensionFlags language extensions
extensionFlags :: IntSet,
-- | Message output action: use "ErrUtils" instead of this if you can
log_action :: LogAction,
haddockOptions :: Maybe String,
-- | what kind of {-# SCC #-} to add automatically
profAuto :: ProfAuto
}
data ProfAuto
= NoProfAuto -- ^ no SCC annotations added
| ProfAutoAll -- ^ top-level and nested functions are annotated
| ProfAutoTop -- ^ top-level functions annotated only
| ProfAutoExports -- ^ exported functions annotated only
| ProfAutoCalls -- ^ annotate call-sites
deriving (Enum)
data Settings = Settings {
sTargetPlatform :: Platform, -- Filled in by SysTools
sGhcUsagePath :: FilePath, -- Filled in by SysTools
sGhciUsagePath :: FilePath, -- ditto
sTopDir :: FilePath,
sTmpDir :: String, -- no trailing '/'
-- You shouldn't need to look things up in rawSettings directly.
-- They should have their own fields instead.
sRawSettings :: [(String, String)],
sExtraGccViaCFlags :: [String],
sSystemPackageConfig :: FilePath,
-- commands for particular phases
sPgm_L :: String,
sPgm_P :: (String,[Option]),
sPgm_F :: String,
sPgm_c :: (String,[Option]),
sPgm_s :: (String,[Option]),
sPgm_a :: (String,[Option]),
sPgm_l :: (String,[Option]),
sPgm_dll :: (String,[Option]),
sPgm_T :: String,
sPgm_sysman :: String,
sPgm_windres :: String,
sPgm_lo :: (String,[Option]), -- LLVM: opt llvm optimiser
sPgm_lc :: (String,[Option]), -- LLVM: llc static compiler
-- options for particular phases
sOpt_L :: [String],
sOpt_P :: [String],
sOpt_F :: [String],
sOpt_c :: [String],
sOpt_a :: [String],
sOpt_l :: [String],
sOpt_windres :: [String],
sOpt_lo :: [String], -- LLVM: llvm optimiser
sOpt_lc :: [String] -- LLVM: llc static compiler
}
targetPlatform :: DynFlags -> Platform
targetPlatform dflags = sTargetPlatform (settings dflags)
ghcUsagePath :: DynFlags -> FilePath
ghcUsagePath dflags = sGhcUsagePath (settings dflags)
ghciUsagePath :: DynFlags -> FilePath
ghciUsagePath dflags = sGhciUsagePath (settings dflags)
topDir :: DynFlags -> FilePath
topDir dflags = sTopDir (settings dflags)
tmpDir :: DynFlags -> String
tmpDir dflags = sTmpDir (settings dflags)
rawSettings :: DynFlags -> [(String, String)]
rawSettings dflags = sRawSettings (settings dflags)
extraGccViaCFlags :: DynFlags -> [String]
extraGccViaCFlags dflags = sExtraGccViaCFlags (settings dflags)
systemPackageConfig :: DynFlags -> FilePath
systemPackageConfig dflags = sSystemPackageConfig (settings dflags)
pgm_L :: DynFlags -> String
pgm_L dflags = sPgm_L (settings dflags)
pgm_P :: DynFlags -> (String,[Option])
pgm_P dflags = sPgm_P (settings dflags)
pgm_F :: DynFlags -> String
pgm_F dflags = sPgm_F (settings dflags)
pgm_c :: DynFlags -> (String,[Option])
pgm_c dflags = sPgm_c (settings dflags)
pgm_s :: DynFlags -> (String,[Option])
pgm_s dflags = sPgm_s (settings dflags)
pgm_a :: DynFlags -> (String,[Option])
pgm_a dflags = sPgm_a (settings dflags)
pgm_l :: DynFlags -> (String,[Option])
pgm_l dflags = sPgm_l (settings dflags)
pgm_dll :: DynFlags -> (String,[Option])
pgm_dll dflags = sPgm_dll (settings dflags)
pgm_T :: DynFlags -> String
pgm_T dflags = sPgm_T (settings dflags)
pgm_sysman :: DynFlags -> String
pgm_sysman dflags = sPgm_sysman (settings dflags)
pgm_windres :: DynFlags -> String
pgm_windres dflags = sPgm_windres (settings dflags)
pgm_lo :: DynFlags -> (String,[Option])
pgm_lo dflags = sPgm_lo (settings dflags)
pgm_lc :: DynFlags -> (String,[Option])
pgm_lc dflags = sPgm_lc (settings dflags)
opt_L :: DynFlags -> [String]
opt_L dflags = sOpt_L (settings dflags)
opt_P :: DynFlags -> [String]
opt_P dflags = sOpt_P (settings dflags)
opt_F :: DynFlags -> [String]
opt_F dflags = sOpt_F (settings dflags)
opt_c :: DynFlags -> [String]
opt_c dflags = sOpt_c (settings dflags)
opt_a :: DynFlags -> [String]
opt_a dflags = sOpt_a (settings dflags)
opt_l :: DynFlags -> [String]
opt_l dflags = sOpt_l (settings dflags)
opt_windres :: DynFlags -> [String]
opt_windres dflags = sOpt_windres (settings dflags)
opt_lo :: DynFlags -> [String]
opt_lo dflags = sOpt_lo (settings dflags)
opt_lc :: DynFlags -> [String]
opt_lc dflags = sOpt_lc (settings dflags)
wayNames :: DynFlags -> [WayName]
wayNames = map wayName . ways
-- | The target code type of the compilation (if any).
--
-- Whenever you change the target, also make sure to set 'ghcLink' to
-- something sensible.
--
-- 'HscNothing' can be used to avoid generating any output, however, note
-- that:
--
-- * This will not run the desugaring step, thus no warnings generated in
-- this step will be output. In particular, this includes warnings related
-- to pattern matching. You can run the desugarer manually using
-- 'GHC.desugarModule'.
--
-- * If a program uses Template Haskell the typechecker may try to run code
-- from an imported module. This will fail if no code has been generated
-- for this module. You can use 'GHC.needsTemplateHaskell' to detect
-- whether this might be the case and choose to either switch to a
-- different target or avoid typechecking such modules. (The latter may
-- preferable for security reasons.)
--
data HscTarget
= HscC -- ^ Generate C code.
| HscAsm -- ^ Generate assembly using the native code generator.
| HscLlvm -- ^ Generate assembly using the llvm code generator.
| HscInterpreted -- ^ Generate bytecode. (Requires 'LinkInMemory')
| HscNothing -- ^ Don't generate any code. See notes above.
deriving (Eq, Show)
showHscTargetFlag :: HscTarget -> String
showHscTargetFlag HscC = "-fvia-c"
showHscTargetFlag HscAsm = "-fasm"
showHscTargetFlag HscLlvm = "-fllvm"
showHscTargetFlag HscInterpreted = "-fbyte-code"
showHscTargetFlag HscNothing = "-fno-code"
-- | Will this target result in an object file on the disk?
isObjectTarget :: HscTarget -> Bool
isObjectTarget HscC = True
isObjectTarget HscAsm = True
isObjectTarget HscLlvm = True
isObjectTarget _ = False
-- | Does this target retain *all* top-level bindings for a module,
-- rather than just the exported bindings, in the TypeEnv and compiled
-- code (if any)? In interpreted mode we do this, so that GHCi can
-- call functions inside a module. In HscNothing mode we also do it,
-- so that Haddock can get access to the GlobalRdrEnv for a module
-- after typechecking it.
targetRetainsAllBindings :: HscTarget -> Bool
targetRetainsAllBindings HscInterpreted = True
targetRetainsAllBindings HscNothing = True
targetRetainsAllBindings _ = False
-- | The 'GhcMode' tells us whether we're doing multi-module
-- compilation (controlled via the "GHC" API) or one-shot
-- (single-module) compilation. This makes a difference primarily to
-- the "Finder": in one-shot mode we look for interface files for
-- imported modules, but in multi-module mode we look for source files
-- in order to check whether they need to be recompiled.
data GhcMode
= CompManager -- ^ @\-\-make@, GHCi, etc.
| OneShot -- ^ @ghc -c Foo.hs@
| MkDepend -- ^ @ghc -M@, see "Finder" for why we need this
deriving Eq
instance Outputable GhcMode where
ppr CompManager = ptext (sLit "CompManager")
ppr OneShot = ptext (sLit "OneShot")
ppr MkDepend = ptext (sLit "MkDepend")
isOneShot :: GhcMode -> Bool
isOneShot OneShot = True
isOneShot _other = False
-- | What to do in the link step, if there is one.
data GhcLink
= NoLink -- ^ Don't link at all
| LinkBinary -- ^ Link object code into a binary
| LinkInMemory -- ^ Use the in-memory dynamic linker (works for both
-- bytecode and object code).
| LinkDynLib -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
deriving (Eq, Show)
isNoLink :: GhcLink -> Bool
isNoLink NoLink = True
isNoLink _ = False
-- Is it worth evaluating this Bool and caching it in the DynFlags value
-- during initDynFlags?
doingTickyProfiling :: DynFlags -> Bool
doingTickyProfiling _ = opt_Ticky
-- XXX -ticky is a static flag, because it implies -debug which is also
-- static. If the way flags were made dynamic, we could fix this.
data PackageFlag
= ExposePackage String
| ExposePackageId String
| HidePackage String
| IgnorePackage String
| TrustPackage String
| DistrustPackage String
deriving Eq
defaultHscTarget :: HscTarget
defaultHscTarget = defaultObjectTarget
-- | The 'HscTarget' value corresponding to the default way to create
-- object files on the current platform.
defaultObjectTarget :: HscTarget
defaultObjectTarget
| cGhcUnregisterised == "YES" = HscC
| cGhcWithNativeCodeGen == "YES" = HscAsm
| otherwise = HscLlvm
data DynLibLoader
= Deployable
| SystemDependent
deriving Eq
data RtsOptsEnabled = RtsOptsNone | RtsOptsSafeOnly | RtsOptsAll
deriving (Show)
-- | Used by 'GHC.newSession' to partially initialize a new 'DynFlags' value
initDynFlags :: DynFlags -> IO DynFlags
initDynFlags dflags = do
-- someday these will be dynamic flags
ways <- readIORef v_Ways
refFilesToClean <- newIORef []
refDirsToClean <- newIORef Map.empty
refGeneratedDumps <- newIORef Set.empty
return dflags{
ways = ways,
buildTag = mkBuildTag (filter (not . wayRTSOnly) ways),
rtsBuildTag = mkBuildTag ways,
filesToClean = refFilesToClean,
dirsToClean = refDirsToClean,
generatedDumps = refGeneratedDumps
}
-- | The normal 'DynFlags'. Note that they is not suitable for use in this form
-- and must be fully initialized by 'GHC.newSession' first.
defaultDynFlags :: Settings -> DynFlags
defaultDynFlags mySettings =
DynFlags {
ghcMode = CompManager,
ghcLink = LinkBinary,
hscTarget = defaultHscTarget,
hscOutName = "",
extCoreName = "",
verbosity = 0,
optLevel = 0,
simplPhases = 2,
maxSimplIterations = 4,
shouldDumpSimplPhase = Nothing,
ruleCheck = Nothing,
simplTickFactor = 100,
specConstrThreshold = Just 2000,
specConstrCount = Just 3,
liberateCaseThreshold = Just 2000,
floatLamArgs = Just 0, -- Default: float only if no fvs
strictnessBefore = [],
cmdlineHcIncludes = [],
importPaths = ["."],
mainModIs = mAIN,
mainFunIs = Nothing,
ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
thisPackage = mainPackageId,
objectDir = Nothing,
dylibInstallName = Nothing,
hiDir = Nothing,
stubDir = Nothing,
dumpDir = Nothing,
objectSuf = phaseInputExt StopLn,
hcSuf = phaseInputExt HCc,
hiSuf = "hi",
pluginModNames = [],
pluginModNameOpts = [],
outputFile = Nothing,
outputHi = Nothing,
dynLibLoader = SystemDependent,
dumpPrefix = Nothing,
dumpPrefixForce = Nothing,
includePaths = [],
libraryPaths = [],
frameworkPaths = [],
cmdlineFrameworks = [],
rtsOpts = Nothing,
rtsOptsEnabled = RtsOptsSafeOnly,
hpcDir = ".hpc",
extraPkgConfs = [],
packageFlags = [],
pkgDatabase = Nothing,
pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
ways = panic "defaultDynFlags: No ways",
buildTag = panic "defaultDynFlags: No buildTag",
rtsBuildTag = panic "defaultDynFlags: No rtsBuildTag",
splitInfo = Nothing,
settings = mySettings,
-- ghc -M values
depMakefile = "Makefile",
depIncludePkgDeps = False,
depExcludeMods = [],
depSuffixes = [],
-- end of ghc -M values
filesToClean = panic "defaultDynFlags: No filesToClean",
dirsToClean = panic "defaultDynFlags: No dirsToClean",
generatedDumps = panic "defaultDynFlags: No generatedDumps",
haddockOptions = Nothing,
flags = IntSet.fromList (map fromEnum defaultFlags),
warningFlags = IntSet.fromList (map fromEnum standardWarnings),
language = Nothing,
safeHaskell = Sf_SafeInfered,
thOnLoc = noSrcSpan,
newDerivOnLoc = noSrcSpan,
pkgTrustOnLoc = noSrcSpan,
warnSafeOnLoc = noSrcSpan,
warnUnsafeOnLoc = noSrcSpan,
extensions = [],
extensionFlags = flattenExtensionFlags Nothing [],
log_action = defaultLogAction,
profAuto = NoProfAuto
}
type LogAction = Severity -> SrcSpan -> PprStyle -> Message -> IO ()
defaultLogAction :: LogAction
defaultLogAction severity srcSpan style msg
= case severity of
SevOutput -> printSDoc msg style
SevInfo -> printErrs msg style
SevFatal -> printErrs msg style
_ -> do hPutChar stderr '\n'
printErrs (mkLocMessage srcSpan msg) style
-- careful (#2302): printErrs prints in UTF-8, whereas
-- converting to string first and using hPutStr would
-- just emit the low 8 bits of each unicode char.
{-
Note [Verbosity levels]
~~~~~~~~~~~~~~~~~~~~~~~
0 | print errors & warnings only
1 | minimal verbosity: print "compiling M ... done." for each module.
2 | equivalent to -dshow-passes
3 | equivalent to existing "ghc -v"
4 | "ghc -v -ddump-most"
5 | "ghc -v -ddump-all"
-}
data OnOff a = On a
| Off a
-- OnOffs accumulate in reverse order, so we use foldr in order to
-- process them in the right order
flattenExtensionFlags :: Maybe Language -> [OnOff ExtensionFlag] -> IntSet
flattenExtensionFlags ml = foldr f defaultExtensionFlags
where f (On f) flags = IntSet.insert (fromEnum f) flags
f (Off f) flags = IntSet.delete (fromEnum f) flags
defaultExtensionFlags = IntSet.fromList (map fromEnum (languageExtensions ml))
languageExtensions :: Maybe Language -> [ExtensionFlag]
languageExtensions Nothing
-- Nothing => the default case
= Opt_NondecreasingIndentation -- This has been on by default for some time
: delete Opt_DatatypeContexts -- The Haskell' committee decided to
-- remove datatype contexts from the
-- language:
-- http://www.haskell.org/pipermail/haskell-prime/2011-January/003335.html
(languageExtensions (Just Haskell2010))
-- NB: MonoPatBinds is no longer the default
languageExtensions (Just Haskell98)
= [Opt_ImplicitPrelude,
Opt_MonomorphismRestriction,
Opt_NPlusKPatterns,
Opt_DatatypeContexts,
Opt_TraditionalRecordSyntax,
Opt_NondecreasingIndentation
-- strictly speaking non-standard, but we always had this
-- on implicitly before the option was added in 7.1, and
-- turning it off breaks code, so we're keeping it on for
-- backwards compatibility. Cabal uses -XHaskell98 by
-- default unless you specify another language.
]
languageExtensions (Just Haskell2010)
= [Opt_ImplicitPrelude,
Opt_MonomorphismRestriction,
Opt_DatatypeContexts,
Opt_TraditionalRecordSyntax,
Opt_EmptyDataDecls,
Opt_ForeignFunctionInterface,
Opt_PatternGuards,
Opt_DoAndIfThenElse,
Opt_RelaxedPolyRec]
-- | Test whether a 'DynFlag' is set
dopt :: DynFlag -> DynFlags -> Bool
dopt f dflags = fromEnum f `IntSet.member` flags dflags
-- | Set a 'DynFlag'
dopt_set :: DynFlags -> DynFlag -> DynFlags
dopt_set dfs f = dfs{ flags = IntSet.insert (fromEnum f) (flags dfs) }
-- | Unset a 'DynFlag'
dopt_unset :: DynFlags -> DynFlag -> DynFlags
dopt_unset dfs f = dfs{ flags = IntSet.delete (fromEnum f) (flags dfs) }
-- | Test whether a 'WarningFlag' is set
wopt :: WarningFlag -> DynFlags -> Bool
wopt f dflags = fromEnum f `IntSet.member` warningFlags dflags
-- | Set a 'WarningFlag'
wopt_set :: DynFlags -> WarningFlag -> DynFlags
wopt_set dfs f = dfs{ warningFlags = IntSet.insert (fromEnum f) (warningFlags dfs) }
-- | Unset a 'WarningFlag'
wopt_unset :: DynFlags -> WarningFlag -> DynFlags
wopt_unset dfs f = dfs{ warningFlags = IntSet.delete (fromEnum f) (warningFlags dfs) }
-- | Test whether a 'ExtensionFlag' is set
xopt :: ExtensionFlag -> DynFlags -> Bool
xopt f dflags = fromEnum f `IntSet.member` extensionFlags dflags
-- | Set a 'ExtensionFlag'
xopt_set :: DynFlags -> ExtensionFlag -> DynFlags
xopt_set dfs f
= let onoffs = On f : extensions dfs
in dfs { extensions = onoffs,
extensionFlags = flattenExtensionFlags (language dfs) onoffs }
-- | Unset a 'ExtensionFlag'
xopt_unset :: DynFlags -> ExtensionFlag -> DynFlags
xopt_unset dfs f
= let onoffs = Off f : extensions dfs
in dfs { extensions = onoffs,
extensionFlags = flattenExtensionFlags (language dfs) onoffs }
-- | Set the Haskell language standard to use
setLanguage :: Language -> DynP ()
setLanguage l = upd f
where f dfs = let mLang = Just l
oneoffs = extensions dfs
in dfs {
language = mLang,
extensionFlags = flattenExtensionFlags mLang oneoffs
}
-- | Some modules have dependencies on others through the DynFlags rather than textual imports
dynFlagDependencies :: DynFlags -> [ModuleName]
dynFlagDependencies = pluginModNames
-- | Is the -fpackage-trust mode on
packageTrustOn :: DynFlags -> Bool
packageTrustOn = dopt Opt_PackageTrust
-- | Is Safe Haskell on in some way (including inference mode)
safeHaskellOn :: DynFlags -> Bool
safeHaskellOn dflags = safeHaskell dflags /= Sf_None
-- | Is the Safe Haskell safe language in use
safeLanguageOn :: DynFlags -> Bool
safeLanguageOn dflags = safeHaskell dflags == Sf_Safe
-- | Is the Safe Haskell safe inference mode active
safeInferOn :: DynFlags -> Bool
safeInferOn dflags = safeHaskell dflags == Sf_SafeInfered
-- | Test if Safe Imports are on in some form
safeImportsOn :: DynFlags -> Bool
safeImportsOn dflags = safeHaskell dflags == Sf_Unsafe ||
safeHaskell dflags == Sf_Trustworthy ||
safeHaskell dflags == Sf_Safe
-- | Set a 'Safe Haskell' flag
setSafeHaskell :: SafeHaskellMode -> DynP ()
setSafeHaskell s = updM f
where f dfs = do
let sf = safeHaskell dfs
safeM <- combineSafeFlags sf s
return $ dfs { safeHaskell = safeM }
-- | Are all direct imports required to be safe for this Safe Haskell mode?
-- Direct imports are when the code explicitly imports a module
safeDirectImpsReq :: DynFlags -> Bool
safeDirectImpsReq d = safeLanguageOn d
-- | Are all implicit imports required to be safe for this Safe Haskell mode?
-- Implicit imports are things in the prelude. e.g System.IO when print is used.
safeImplicitImpsReq :: DynFlags -> Bool
safeImplicitImpsReq d = safeLanguageOn d
-- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags.
-- This makes Safe Haskell very much a monoid but for now I prefer this as I don't
-- want to export this functionality from the module but do want to export the
-- type constructors.
combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode
combineSafeFlags a b | a == Sf_SafeInfered = return b
| b == Sf_SafeInfered = return a
| a == Sf_None = return b
| b == Sf_None = return a
| a == b = return a
| otherwise = addErr errm >> return (panic errm)
where errm = "Incompatible Safe Haskell flags! ("
++ showPpr a ++ ", " ++ showPpr b ++ ")"
-- | A list of unsafe flags under Safe Haskell. Tuple elements are:
-- * name of the flag
-- * function to get srcspan that enabled the flag
-- * function to test if the flag is on
-- * function to turn the flag off
unsafeFlags :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool, DynFlags -> DynFlags)]
unsafeFlags = [("-XGeneralizedNewtypeDeriving", newDerivOnLoc,
xopt Opt_GeneralizedNewtypeDeriving,
flip xopt_unset Opt_GeneralizedNewtypeDeriving),
("-XTemplateHaskell", thOnLoc,
xopt Opt_TemplateHaskell,
flip xopt_unset Opt_TemplateHaskell)]
-- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order
getOpts :: DynFlags -- ^ 'DynFlags' to retrieve the options from
-> (DynFlags -> [a]) -- ^ Relevant record accessor: one of the @opt_*@ accessors
-> [a] -- ^ Correctly ordered extracted options
getOpts dflags opts = reverse (opts dflags)
-- We add to the options from the front, so we need to reverse the list
-- | Gets the verbosity flag for the current verbosity level. This is fed to
-- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included
getVerbFlags :: DynFlags -> [String]
getVerbFlags dflags
| verbosity dflags >= 4 = ["-v"]
| otherwise = []
setObjectDir, setHiDir, setStubDir, setDumpDir, setOutputDir,
setDylibInstallName,
setObjectSuf, setHiSuf, setHcSuf, parseDynLibLoaderMode,
setPgmP, addOptl, addOptP,
addCmdlineFramework, addHaddockOpts
:: String -> DynFlags -> DynFlags
setOutputFile, setOutputHi, setDumpPrefixForce
:: Maybe String -> DynFlags -> DynFlags
setObjectDir f d = d{ objectDir = Just f}
setHiDir f d = d{ hiDir = Just f}
setStubDir f d = d{ stubDir = Just f, includePaths = f : includePaths d }
-- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
-- \#included from the .hc file when compiling via C (i.e. unregisterised
-- builds).
setDumpDir f d = d{ dumpDir = Just f}
setOutputDir f = setObjectDir f . setHiDir f . setStubDir f . setDumpDir f
setDylibInstallName f d = d{ dylibInstallName = Just f}
setObjectSuf f d = d{ objectSuf = f}
setHiSuf f d = d{ hiSuf = f}
setHcSuf f d = d{ hcSuf = f}
setOutputFile f d = d{ outputFile = f}
setOutputHi f d = d{ outputHi = f}
addPluginModuleName :: String -> DynFlags -> DynFlags
addPluginModuleName name d = d { pluginModNames = (mkModuleName name) : (pluginModNames d) }
addPluginModuleNameOption :: String -> DynFlags -> DynFlags
addPluginModuleNameOption optflag d = d { pluginModNameOpts = (mkModuleName m, option) : (pluginModNameOpts d) }
where (m, rest) = break (== ':') optflag
option = case rest of
[] -> "" -- should probably signal an error
(_:plug_opt) -> plug_opt -- ignore the ':' from break
parseDynLibLoaderMode f d =
case splitAt 8 f of
("deploy", "") -> d{ dynLibLoader = Deployable }
("sysdep", "") -> d{ dynLibLoader = SystemDependent }
_ -> ghcError (CmdLineError ("Unknown dynlib loader: " ++ f))
setDumpPrefixForce f d = d { dumpPrefixForce = f}
-- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
-- Config.hs should really use Option.
setPgmP f = let (pgm:args) = words f in alterSettings (\s -> s { sPgm_P = (pgm, map Option args)})
addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s})
addOptP f = alterSettings (\s -> s { sOpt_P = f : sOpt_P s})
setDepMakefile :: FilePath -> DynFlags -> DynFlags
setDepMakefile f d = d { depMakefile = deOptDep f }
setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags
setDepIncludePkgDeps b d = d { depIncludePkgDeps = b }
addDepExcludeMod :: String -> DynFlags -> DynFlags
addDepExcludeMod m d
= d { depExcludeMods = mkModuleName (deOptDep m) : depExcludeMods d }
addDepSuffix :: FilePath -> DynFlags -> DynFlags
addDepSuffix s d = d { depSuffixes = deOptDep s : depSuffixes d }
-- XXX Legacy code:
-- We used to use "-optdep-flag -optdeparg", so for legacy applications
-- we need to strip the "-optdep" off of the arg
deOptDep :: String -> String
deOptDep x = case stripPrefix "-optdep" x of
Just rest -> rest
Nothing -> x
addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
addHaddockOpts f d = d{ haddockOptions = Just f}
-- -----------------------------------------------------------------------------
-- Command-line options
-- | When invoking external tools as part of the compilation pipeline, we
-- pass these a sequence of options on the command-line. Rather than
-- just using a list of Strings, we use a type that allows us to distinguish
-- between filepaths and 'other stuff'. The reason for this is that
-- this type gives us a handle on transforming filenames, and filenames only,
-- to whatever format they're expected to be on a particular platform.
data Option
= FileOption -- an entry that _contains_ filename(s) / filepaths.
String -- a non-filepath prefix that shouldn't be
-- transformed (e.g., "/out=")
String -- the filepath/filename portion
| Option String
deriving ( Eq )
showOpt :: Option -> String
showOpt (FileOption pre f) = pre ++ f
showOpt (Option s) = s
-----------------------------------------------------------------------------
-- Setting the optimisation level
updOptLevel :: Int -> DynFlags -> DynFlags
-- ^ Sets the 'DynFlags' to be appropriate to the optimisation level
updOptLevel n dfs
= dfs2{ optLevel = final_n }
where
final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
dfs1 = foldr (flip dopt_unset) dfs remove_dopts
dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
extra_dopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
remove_dopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
-- -----------------------------------------------------------------------------
-- StgToDo: abstraction of stg-to-stg passes to run.
data StgToDo
= StgDoMassageForProfiling -- should be (next to) last
-- There's also setStgVarInfo, but its absolute "lastness"
-- is so critical that it is hardwired in (no flag).
| D_stg_stats
getStgToDo :: DynFlags -> [StgToDo]
getStgToDo dflags
= todo2
where
stg_stats = dopt Opt_StgStats dflags
todo1 = if stg_stats then [D_stg_stats] else []
todo2 | WayProf `elem` wayNames dflags
= StgDoMassageForProfiling : todo1
| otherwise
= todo1
{- **********************************************************************
%* *
DynFlags parser
%* *
%********************************************************************* -}
-- -----------------------------------------------------------------------------
-- Parsing the dynamic flags.
-- | Parse dynamic flags from a list of command line arguments. Returns the
-- the parsed 'DynFlags', the left-over arguments, and a list of warnings.
-- Throws a 'UsageError' if errors occurred during parsing (such as unknown
-- flags or missing arguments).
parseDynamicFlagsCmdLine :: Monad m =>
DynFlags -> [Located String]
-> m (DynFlags, [Located String], [Located String])
-- ^ Updated 'DynFlags', left-over arguments, and
-- list of warnings.
parseDynamicFlagsCmdLine dflags args = parseDynamicFlags dflags args True
-- | Like 'parseDynamicFlagsCmdLine' but does not allow the package flags
-- (-package, -hide-package, -ignore-package, -hide-all-packages, -package-conf).
-- Used to parse flags set in a modules pragma.
parseDynamicFilePragma :: Monad m =>
DynFlags -> [Located String]
-> m (DynFlags, [Located String], [Located String])
-- ^ Updated 'DynFlags', left-over arguments, and
-- list of warnings.
parseDynamicFilePragma dflags args = parseDynamicFlags dflags args False
parseDynamicFlags :: Monad m =>
DynFlags -> [Located String] -> Bool
-> m (DynFlags, [Located String], [Located String])
parseDynamicFlags dflags0 args cmdline = do
-- XXX Legacy support code
-- We used to accept things like
-- optdep-f -optdepdepend
-- optdep-f -optdep depend
-- optdep -f -optdepdepend
-- optdep -f -optdep depend
-- but the spaces trip up proper argument handling. So get rid of them.
let f (L p "-optdep" : L _ x : xs) = (L p ("-optdep" ++ x)) : f xs
f (x : xs) = x : f xs
f xs = xs
args' = f args
-- Note: -ignore-package (package_flags) must precede -i* (dynamic_flags)
flag_spec | cmdline = package_flags ++ dynamic_flags
| otherwise = dynamic_flags
let ((leftover, errs, warns), dflags1)
= runCmdLine (processArgs flag_spec args') dflags0
when (not (null errs)) $ ghcError $ errorsToGhcException errs
-- check for disabled flags in safe haskell
let (dflags2, sh_warns) = safeFlagCheck cmdline dflags1
return (dflags2, leftover, sh_warns ++ warns)
-- | Check (and potentially disable) any extensions that aren't allowed
-- in safe mode.
safeFlagCheck :: Bool -> DynFlags -> (DynFlags, [Located String])
safeFlagCheck _ dflags | not (safeLanguageOn dflags || safeInferOn dflags)
= (dflags, [])
safeFlagCheck cmdl dflags =
case safeLanguageOn dflags of
True -> (dflags', warns)
-- throw error if -fpackage-trust by itself with no safe haskell flag
False | not cmdl && safeInferOn dflags && packageTrustOn dflags
-> (dopt_unset dflags' Opt_PackageTrust,
[L (pkgTrustOnLoc dflags') $
"Warning: -fpackage-trust ignored;" ++
" must be specified with a Safe Haskell flag"]
)
False | null warns && safeInfOk
-> (dflags', [])
| otherwise
-> (dflags' { safeHaskell = Sf_None }, [])
-- Have we infered Unsafe?
-- See Note [HscMain . Safe Haskell Inference]
where
-- TODO: Can we do better than this for inference?
safeInfOk = not $ xopt Opt_OverlappingInstances dflags
(dflags', warns) = foldl check_method (dflags, []) unsafeFlags
check_method (df, warns) (str,loc,test,fix)
| test df = (apFix fix df, warns ++ safeFailure (loc dflags) str)
| otherwise = (df, warns)
apFix f = if safeInferOn dflags then id else f
safeFailure loc str = [L loc $ "Warning: " ++ str ++ " is not allowed in"
++ " Safe Haskell; ignoring " ++ str]
{- **********************************************************************
%* *
DynFlags specifications
%* *
%********************************************************************* -}
allFlags :: [String]
allFlags = map ('-':) $
[ flagName flag | flag <- dynamic_flags ++ package_flags, ok (flagOptKind flag) ] ++
map ("fno-"++) fflags ++
map ("f"++) fflags ++
map ("X"++) supportedExtensions
where ok (PrefixPred _ _) = False
ok _ = True
fflags = fflags0 ++ fflags1 ++ fflags2
fflags0 = [ name | (name, _, _) <- fFlags ]
fflags1 = [ name | (name, _, _) <- fWarningFlags ]
fflags2 = [ name | (name, _, _) <- fLangFlags ]
--------------- The main flags themselves ------------------
dynamic_flags :: [Flag (CmdLineP DynFlags)]
dynamic_flags = [
Flag "n" (NoArg (addWarn "The -n flag is deprecated and no longer has any effect"))
, Flag "cpp" (NoArg (setExtensionFlag Opt_Cpp))
, Flag "F" (NoArg (setDynFlag Opt_Pp))
, Flag "#include"
(HasArg (\s -> do addCmdlineHCInclude s
addWarn "-#include and INCLUDE pragmas are deprecated: They no longer have any effect"))
, Flag "v" (OptIntSuffix setVerbosity)
------- Specific phases --------------------------------------------
-- need to appear before -pgmL to be parsed as LLVM flags.
, Flag "pgmlo" (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])})))
, Flag "pgmlc" (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])})))
, Flag "pgmL" (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f})))
, Flag "pgmP" (hasArg setPgmP)
, Flag "pgmF" (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f})))
, Flag "pgmc" (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[])})))
, Flag "pgmm" (HasArg (\_ -> addWarn "The -pgmm flag does nothing; it will be removed in a future GHC release"))
, Flag "pgms" (hasArg (\f -> alterSettings (\s -> s { sPgm_s = (f,[])})))
, Flag "pgma" (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])})))
, Flag "pgml" (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])})))
, Flag "pgmdll" (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])})))
, Flag "pgmwindres" (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f})))
-- need to appear before -optl/-opta to be parsed as LLVM flags.
, Flag "optlo" (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s})))
, Flag "optlc" (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s})))
, Flag "optL" (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s})))
, Flag "optP" (hasArg addOptP)
, Flag "optF" (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s})))
, Flag "optc" (hasArg (\f -> alterSettings (\s -> s { sOpt_c = f : sOpt_c s})))
, Flag "optm" (HasArg (\_ -> addWarn "The -optm flag does nothing; it will be removed in a future GHC release"))
, Flag "opta" (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s})))
, Flag "optl" (hasArg addOptl)
, Flag "optwindres" (hasArg (\f -> alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s})))
, Flag "split-objs"
(NoArg (if can_split
then setDynFlag Opt_SplitObjs
else addWarn "ignoring -fsplit-objs"))
-------- ghc -M -----------------------------------------------------
, Flag "dep-suffix" (hasArg addDepSuffix)
, Flag "optdep-s" (hasArgDF addDepSuffix "Use -dep-suffix instead")
, Flag "dep-makefile" (hasArg setDepMakefile)
, Flag "optdep-f" (hasArgDF setDepMakefile "Use -dep-makefile instead")
, Flag "optdep-w" (NoArg (deprecate "doesn't do anything"))
, Flag "include-pkg-deps" (noArg (setDepIncludePkgDeps True))
, Flag "optdep--include-prelude" (noArgDF (setDepIncludePkgDeps True) "Use -include-pkg-deps instead")
, Flag "optdep--include-pkg-deps" (noArgDF (setDepIncludePkgDeps True) "Use -include-pkg-deps instead")
, Flag "exclude-module" (hasArg addDepExcludeMod)
, Flag "optdep--exclude-module" (hasArgDF addDepExcludeMod "Use -exclude-module instead")
, Flag "optdep-x" (hasArgDF addDepExcludeMod "Use -exclude-module instead")
-------- Linking ----------------------------------------------------
, Flag "no-link" (noArg (\d -> d{ ghcLink=NoLink }))
, Flag "shared" (noArg (\d -> d{ ghcLink=LinkDynLib }))
, Flag "dynload" (hasArg parseDynLibLoaderMode)
, Flag "dylib-install-name" (hasArg setDylibInstallName)
------- Libraries ---------------------------------------------------
, Flag "L" (Prefix addLibraryPath)
, Flag "l" (hasArg (addOptl . ("-l" ++)))
------- Frameworks --------------------------------------------------
-- -framework-path should really be -F ...
, Flag "framework-path" (HasArg addFrameworkPath)
, Flag "framework" (hasArg addCmdlineFramework)
------- Output Redirection ------------------------------------------
, Flag "odir" (hasArg setObjectDir)
, Flag "o" (sepArg (setOutputFile . Just))
, Flag "ohi" (hasArg (setOutputHi . Just ))
, Flag "osuf" (hasArg setObjectSuf)
, Flag "hcsuf" (hasArg setHcSuf)
, Flag "hisuf" (hasArg setHiSuf)
, Flag "hidir" (hasArg setHiDir)
, Flag "tmpdir" (hasArg setTmpDir)
, Flag "stubdir" (hasArg setStubDir)
, Flag "dumpdir" (hasArg setDumpDir)
, Flag "outputdir" (hasArg setOutputDir)
, Flag "ddump-file-prefix" (hasArg (setDumpPrefixForce . Just))
------- Keeping temporary files -------------------------------------
-- These can be singular (think ghc -c) or plural (think ghc --make)
, Flag "keep-hc-file" (NoArg (setDynFlag Opt_KeepHcFiles))
, Flag "keep-hc-files" (NoArg (setDynFlag Opt_KeepHcFiles))
, Flag "keep-s-file" (NoArg (setDynFlag Opt_KeepSFiles))
, Flag "keep-s-files" (NoArg (setDynFlag Opt_KeepSFiles))
, Flag "keep-raw-s-file" (NoArg (addWarn "The -keep-raw-s-file flag does nothing; it will be removed in a future GHC release"))
, Flag "keep-raw-s-files" (NoArg (addWarn "The -keep-raw-s-files flag does nothing; it will be removed in a future GHC release"))
, Flag "keep-llvm-file" (NoArg (do setObjTarget HscLlvm
setDynFlag Opt_KeepLlvmFiles))
, Flag "keep-llvm-files" (NoArg (do setObjTarget HscLlvm
setDynFlag Opt_KeepLlvmFiles))
-- This only makes sense as plural
, Flag "keep-tmp-files" (NoArg (setDynFlag Opt_KeepTmpFiles))
------- Miscellaneous ----------------------------------------------
, Flag "no-auto-link-packages" (NoArg (unSetDynFlag Opt_AutoLinkPackages))
, Flag "no-hs-main" (NoArg (setDynFlag Opt_NoHsMain))
, Flag "with-rtsopts" (HasArg setRtsOpts)
, Flag "rtsopts" (NoArg (setRtsOptsEnabled RtsOptsAll))
, Flag "rtsopts=all" (NoArg (setRtsOptsEnabled RtsOptsAll))
, Flag "rtsopts=some" (NoArg (setRtsOptsEnabled RtsOptsSafeOnly))
, Flag "rtsopts=none" (NoArg (setRtsOptsEnabled RtsOptsNone))
, Flag "no-rtsopts" (NoArg (setRtsOptsEnabled RtsOptsNone))
, Flag "main-is" (SepArg setMainIs)
, Flag "haddock" (NoArg (setDynFlag Opt_Haddock))
, Flag "haddock-opts" (hasArg addHaddockOpts)
, Flag "hpcdir" (SepArg setOptHpcDir)
------- recompilation checker --------------------------------------
, Flag "recomp" (NoArg (do unSetDynFlag Opt_ForceRecomp
deprecate "Use -fno-force-recomp instead"))
, Flag "no-recomp" (NoArg (do setDynFlag Opt_ForceRecomp
deprecate "Use -fforce-recomp instead"))
------ HsCpp opts ---------------------------------------------------
, Flag "D" (AnySuffix (upd . addOptP))
, Flag "U" (AnySuffix (upd . addOptP))
------- Include/Import Paths ----------------------------------------
, Flag "I" (Prefix addIncludePath)
, Flag "i" (OptPrefix addImportPath)
------ Debugging ----------------------------------------------------
, Flag "dstg-stats" (NoArg (setDynFlag Opt_StgStats))
, Flag "ddump-cmm" (setDumpFlag Opt_D_dump_cmm)
, Flag "ddump-raw-cmm" (setDumpFlag Opt_D_dump_raw_cmm)
, Flag "ddump-cmmz" (setDumpFlag Opt_D_dump_cmmz)
, Flag "ddump-cmmz-pretty" (setDumpFlag Opt_D_dump_cmmz_pretty)
, Flag "ddump-cmmz-cbe" (setDumpFlag Opt_D_dump_cmmz_cbe)
, Flag "ddump-cmmz-spills" (setDumpFlag Opt_D_dump_cmmz_spills)
, Flag "ddump-cmmz-proc" (setDumpFlag Opt_D_dump_cmmz_proc)
, Flag "ddump-cmmz-rewrite" (setDumpFlag Opt_D_dump_cmmz_rewrite)
, Flag "ddump-cmmz-dead" (setDumpFlag Opt_D_dump_cmmz_dead)
, Flag "ddump-cmmz-stub" (setDumpFlag Opt_D_dump_cmmz_stub)
, Flag "ddump-cmmz-sp" (setDumpFlag Opt_D_dump_cmmz_sp)
, Flag "ddump-cmmz-procmap" (setDumpFlag Opt_D_dump_cmmz_procmap)
, Flag "ddump-cmmz-split" (setDumpFlag Opt_D_dump_cmmz_split)
, Flag "ddump-cmmz-lower" (setDumpFlag Opt_D_dump_cmmz_lower)
, Flag "ddump-cmmz-info" (setDumpFlag Opt_D_dump_cmmz_info)
, Flag "ddump-cmmz-cafs" (setDumpFlag Opt_D_dump_cmmz_cafs)
, Flag "ddump-core-stats" (setDumpFlag Opt_D_dump_core_stats)
, Flag "ddump-cps-cmm" (setDumpFlag Opt_D_dump_cps_cmm)
, Flag "ddump-cvt-cmm" (setDumpFlag Opt_D_dump_cvt_cmm)
, Flag "ddump-asm" (setDumpFlag Opt_D_dump_asm)
, Flag "ddump-asm-native" (setDumpFlag Opt_D_dump_asm_native)
, Flag "ddump-asm-liveness" (setDumpFlag Opt_D_dump_asm_liveness)
, Flag "ddump-asm-coalesce" (setDumpFlag Opt_D_dump_asm_coalesce)
, Flag "ddump-asm-regalloc" (setDumpFlag Opt_D_dump_asm_regalloc)
, Flag "ddump-asm-conflicts" (setDumpFlag Opt_D_dump_asm_conflicts)
, Flag "ddump-asm-regalloc-stages" (setDumpFlag Opt_D_dump_asm_regalloc_stages)
, Flag "ddump-asm-stats" (setDumpFlag Opt_D_dump_asm_stats)
, Flag "ddump-asm-expanded" (setDumpFlag Opt_D_dump_asm_expanded)
, Flag "ddump-llvm" (NoArg (do setObjTarget HscLlvm
setDumpFlag' Opt_D_dump_llvm))
, Flag "ddump-cpranal" (setDumpFlag Opt_D_dump_cpranal)
, Flag "ddump-deriv" (setDumpFlag Opt_D_dump_deriv)
, Flag "ddump-ds" (setDumpFlag Opt_D_dump_ds)
, Flag "ddump-flatC" (setDumpFlag Opt_D_dump_flatC)
, Flag "ddump-foreign" (setDumpFlag Opt_D_dump_foreign)
, Flag "ddump-inlinings" (setDumpFlag Opt_D_dump_inlinings)
, Flag "ddump-rule-firings" (setDumpFlag Opt_D_dump_rule_firings)
, Flag "ddump-rule-rewrites" (setDumpFlag Opt_D_dump_rule_rewrites)
, Flag "ddump-occur-anal" (setDumpFlag Opt_D_dump_occur_anal)
, Flag "ddump-parsed" (setDumpFlag Opt_D_dump_parsed)
, Flag "ddump-rn" (setDumpFlag Opt_D_dump_rn)
, Flag "ddump-core-pipeline" (setDumpFlag Opt_D_dump_core_pipeline)
, Flag "ddump-simpl" (setDumpFlag Opt_D_dump_simpl)
, Flag "ddump-simpl-iterations" (setDumpFlag Opt_D_dump_simpl_iterations)
, Flag "ddump-simpl-phases" (OptPrefix setDumpSimplPhases)
, Flag "ddump-spec" (setDumpFlag Opt_D_dump_spec)
, Flag "ddump-prep" (setDumpFlag Opt_D_dump_prep)
, Flag "ddump-stg" (setDumpFlag Opt_D_dump_stg)
, Flag "ddump-stranal" (setDumpFlag Opt_D_dump_stranal)
, Flag "ddump-tc" (setDumpFlag Opt_D_dump_tc)
, Flag "ddump-types" (setDumpFlag Opt_D_dump_types)
, Flag "ddump-rules" (setDumpFlag Opt_D_dump_rules)
, Flag "ddump-cse" (setDumpFlag Opt_D_dump_cse)
, Flag "ddump-worker-wrapper" (setDumpFlag Opt_D_dump_worker_wrapper)
, Flag "ddump-rn-trace" (setDumpFlag Opt_D_dump_rn_trace)
, Flag "ddump-if-trace" (setDumpFlag Opt_D_dump_if_trace)
, Flag "ddump-cs-trace" (setDumpFlag Opt_D_dump_cs_trace)
, Flag "ddump-tc-trace" (setDumpFlag Opt_D_dump_tc_trace)
, Flag "ddump-vt-trace" (setDumpFlag Opt_D_dump_vt_trace)
, Flag "ddump-splices" (setDumpFlag Opt_D_dump_splices)
, Flag "ddump-rn-stats" (setDumpFlag Opt_D_dump_rn_stats)
, Flag "ddump-opt-cmm" (setDumpFlag Opt_D_dump_opt_cmm)
, Flag "ddump-simpl-stats" (setDumpFlag Opt_D_dump_simpl_stats)
, Flag "ddump-bcos" (setDumpFlag Opt_D_dump_BCOs)
, Flag "dsource-stats" (setDumpFlag Opt_D_source_stats)
, Flag "dverbose-core2core" (NoArg (do setVerbosity (Just 2)
setVerboseCore2Core))
, Flag "dverbose-stg2stg" (setDumpFlag Opt_D_verbose_stg2stg)
, Flag "ddump-hi" (setDumpFlag Opt_D_dump_hi)
, Flag "ddump-minimal-imports" (setDumpFlag Opt_D_dump_minimal_imports)
, Flag "ddump-vect" (setDumpFlag Opt_D_dump_vect)
, Flag "ddump-hpc" (setDumpFlag Opt_D_dump_ticked) -- back compat
, Flag "ddump-ticked" (setDumpFlag Opt_D_dump_ticked)
, Flag "ddump-mod-cycles" (setDumpFlag Opt_D_dump_mod_cycles)
, Flag "ddump-view-pattern-commoning" (setDumpFlag Opt_D_dump_view_pattern_commoning)
, Flag "ddump-to-file" (setDumpFlag Opt_DumpToFile)
, Flag "ddump-hi-diffs" (setDumpFlag Opt_D_dump_hi_diffs)
, Flag "ddump-rtti" (setDumpFlag Opt_D_dump_rtti)
, Flag "dcore-lint" (NoArg (setDynFlag Opt_DoCoreLinting))
, Flag "dstg-lint" (NoArg (setDynFlag Opt_DoStgLinting))
, Flag "dcmm-lint" (NoArg (setDynFlag Opt_DoCmmLinting))
, Flag "dasm-lint" (NoArg (setDynFlag Opt_DoAsmLinting))
, Flag "dshow-passes" (NoArg (do forceRecompile
setVerbosity $ Just 2))
, Flag "dfaststring-stats" (NoArg (setDynFlag Opt_D_faststring_stats))
, Flag "dno-llvm-mangler" (NoArg (setDynFlag Opt_NoLlvmMangler))
------ Machine dependant (-m<blah>) stuff ---------------------------
, Flag "monly-2-regs" (NoArg (addWarn "The -monly-2-regs flag does nothing; it will be removed in a future GHC release"))
, Flag "monly-3-regs" (NoArg (addWarn "The -monly-3-regs flag does nothing; it will be removed in a future GHC release"))
, Flag "monly-4-regs" (NoArg (addWarn "The -monly-4-regs flag does nothing; it will be removed in a future GHC release"))
, Flag "msse2" (NoArg (setDynFlag Opt_SSE2))
, Flag "msse4.2" (NoArg (setDynFlag Opt_SSE4_2))
------ Warning opts -------------------------------------------------
, Flag "W" (NoArg (mapM_ setWarningFlag minusWOpts))
, Flag "Werror" (NoArg (setDynFlag Opt_WarnIsError))
, Flag "Wwarn" (NoArg (unSetDynFlag Opt_WarnIsError))
, Flag "Wall" (NoArg (mapM_ setWarningFlag minusWallOpts))
, Flag "Wnot" (NoArg (do upd (\dfs -> dfs {warningFlags = IntSet.empty})
deprecate "Use -w instead"))
, Flag "w" (NoArg (upd (\dfs -> dfs {warningFlags = IntSet.empty})))
------ Plugin flags ------------------------------------------------
, Flag "fplugin-opt" (hasArg addPluginModuleNameOption)
, Flag "fplugin" (hasArg addPluginModuleName)
------ Optimisation flags ------------------------------------------
, Flag "O" (noArgM (setOptLevel 1))
, Flag "Onot" (noArgM (\dflags -> do deprecate "Use -O0 instead"
setOptLevel 0 dflags))
, Flag "Odph" (noArgM setDPHOpt)
, Flag "O" (optIntSuffixM (\mb_n -> setOptLevel (mb_n `orElse` 1)))
-- If the number is missing, use 1
, Flag "fsimplifier-phases" (intSuffix (\n d -> d{ simplPhases = n }))
, Flag "fmax-simplifier-iterations" (intSuffix (\n d -> d{ maxSimplIterations = n }))
, Flag "fsimpl-tick-factor" (intSuffix (\n d -> d{ simplTickFactor = n }))
, Flag "fspec-constr-threshold" (intSuffix (\n d -> d{ specConstrThreshold = Just n }))
, Flag "fno-spec-constr-threshold" (noArg (\d -> d{ specConstrThreshold = Nothing }))
, Flag "fspec-constr-count" (intSuffix (\n d -> d{ specConstrCount = Just n }))
, Flag "fno-spec-constr-count" (noArg (\d -> d{ specConstrCount = Nothing }))
, Flag "fliberate-case-threshold" (intSuffix (\n d -> d{ liberateCaseThreshold = Just n }))
, Flag "fno-liberate-case-threshold" (noArg (\d -> d{ liberateCaseThreshold = Nothing }))
, Flag "frule-check" (sepArg (\s d -> d{ ruleCheck = Just s }))
, Flag "fcontext-stack" (intSuffix (\n d -> d{ ctxtStkDepth = n }))
, Flag "fstrictness-before" (intSuffix (\n d -> d{ strictnessBefore = n : strictnessBefore d }))
, Flag "ffloat-lam-args" (intSuffix (\n d -> d{ floatLamArgs = Just n }))
, Flag "ffloat-all-lams" (noArg (\d -> d{ floatLamArgs = Nothing }))
------ Profiling ----------------------------------------------------
-- OLD profiling flags
, Flag "auto-all" (noArg (\d -> d { profAuto = ProfAutoAll } ))
, Flag "no-auto-all" (noArg (\d -> d { profAuto = NoProfAuto } ))
, Flag "auto" (noArg (\d -> d { profAuto = ProfAutoExports } ))
, Flag "no-auto" (noArg (\d -> d { profAuto = NoProfAuto } ))
, Flag "caf-all" (NoArg (setDynFlag Opt_AutoSccsOnIndividualCafs))
, Flag "no-caf-all" (NoArg (unSetDynFlag Opt_AutoSccsOnIndividualCafs))
-- NEW profiling flags
, Flag "fprof-auto" (noArg (\d -> d { profAuto = ProfAutoAll } ))
, Flag "fprof-auto-top" (noArg (\d -> d { profAuto = ProfAutoTop } ))
, Flag "fprof-auto-exported" (noArg (\d -> d { profAuto = ProfAutoExports } ))
, Flag "fprof-auto-calls" (noArg (\d -> d { profAuto = ProfAutoCalls } ))
, Flag "fno-prof-auto" (noArg (\d -> d { profAuto = NoProfAuto } ))
------ Compiler flags -----------------------------------------------
, Flag "fasm" (NoArg (setObjTarget HscAsm))
, Flag "fvia-c" (NoArg
(addWarn "The -fvia-c flag does nothing; it will be removed in a future GHC release"))
, Flag "fvia-C" (NoArg
(addWarn "The -fvia-C flag does nothing; it will be removed in a future GHC release"))
, Flag "fllvm" (NoArg (setObjTarget HscLlvm))
, Flag "fno-code" (NoArg (do upd $ \d -> d{ ghcLink=NoLink }
setTarget HscNothing))
, Flag "fbyte-code" (NoArg (setTarget HscInterpreted))
, Flag "fobject-code" (NoArg (setTarget defaultHscTarget))
, Flag "fglasgow-exts" (NoArg (enableGlasgowExts >> deprecate "Use individual extensions instead"))
, Flag "fno-glasgow-exts" (NoArg (disableGlasgowExts >> deprecate "Use individual extensions instead"))
------ Safe Haskell flags -------------------------------------------
, Flag "fpackage-trust" (NoArg setPackageTrust)
, Flag "fno-safe-infer" (NoArg (setSafeHaskell Sf_None))
]
++ map (mkFlag turnOn "f" setDynFlag ) fFlags
++ map (mkFlag turnOff "fno-" unSetDynFlag) fFlags
++ map (mkFlag turnOn "f" setWarningFlag ) fWarningFlags
++ map (mkFlag turnOff "fno-" unSetWarningFlag) fWarningFlags
++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlags
++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlags
++ map (mkFlag turnOn "X" setExtensionFlag ) xFlags
++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlags
++ map (mkFlag turnOn "X" setLanguage) languageFlags
++ map (mkFlag turnOn "X" setSafeHaskell) safeHaskellFlags
++ [ Flag "XGenerics" (NoArg (deprecate "it does nothing; look into -XDefaultSignatures and -XDeriveGeneric for generic programming support."))
, Flag "XNoGenerics" (NoArg (deprecate "it does nothing; look into -XDefaultSignatures and -XDeriveGeneric for generic programming support.")) ]
package_flags :: [Flag (CmdLineP DynFlags)]
package_flags = [
------- Packages ----------------------------------------------------
Flag "package-conf" (HasArg extraPkgConf_)
, Flag "no-user-package-conf" (NoArg (unSetDynFlag Opt_ReadUserPackageConf))
, Flag "package-name" (hasArg setPackageName)
, Flag "package-id" (HasArg exposePackageId)
, Flag "package" (HasArg exposePackage)
, Flag "hide-package" (HasArg hidePackage)
, Flag "hide-all-packages" (NoArg (setDynFlag Opt_HideAllPackages))
, Flag "ignore-package" (HasArg ignorePackage)
, Flag "syslib" (HasArg (\s -> do exposePackage s
deprecate "Use -package instead"))
, Flag "trust" (HasArg trustPackage)
, Flag "distrust" (HasArg distrustPackage)
, Flag "distrust-all-packages" (NoArg (setDynFlag Opt_DistrustAllPackages))
]
type TurnOnFlag = Bool -- True <=> we are turning the flag on
-- False <=> we are turning the flag off
turnOn :: TurnOnFlag; turnOn = True
turnOff :: TurnOnFlag; turnOff = False
type FlagSpec flag
= ( String -- Flag in string form
, flag -- Flag in internal form
, TurnOnFlag -> DynP ()) -- Extra action to run when the flag is found
-- Typically, emit a warning or error
mkFlag :: TurnOnFlag -- ^ True <=> it should be turned on
-> String -- ^ The flag prefix
-> (flag -> DynP ()) -- ^ What to do when the flag is found
-> FlagSpec flag -- ^ Specification of this particular flag
-> Flag (CmdLineP DynFlags)
mkFlag turn_on flagPrefix f (name, flag, extra_action)
= Flag (flagPrefix ++ name) (NoArg (f flag >> extra_action turn_on))
deprecatedForExtension :: String -> TurnOnFlag -> DynP ()
deprecatedForExtension lang turn_on
= deprecate ("use -X" ++ flag ++ " or pragma {-# LANGUAGE " ++ flag ++ " #-} instead")
where
flag | turn_on = lang
| otherwise = "No"++lang
useInstead :: String -> TurnOnFlag -> DynP ()
useInstead flag turn_on
= deprecate ("Use -f" ++ no ++ flag ++ " instead")
where
no = if turn_on then "" else "no-"
nop :: TurnOnFlag -> DynP ()
nop _ = return ()
-- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
fWarningFlags :: [FlagSpec WarningFlag]
fWarningFlags = [
( "warn-dodgy-foreign-imports", Opt_WarnDodgyForeignImports, nop ),
( "warn-dodgy-exports", Opt_WarnDodgyExports, nop ),
( "warn-dodgy-imports", Opt_WarnDodgyImports, nop ),
( "warn-duplicate-exports", Opt_WarnDuplicateExports, nop ),
( "warn-hi-shadowing", Opt_WarnHiShadows, nop ),
( "warn-implicit-prelude", Opt_WarnImplicitPrelude, nop ),
( "warn-incomplete-patterns", Opt_WarnIncompletePatterns, nop ),
( "warn-incomplete-uni-patterns", Opt_WarnIncompleteUniPatterns, nop ),
( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd, nop ),
( "warn-missing-fields", Opt_WarnMissingFields, nop ),
( "warn-missing-import-lists", Opt_WarnMissingImportList, nop ),
( "warn-missing-methods", Opt_WarnMissingMethods, nop ),
( "warn-missing-signatures", Opt_WarnMissingSigs, nop ),
( "warn-missing-local-sigs", Opt_WarnMissingLocalSigs, nop ),
( "warn-name-shadowing", Opt_WarnNameShadowing, nop ),
( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns, nop ),
( "warn-type-defaults", Opt_WarnTypeDefaults, nop ),
( "warn-monomorphism-restriction", Opt_WarnMonomorphism, nop ),
( "warn-unused-binds", Opt_WarnUnusedBinds, nop ),
( "warn-unused-imports", Opt_WarnUnusedImports, nop ),
( "warn-unused-matches", Opt_WarnUnusedMatches, nop ),
( "warn-warnings-deprecations", Opt_WarnWarningsDeprecations, nop ),
( "warn-deprecations", Opt_WarnWarningsDeprecations, nop ),
( "warn-deprecated-flags", Opt_WarnDeprecatedFlags, nop ),
( "warn-orphans", Opt_WarnOrphans, nop ),
( "warn-identities", Opt_WarnIdentities, nop ),
( "warn-auto-orphans", Opt_WarnAutoOrphans, nop ),
( "warn-tabs", Opt_WarnTabs, nop ),
( "warn-unrecognised-pragmas", Opt_WarnUnrecognisedPragmas, nop ),
( "warn-lazy-unlifted-bindings", Opt_WarnLazyUnliftedBindings, nop ),
( "warn-unused-do-bind", Opt_WarnUnusedDoBind, nop ),
( "warn-wrong-do-bind", Opt_WarnWrongDoBind, nop ),
( "warn-alternative-layout-rule-transitional", Opt_WarnAlternativeLayoutRuleTransitional, nop ),
( "warn-unsafe", Opt_WarnUnsafe, setWarnUnsafe ),
( "warn-safe", Opt_WarnSafe, setWarnSafe ) ]
-- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
fFlags :: [FlagSpec DynFlag]
fFlags = [
( "print-explicit-foralls", Opt_PrintExplicitForalls, nop ),
( "strictness", Opt_Strictness, nop ),
( "specialise", Opt_Specialise, nop ),
( "float-in", Opt_FloatIn, nop ),
( "static-argument-transformation", Opt_StaticArgumentTransformation, nop ),
( "full-laziness", Opt_FullLaziness, nop ),
( "liberate-case", Opt_LiberateCase, nop ),
( "spec-constr", Opt_SpecConstr, nop ),
( "cse", Opt_CSE, nop ),
( "pedantic-bottoms", Opt_PedanticBottoms, nop ),
( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas, nop ),
( "omit-interface-pragmas", Opt_OmitInterfacePragmas, nop ),
( "expose-all-unfoldings", Opt_ExposeAllUnfoldings, nop ),
( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion, nop ),
( "ignore-asserts", Opt_IgnoreAsserts, nop ),
( "do-eta-reduction", Opt_DoEtaReduction, nop ),
( "case-merge", Opt_CaseMerge, nop ),
( "unbox-strict-fields", Opt_UnboxStrictFields, nop ),
( "dicts-cheap", Opt_DictsCheap, nop ),
( "excess-precision", Opt_ExcessPrecision, nop ),
( "eager-blackholing", Opt_EagerBlackHoling, nop ),
( "print-bind-result", Opt_PrintBindResult, nop ),
( "force-recomp", Opt_ForceRecomp, nop ),
( "hpc-no-auto", Opt_Hpc_No_Auto, nop ),
( "rewrite-rules", Opt_EnableRewriteRules, useInstead "enable-rewrite-rules" ),
( "enable-rewrite-rules", Opt_EnableRewriteRules, nop ),
( "break-on-exception", Opt_BreakOnException, nop ),
( "break-on-error", Opt_BreakOnError, nop ),
( "print-evld-with-show", Opt_PrintEvldWithShow, nop ),
( "print-bind-contents", Opt_PrintBindContents, nop ),
( "run-cps", Opt_RunCPS, nop ),
( "run-cpsz", Opt_RunCPSZ, nop ),
( "new-codegen", Opt_TryNewCodeGen, nop ),
( "vectorise", Opt_Vectorise, nop ),
( "regs-graph", Opt_RegsGraph, nop ),
( "regs-iterative", Opt_RegsIterative, nop ),
( "gen-manifest", Opt_GenManifest, nop ),
( "embed-manifest", Opt_EmbedManifest, nop ),
( "ext-core", Opt_EmitExternalCore, nop ),
( "shared-implib", Opt_SharedImplib, nop ),
( "ghci-sandbox", Opt_GhciSandbox, nop ),
( "ghci-history", Opt_GhciHistory, nop ),
( "helpful-errors", Opt_HelpfulErrors, nop ),
( "building-cabal-package", Opt_BuildingCabalPackage, nop ),
( "implicit-import-qualified", Opt_ImplicitImportQualified, nop ),
( "prof-count-entries", Opt_ProfCountEntries, nop ),
( "prof-cafs", Opt_AutoSccsOnIndividualCafs, nop )
]
-- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
fLangFlags :: [FlagSpec ExtensionFlag]
fLangFlags = [
( "th", Opt_TemplateHaskell,
deprecatedForExtension "TemplateHaskell" >> checkTemplateHaskellOk ),
( "fi", Opt_ForeignFunctionInterface,
deprecatedForExtension "ForeignFunctionInterface" ),
( "ffi", Opt_ForeignFunctionInterface,
deprecatedForExtension "ForeignFunctionInterface" ),
( "arrows", Opt_Arrows,
deprecatedForExtension "Arrows" ),
( "implicit-prelude", Opt_ImplicitPrelude,
deprecatedForExtension "ImplicitPrelude" ),
( "bang-patterns", Opt_BangPatterns,
deprecatedForExtension "BangPatterns" ),
( "monomorphism-restriction", Opt_MonomorphismRestriction,
deprecatedForExtension "MonomorphismRestriction" ),
( "mono-pat-binds", Opt_MonoPatBinds,
deprecatedForExtension "MonoPatBinds" ),
( "extended-default-rules", Opt_ExtendedDefaultRules,
deprecatedForExtension "ExtendedDefaultRules" ),
( "implicit-params", Opt_ImplicitParams,
deprecatedForExtension "ImplicitParams" ),
( "scoped-type-variables", Opt_ScopedTypeVariables,
deprecatedForExtension "ScopedTypeVariables" ),
( "parr", Opt_ParallelArrays,
deprecatedForExtension "ParallelArrays" ),
( "PArr", Opt_ParallelArrays,
deprecatedForExtension "ParallelArrays" ),
( "allow-overlapping-instances", Opt_OverlappingInstances,
deprecatedForExtension "OverlappingInstances" ),
( "allow-undecidable-instances", Opt_UndecidableInstances,
deprecatedForExtension "UndecidableInstances" ),
( "allow-incoherent-instances", Opt_IncoherentInstances,
deprecatedForExtension "IncoherentInstances" )
]
supportedLanguages :: [String]
supportedLanguages = [ name | (name, _, _) <- languageFlags ]
supportedLanguageOverlays :: [String]
supportedLanguageOverlays = [ name | (name, _, _) <- safeHaskellFlags ]
supportedExtensions :: [String]
supportedExtensions = [ name' | (name, _, _) <- xFlags, name' <- [name, "No" ++ name] ]
supportedLanguagesAndExtensions :: [String]
supportedLanguagesAndExtensions =
supportedLanguages ++ supportedLanguageOverlays ++ supportedExtensions
-- | These -X<blah> flags cannot be reversed with -XNo<blah>
languageFlags :: [FlagSpec Language]
languageFlags = [
( "Haskell98", Haskell98, nop ),
( "Haskell2010", Haskell2010, nop )
]
-- | These -X<blah> flags cannot be reversed with -XNo<blah>
-- They are used to place hard requirements on what GHC Haskell language
-- features can be used.
safeHaskellFlags :: [FlagSpec SafeHaskellMode]
safeHaskellFlags = [mkF Sf_Unsafe, mkF Sf_Trustworthy, mkF Sf_Safe]
where mkF flag = (showPpr flag, flag, nop)
-- | These -X<blah> flags can all be reversed with -XNo<blah>
xFlags :: [FlagSpec ExtensionFlag]
xFlags = [
( "CPP", Opt_Cpp, nop ),
( "PostfixOperators", Opt_PostfixOperators, nop ),
( "TupleSections", Opt_TupleSections, nop ),
( "PatternGuards", Opt_PatternGuards, nop ),
( "UnicodeSyntax", Opt_UnicodeSyntax, nop ),
( "MagicHash", Opt_MagicHash, nop ),
( "PolymorphicComponents", Opt_PolymorphicComponents, nop ),
( "ExistentialQuantification", Opt_ExistentialQuantification, nop ),
( "KindSignatures", Opt_KindSignatures, nop ),
( "EmptyDataDecls", Opt_EmptyDataDecls, nop ),
( "ParallelListComp", Opt_ParallelListComp, nop ),
( "TransformListComp", Opt_TransformListComp, nop ),
( "MonadComprehensions", Opt_MonadComprehensions, nop),
( "ForeignFunctionInterface", Opt_ForeignFunctionInterface, nop ),
( "UnliftedFFITypes", Opt_UnliftedFFITypes, nop ),
( "InterruptibleFFI", Opt_InterruptibleFFI, nop ),
( "CApiFFI", Opt_CApiFFI, nop ),
( "GHCForeignImportPrim", Opt_GHCForeignImportPrim, nop ),
( "LiberalTypeSynonyms", Opt_LiberalTypeSynonyms, nop ),
( "Rank2Types", Opt_Rank2Types, nop ),
( "RankNTypes", Opt_RankNTypes, nop ),
( "ImpredicativeTypes", Opt_ImpredicativeTypes, nop),
( "TypeOperators", Opt_TypeOperators, nop ),
( "RecursiveDo", Opt_RecursiveDo, -- Enables 'mdo'
deprecatedForExtension "DoRec"),
( "DoRec", Opt_DoRec, nop ), -- Enables 'rec' keyword
( "Arrows", Opt_Arrows, nop ),
( "ParallelArrays", Opt_ParallelArrays, nop ),
( "TemplateHaskell", Opt_TemplateHaskell, checkTemplateHaskellOk ),
( "QuasiQuotes", Opt_QuasiQuotes, nop ),
( "ImplicitPrelude", Opt_ImplicitPrelude, nop ),
( "RecordWildCards", Opt_RecordWildCards, nop ),
( "NamedFieldPuns", Opt_RecordPuns, nop ),
( "RecordPuns", Opt_RecordPuns,
deprecatedForExtension "NamedFieldPuns" ),
( "DisambiguateRecordFields", Opt_DisambiguateRecordFields, nop ),
( "OverloadedStrings", Opt_OverloadedStrings, nop ),
( "GADTs", Opt_GADTs, nop ),
( "GADTSyntax", Opt_GADTSyntax, nop ),
( "ViewPatterns", Opt_ViewPatterns, nop ),
( "TypeFamilies", Opt_TypeFamilies, nop ),
( "BangPatterns", Opt_BangPatterns, nop ),
( "MonomorphismRestriction", Opt_MonomorphismRestriction, nop ),
( "NPlusKPatterns", Opt_NPlusKPatterns, nop ),
( "DoAndIfThenElse", Opt_DoAndIfThenElse, nop ),
( "RebindableSyntax", Opt_RebindableSyntax, nop ),
( "ConstraintKinds", Opt_ConstraintKinds, nop ),
( "PolyKinds", Opt_PolyKinds, nop ),
( "DataKinds", Opt_DataKinds, nop ),
( "MonoPatBinds", Opt_MonoPatBinds,
\ turn_on -> when turn_on $ deprecate "Experimental feature now removed; has no effect" ),
( "ExplicitForAll", Opt_ExplicitForAll, nop ),
( "AlternativeLayoutRule", Opt_AlternativeLayoutRule, nop ),
( "AlternativeLayoutRuleTransitional",Opt_AlternativeLayoutRuleTransitional, nop ),
( "DatatypeContexts", Opt_DatatypeContexts,
\ turn_on -> when turn_on $ deprecate "It was widely considered a misfeature, and has been removed from the Haskell language." ),
( "NondecreasingIndentation", Opt_NondecreasingIndentation, nop ),
( "RelaxedLayout", Opt_RelaxedLayout, nop ),
( "TraditionalRecordSyntax", Opt_TraditionalRecordSyntax, nop ),
( "MonoLocalBinds", Opt_MonoLocalBinds, nop ),
( "RelaxedPolyRec", Opt_RelaxedPolyRec,
\ turn_on -> if not turn_on
then deprecate "You can't turn off RelaxedPolyRec any more"
else return () ),
( "ExtendedDefaultRules", Opt_ExtendedDefaultRules, nop ),
( "ImplicitParams", Opt_ImplicitParams, nop ),
( "ScopedTypeVariables", Opt_ScopedTypeVariables, nop ),
( "PatternSignatures", Opt_ScopedTypeVariables,
deprecatedForExtension "ScopedTypeVariables" ),
( "UnboxedTuples", Opt_UnboxedTuples, nop ),
( "StandaloneDeriving", Opt_StandaloneDeriving, nop ),
( "DeriveDataTypeable", Opt_DeriveDataTypeable, nop ),
( "DeriveFunctor", Opt_DeriveFunctor, nop ),
( "DeriveTraversable", Opt_DeriveTraversable, nop ),
( "DeriveFoldable", Opt_DeriveFoldable, nop ),
( "DeriveGeneric", Opt_DeriveGeneric, nop ),
( "DefaultSignatures", Opt_DefaultSignatures, nop ),
( "TypeSynonymInstances", Opt_TypeSynonymInstances, nop ),
( "FlexibleContexts", Opt_FlexibleContexts, nop ),
( "FlexibleInstances", Opt_FlexibleInstances, nop ),
( "ConstrainedClassMethods", Opt_ConstrainedClassMethods, nop ),
( "MultiParamTypeClasses", Opt_MultiParamTypeClasses, nop ),
( "FunctionalDependencies", Opt_FunctionalDependencies, nop ),
( "GeneralizedNewtypeDeriving", Opt_GeneralizedNewtypeDeriving, setGenDeriving ),
( "OverlappingInstances", Opt_OverlappingInstances, nop ),
( "UndecidableInstances", Opt_UndecidableInstances, nop ),
( "IncoherentInstances", Opt_IncoherentInstances, nop ),
( "PackageImports", Opt_PackageImports, nop ),
( "ApplicativeFix", Opt_ApplicativeFix, nop )
]
defaultFlags :: [DynFlag]
defaultFlags
= [ Opt_AutoLinkPackages,
Opt_ReadUserPackageConf,
Opt_SharedImplib,
#if GHC_DEFAULT_NEW_CODEGEN
Opt_TryNewCodeGen,
#endif
Opt_GenManifest,
Opt_EmbedManifest,
Opt_PrintBindContents,
Opt_GhciSandbox,
Opt_GhciHistory,
Opt_HelpfulErrors,
Opt_ProfCountEntries
]
++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
-- The default -O0 options
impliedFlags :: [(ExtensionFlag, TurnOnFlag, ExtensionFlag)]
impliedFlags
= [ (Opt_RankNTypes, turnOn, Opt_ExplicitForAll)
, (Opt_Rank2Types, turnOn, Opt_ExplicitForAll)
, (Opt_ScopedTypeVariables, turnOn, Opt_ExplicitForAll)
, (Opt_LiberalTypeSynonyms, turnOn, Opt_ExplicitForAll)
, (Opt_ExistentialQuantification, turnOn, Opt_ExplicitForAll)
, (Opt_PolymorphicComponents, turnOn, Opt_ExplicitForAll)
, (Opt_FlexibleInstances, turnOn, Opt_TypeSynonymInstances)
, (Opt_FunctionalDependencies, turnOn, Opt_MultiParamTypeClasses)
, (Opt_RebindableSyntax, turnOff, Opt_ImplicitPrelude) -- NB: turn off!
, (Opt_GADTs, turnOn, Opt_GADTSyntax)
, (Opt_GADTs, turnOn, Opt_MonoLocalBinds)
, (Opt_TypeFamilies, turnOn, Opt_MonoLocalBinds)
, (Opt_TypeFamilies, turnOn, Opt_KindSignatures) -- Type families use kind signatures
-- all over the place
, (Opt_ImpredicativeTypes, turnOn, Opt_RankNTypes)
-- Record wild-cards implies field disambiguation
-- Otherwise if you write (C {..}) you may well get
-- stuff like " 'a' not in scope ", which is a bit silly
-- if the compiler has just filled in field 'a' of constructor 'C'
, (Opt_RecordWildCards, turnOn, Opt_DisambiguateRecordFields)
, (Opt_ParallelArrays, turnOn, Opt_ParallelListComp)
]
optLevelFlags :: [([Int], DynFlag)]
optLevelFlags
= [ ([0], Opt_IgnoreInterfacePragmas)
, ([0], Opt_OmitInterfacePragmas)
, ([1,2], Opt_IgnoreAsserts)
, ([1,2], Opt_EnableRewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
-- in PrelRules
, ([1,2], Opt_DoEtaReduction)
, ([1,2], Opt_CaseMerge)
, ([1,2], Opt_Strictness)
, ([1,2], Opt_CSE)
, ([1,2], Opt_FullLaziness)
, ([1,2], Opt_Specialise)
, ([1,2], Opt_FloatIn)
, ([2], Opt_LiberateCase)
, ([2], Opt_SpecConstr)
, ([2], Opt_RegsGraph)
-- , ([2], Opt_StaticArgumentTransformation)
-- Max writes: I think it's probably best not to enable SAT with -O2 for the
-- 6.10 release. The version of SAT in HEAD at the moment doesn't incorporate
-- several improvements to the heuristics, and I'm concerned that without
-- those changes SAT will interfere with some attempts to write "high
-- performance Haskell", as we saw in some posts on Haskell-Cafe earlier
-- this year. In particular, the version in HEAD lacks the tail call
-- criterion, so many things that look like reasonable loops will be
-- turned into functions with extra (unneccesary) thunk creation.
, ([0,1,2], Opt_DoLambdaEtaExpansion)
-- This one is important for a tiresome reason:
-- we want to make sure that the bindings for data
-- constructors are eta-expanded. This is probably
-- a good thing anyway, but it seems fragile.
]
-- -----------------------------------------------------------------------------
-- Standard sets of warning options
standardWarnings :: [WarningFlag]
standardWarnings
= [ Opt_WarnWarningsDeprecations,
Opt_WarnDeprecatedFlags,
Opt_WarnUnrecognisedPragmas,
Opt_WarnOverlappingPatterns,
Opt_WarnMissingFields,
Opt_WarnMissingMethods,
Opt_WarnDuplicateExports,
Opt_WarnLazyUnliftedBindings,
Opt_WarnDodgyForeignImports,
Opt_WarnWrongDoBind,
Opt_WarnAlternativeLayoutRuleTransitional
]
minusWOpts :: [WarningFlag]
-- Things you get with -W
minusWOpts
= standardWarnings ++
[ Opt_WarnUnusedBinds,
Opt_WarnUnusedMatches,
Opt_WarnUnusedImports,
Opt_WarnIncompletePatterns,
Opt_WarnDodgyExports,
Opt_WarnDodgyImports
]
minusWallOpts :: [WarningFlag]
-- Things you get with -Wall
minusWallOpts
= minusWOpts ++
[ Opt_WarnTypeDefaults,
Opt_WarnNameShadowing,
Opt_WarnMissingSigs,
Opt_WarnHiShadows,
Opt_WarnOrphans,
Opt_WarnUnusedDoBind
]
enableGlasgowExts :: DynP ()
enableGlasgowExts = do setDynFlag Opt_PrintExplicitForalls
mapM_ setExtensionFlag glasgowExtsFlags
disableGlasgowExts :: DynP ()
disableGlasgowExts = do unSetDynFlag Opt_PrintExplicitForalls
mapM_ unSetExtensionFlag glasgowExtsFlags
glasgowExtsFlags :: [ExtensionFlag]
glasgowExtsFlags = [
Opt_ForeignFunctionInterface
, Opt_UnliftedFFITypes
, Opt_ImplicitParams
, Opt_ScopedTypeVariables
, Opt_UnboxedTuples
, Opt_TypeSynonymInstances
, Opt_StandaloneDeriving
, Opt_DeriveDataTypeable
, Opt_DeriveFunctor
, Opt_DeriveFoldable
, Opt_DeriveTraversable
, Opt_DeriveGeneric
, Opt_FlexibleContexts
, Opt_FlexibleInstances
, Opt_ConstrainedClassMethods
, Opt_MultiParamTypeClasses
, Opt_FunctionalDependencies
, Opt_MagicHash
, Opt_PolymorphicComponents
, Opt_ExistentialQuantification
, Opt_UnicodeSyntax
, Opt_PostfixOperators
, Opt_PatternGuards
, Opt_LiberalTypeSynonyms
, Opt_RankNTypes
, Opt_TypeOperators
, Opt_DoRec
, Opt_ParallelListComp
, Opt_EmptyDataDecls
, Opt_KindSignatures
, Opt_GeneralizedNewtypeDeriving ]
#ifdef GHCI
-- Consult the RTS to find whether GHC itself has been built profiled
-- If so, you can't use Template Haskell
foreign import ccall unsafe "rts_isProfiled" rtsIsProfiledIO :: IO CInt
rtsIsProfiled :: Bool
rtsIsProfiled = unsafePerformIO rtsIsProfiledIO /= 0
#endif
setWarnSafe :: Bool -> DynP ()
setWarnSafe True = getCurLoc >>= \l -> upd (\d -> d { warnSafeOnLoc = l })
setWarnSafe False = return ()
setWarnUnsafe :: Bool -> DynP ()
setWarnUnsafe True = getCurLoc >>= \l -> upd (\d -> d { warnUnsafeOnLoc = l })
setWarnUnsafe False = return ()
setPackageTrust :: DynP ()
setPackageTrust = do
setDynFlag Opt_PackageTrust
l <- getCurLoc
upd $ \d -> d { pkgTrustOnLoc = l }
setGenDeriving :: Bool -> DynP ()
setGenDeriving True = getCurLoc >>= \l -> upd (\d -> d { newDerivOnLoc = l })
setGenDeriving False = return ()
checkTemplateHaskellOk :: Bool -> DynP ()
#ifdef GHCI
checkTemplateHaskellOk turn_on
| turn_on && rtsIsProfiled
= addErr "You can't use Template Haskell with a profiled compiler"
| otherwise
= getCurLoc >>= \l -> upd (\d -> d { thOnLoc = l })
#else
-- In stage 1 we don't know that the RTS has rts_isProfiled,
-- so we simply say "ok". It doesn't matter because TH isn't
-- available in stage 1 anyway.
checkTemplateHaskellOk _ = return ()
#endif
{- **********************************************************************
%* *
DynFlags constructors
%* *
%********************************************************************* -}
type DynP = EwM (CmdLineP DynFlags)
upd :: (DynFlags -> DynFlags) -> DynP ()
upd f = liftEwM (do dflags <- getCmdLineState
putCmdLineState $! f dflags)
updM :: (DynFlags -> DynP DynFlags) -> DynP ()
updM f = do dflags <- liftEwM getCmdLineState
dflags' <- f dflags
liftEwM $ putCmdLineState $! dflags'
--------------- Constructor functions for OptKind -----------------
noArg :: (DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
noArg fn = NoArg (upd fn)
noArgM :: (DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags)
noArgM fn = NoArg (updM fn)
noArgDF :: (DynFlags -> DynFlags) -> String -> OptKind (CmdLineP DynFlags)
noArgDF fn deprec = NoArg (upd fn >> deprecate deprec)
hasArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
hasArg fn = HasArg (upd . fn)
hasArgDF :: (String -> DynFlags -> DynFlags) -> String -> OptKind (CmdLineP DynFlags)
hasArgDF fn deprec = HasArg (\s -> do upd (fn s)
deprecate deprec)
sepArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
sepArg fn = SepArg (upd . fn)
intSuffix :: (Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
intSuffix fn = IntSuffix (\n -> upd (fn n))
optIntSuffixM :: (Maybe Int -> DynFlags -> DynP DynFlags)
-> OptKind (CmdLineP DynFlags)
optIntSuffixM fn = OptIntSuffix (\mi -> updM (fn mi))
setDumpFlag :: DynFlag -> OptKind (CmdLineP DynFlags)
setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag)
--------------------------
setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
setDynFlag f = upd (\dfs -> dopt_set dfs f)
unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
--------------------------
setWarningFlag, unSetWarningFlag :: WarningFlag -> DynP ()
setWarningFlag f = upd (\dfs -> wopt_set dfs f)
unSetWarningFlag f = upd (\dfs -> wopt_unset dfs f)
--------------------------
setExtensionFlag, unSetExtensionFlag :: ExtensionFlag -> DynP ()
setExtensionFlag f = do upd (\dfs -> xopt_set dfs f)
sequence_ deps
where
deps = [ if turn_on then setExtensionFlag d
else unSetExtensionFlag d
| (f', turn_on, d) <- impliedFlags, f' == f ]
-- When you set f, set the ones it implies
-- NB: use setExtensionFlag recursively, in case the implied flags
-- implies further flags
unSetExtensionFlag f = upd (\dfs -> xopt_unset dfs f)
-- When you un-set f, however, we don't un-set the things it implies
-- (except for -fno-glasgow-exts, which is treated specially)
--------------------------
alterSettings :: (Settings -> Settings) -> DynFlags -> DynFlags
alterSettings f dflags = dflags { settings = f (settings dflags) }
--------------------------
setDumpFlag' :: DynFlag -> DynP ()
setDumpFlag' dump_flag
= do setDynFlag dump_flag
when want_recomp forceRecompile
where
-- Certain dumpy-things are really interested in what's going
-- on during recompilation checking, so in those cases we
-- don't want to turn it off.
want_recomp = dump_flag `notElem` [Opt_D_dump_if_trace,
Opt_D_dump_hi_diffs]
forceRecompile :: DynP ()
-- Whenver we -ddump, force recompilation (by switching off the
-- recompilation checker), else you don't see the dump! However,
-- don't switch it off in --make mode, else *everything* gets
-- recompiled which probably isn't what you want
forceRecompile = do dfs <- liftEwM getCmdLineState
when (force_recomp dfs) (setDynFlag Opt_ForceRecomp)
where
force_recomp dfs = isOneShot (ghcMode dfs)
setVerboseCore2Core :: DynP ()
setVerboseCore2Core = do forceRecompile
setDynFlag Opt_D_verbose_core2core
upd (\dfs -> dfs { shouldDumpSimplPhase = Nothing })
setDumpSimplPhases :: String -> DynP ()
setDumpSimplPhases s = do forceRecompile
upd (\dfs -> dfs { shouldDumpSimplPhase = Just spec })
where
spec = case s of { ('=' : s') -> s'; _ -> s }
setVerbosity :: Maybe Int -> DynP ()
setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
addCmdlineHCInclude :: String -> DynP ()
addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
extraPkgConf_ :: FilePath -> DynP ()
extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
exposePackage, exposePackageId, hidePackage, ignorePackage,
trustPackage, distrustPackage :: String -> DynP ()
exposePackage p =
upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
exposePackageId p =
upd (\s -> s{ packageFlags = ExposePackageId p : packageFlags s })
hidePackage p =
upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
ignorePackage p =
upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
trustPackage p = exposePackage p >> -- both trust and distrust also expose a package
upd (\s -> s{ packageFlags = TrustPackage p : packageFlags s })
distrustPackage p = exposePackage p >>
upd (\s -> s{ packageFlags = DistrustPackage p : packageFlags s })
setPackageName :: String -> DynFlags -> DynFlags
setPackageName p s = s{ thisPackage = stringToPackageId p }
-- If we're linking a binary, then only targets that produce object
-- code are allowed (requests for other target types are ignored).
setTarget :: HscTarget -> DynP ()
setTarget l = upd set
where
set dfs
| ghcLink dfs /= LinkBinary || isObjectTarget l = dfs{ hscTarget = l }
| otherwise = dfs
-- Changes the target only if we're compiling object code. This is
-- used by -fasm and -fllvm, which switch from one to the other, but
-- not from bytecode to object-code. The idea is that -fasm/-fllvm
-- can be safely used in an OPTIONS_GHC pragma.
setObjTarget :: HscTarget -> DynP ()
setObjTarget l = updM set
where
set dflags
| isObjectTarget (hscTarget dflags)
= case l of
HscC
| cGhcUnregisterised /= "YES" ->
do addWarn ("Compiler not unregisterised, so ignoring " ++ flag)
return dflags
HscAsm
| cGhcWithNativeCodeGen /= "YES" ->
do addWarn ("Compiler has no native codegen, so ignoring " ++
flag)
return dflags
HscLlvm
| not ((arch == ArchX86_64) && (os == OSLinux || os == OSDarwin)) &&
(not opt_Static || opt_PIC)
->
do addWarn ("Ignoring " ++ flag ++ " as it is incompatible with -fPIC and -dynamic on this platform")
return dflags
_ -> return $ dflags { hscTarget = l }
| otherwise = return dflags
where platform = targetPlatform dflags
arch = platformArch platform
os = platformOS platform
flag = showHscTargetFlag l
setOptLevel :: Int -> DynFlags -> DynP DynFlags
setOptLevel n dflags
| hscTarget dflags == HscInterpreted && n > 0
= do addWarn "-O conflicts with --interactive; -O ignored."
return dflags
| otherwise
= return (updOptLevel n dflags)
-- -Odph is equivalent to
--
-- -O2 optimise as much as possible
-- -fmax-simplifier-iterations20 this is necessary sometimes
-- -fsimplifier-phases=3 we use an additional simplifier phase for fusion
--
setDPHOpt :: DynFlags -> DynP DynFlags
setDPHOpt dflags = setOptLevel 2 (dflags { maxSimplIterations = 20
, simplPhases = 3
})
setMainIs :: String -> DynP ()
setMainIs arg
| not (null main_fn) && isLower (head main_fn)
-- The arg looked like "Foo.Bar.baz"
= upd $ \d -> d{ mainFunIs = Just main_fn,
mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
| isUpper (head arg) -- The arg looked like "Foo" or "Foo.Bar"
= upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName arg) }
| otherwise -- The arg looked like "baz"
= upd $ \d -> d{ mainFunIs = Just arg }
where
(main_mod, main_fn) = splitLongestPrefix arg (== '.')
-----------------------------------------------------------------------------
-- Paths & Libraries
addImportPath, addLibraryPath, addIncludePath, addFrameworkPath :: FilePath -> DynP ()
-- -i on its own deletes the import paths
addImportPath "" = upd (\s -> s{importPaths = []})
addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
addLibraryPath p =
upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
addIncludePath p =
upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
addFrameworkPath p =
upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
#ifndef mingw32_TARGET_OS
split_marker :: Char
split_marker = ':' -- not configurable (ToDo)
#endif
splitPathList :: String -> [String]
splitPathList s = filter notNull (splitUp s)
-- empty paths are ignored: there might be a trailing
-- ':' in the initial list, for example. Empty paths can
-- cause confusion when they are translated into -I options
-- for passing to gcc.
where
#ifndef mingw32_TARGET_OS
splitUp xs = split split_marker xs
#else
-- Windows: 'hybrid' support for DOS-style paths in directory lists.
--
-- That is, if "foo:bar:baz" is used, this interpreted as
-- consisting of three entries, 'foo', 'bar', 'baz'.
-- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
-- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
--
-- Notice that no attempt is made to fully replace the 'standard'
-- split marker ':' with the Windows / DOS one, ';'. The reason being
-- that this will cause too much breakage for users & ':' will
-- work fine even with DOS paths, if you're not insisting on being silly.
-- So, use either.
splitUp [] = []
splitUp (x:':':div:xs) | div `elem` dir_markers
= ((x:':':div:p): splitUp rs)
where
(p,rs) = findNextPath xs
-- we used to check for existence of the path here, but that
-- required the IO monad to be threaded through the command-line
-- parser which is quite inconvenient. The
splitUp xs = cons p (splitUp rs)
where
(p,rs) = findNextPath xs
cons "" xs = xs
cons x xs = x:xs
-- will be called either when we've consumed nought or the
-- "<Drive>:/" part of a DOS path, so splitting is just a Q of
-- finding the next split marker.
findNextPath xs =
case break (`elem` split_markers) xs of
(p, _:ds) -> (p, ds)
(p, xs) -> (p, xs)
split_markers :: [Char]
split_markers = [':', ';']
dir_markers :: [Char]
dir_markers = ['/', '\\']
#endif
-- -----------------------------------------------------------------------------
-- tmpDir, where we store temporary files.
setTmpDir :: FilePath -> DynFlags -> DynFlags
setTmpDir dir = alterSettings (\s -> s { sTmpDir = normalise dir })
-- we used to fix /cygdrive/c/.. on Windows, but this doesn't
-- seem necessary now --SDM 7/2/2008
-----------------------------------------------------------------------------
-- RTS opts
setRtsOpts :: String -> DynP ()
setRtsOpts arg = upd $ \ d -> d {rtsOpts = Just arg}
setRtsOptsEnabled :: RtsOptsEnabled -> DynP ()
setRtsOptsEnabled arg = upd $ \ d -> d {rtsOptsEnabled = arg}
-----------------------------------------------------------------------------
-- Hpc stuff
setOptHpcDir :: String -> DynP ()
setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
-----------------------------------------------------------------------------
-- Via-C compilation stuff
-- There are some options that we need to pass to gcc when compiling
-- Haskell code via C, but are only supported by recent versions of
-- gcc. The configure script decides which of these options we need,
-- and puts them in the "settings" file in $topdir. The advantage of
-- having these in a separate file is that the file can be created at
-- install-time depending on the available gcc version, and even
-- re-generated later if gcc is upgraded.
--
-- The options below are not dependent on the version of gcc, only the
-- platform.
picCCOpts :: DynFlags -> [String]
picCCOpts dflags
= case platformOS (targetPlatform dflags) of
OSDarwin
-- Apple prefers to do things the other way round.
-- PIC is on by default.
-- -mdynamic-no-pic:
-- Turn off PIC code generation.
-- -fno-common:
-- Don't generate "common" symbols - these are unwanted
-- in dynamic libraries.
| opt_PIC -> ["-fno-common", "-U __PIC__", "-D__PIC__"]
| otherwise -> ["-mdynamic-no-pic"]
OSMinGW32 -- no -fPIC for Windows
| opt_PIC -> ["-U __PIC__", "-D__PIC__"]
| otherwise -> []
_
-- we need -fPIC for C files when we are compiling with -dynamic,
-- otherwise things like stub.c files don't get compiled
-- correctly. They need to reference data in the Haskell
-- objects, but can't without -fPIC. See
-- http://hackage.haskell.org/trac/ghc/wiki/Commentary/PositionIndependentCode
| opt_PIC || not opt_Static -> ["-fPIC", "-U __PIC__", "-D__PIC__"]
| otherwise -> []
-- -----------------------------------------------------------------------------
-- Splitting
can_split :: Bool
can_split = cSupportsSplitObjs == "YES"
-- -----------------------------------------------------------------------------
-- Compiler Info
compilerInfo :: DynFlags -> [(String, String)]
compilerInfo dflags
= -- We always make "Project name" be first to keep parsing in
-- other languages simple, i.e. when looking for other fields,
-- you don't have to worry whether there is a leading '[' or not
("Project name", cProjectName)
-- Next come the settings, so anything else can be overridden
-- in the settings file (as "lookup" uses the first match for the
-- key)
: rawSettings dflags
++ [("Project version", cProjectVersion),
("Booter version", cBooterVersion),
("Stage", cStage),
("Build platform", cBuildPlatformString),
("Host platform", cHostPlatformString),
("Target platform", cTargetPlatformString),
("Have interpreter", cGhcWithInterpreter),
("Object splitting supported", cSupportsSplitObjs),
("Have native code generator", cGhcWithNativeCodeGen),
("Support SMP", cGhcWithSMP),
("Unregisterised", cGhcUnregisterised),
("Tables next to code", cGhcEnableTablesNextToCode),
("RTS ways", cGhcRTSWays),
("Leading underscore", cLeadingUnderscore),
("Debug on", show debugIsOn),
("LibDir", topDir dflags),
("Global Package DB", systemPackageConfig dflags),
("Gcc Linker flags", show cGccLinkerOpts),
("Ld Linker flags", show cLdLinkerOpts)
]
|
ilyasergey/GHC-XAppFix
|
compiler/main/DynFlags.hs
|
Haskell
|
bsd-3-clause
| 111,305
|
module Test.Utils (
testProvider
, (@=~?)
, (?=~@)
, (=~)
) where
import qualified Data.Array.Repa as R
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Unboxed as VU
import qualified Test.Framework as TF
import qualified Test.Framework.Providers.HUnit as TFH
import qualified Test.HUnit as HU
infix 4 =~
class AEq a where
(=~) :: a -> a -> Bool
instance AEq Double where
x =~ y = abs ( x - y ) < (1.0e-8 :: Double)
instance AEq Int where
x =~ y = x == y
instance (AEq a) => AEq [a] where
xs =~ ys = (length xs == length ys) &&
(all (\(x,y) -> x =~ y) $ zip xs ys)
instance (AEq a) => AEq (Maybe a) where
Nothing =~ Nothing = True
Just x =~ Just y = x =~ y
_ =~ _ = False
instance (AEq a, AEq b) => AEq (a, b) where
(a, b) =~ (aa, bb) = (a =~ aa) && (b =~ bb)
instance (AEq a, AEq b, AEq c) => AEq (a, b, c) where
(a, b, c) =~ (aa, bb, cc) = (a =~ aa) && (b =~ bb) && (c =~ cc)
instance (AEq a, AEq b, AEq c, AEq d) => AEq (a, b, c, d) where
(a, b, c, d) =~ (aa, bb, cc, dd) = (a =~ aa) && (b =~ bb) &&
(c =~ cc) && (d =~ dd)
instance (AEq e, R.Shape sh, R.Source r e) => AEq (R.Array r sh e) where
xs =~ ys = (R.extent xs == R.extent ys) &&
(R.foldAllS (&&) True $ R.zipWith (=~) xs ys)
instance (AEq a, VG.Vector VU.Vector a) => AEq (VU.Vector a) where
xs =~ ys = (VG.toList xs) =~ (VG.toList ys)
instance (AEq a, VG.Vector VS.Vector a) => AEq (VS.Vector a) where
xs =~ ys = (VG.toList xs) =~ (VG.toList ys)
-- This function takes the name for the test, a testing function and a data
-- provider and creates a testGroup
testProvider :: String -> (a -> HU.Assertion) -> [a] -> TF.Test
testProvider testGroupName testFunction =
TF.testGroup testGroupName . map createTest . zipWith assignName [1::Int ..]
where
createTest (name, dataSet) = TFH.testCase name $ testFunction dataSet
assignName setNumber dataSet = ("Data set " ++ show setNumber, dataSet)
-- "Almost equal" assertions for HUnit
infix 4 @=~?
(@=~?) :: (Show a, AEq a) => a -> a -> HU.Assertion
(@=~?) expected actual = expected =~ actual HU.@? assertionMsg
where
assertionMsg = "Expected : " ++ show expected ++
"\nActual : " ++ show actual
infix 4 ?=~@
(?=~@) :: (Show a, AEq a) => a -> a -> HU.Assertion
(?=~@) actual expected = actual =~ expected HU.@? assertionMsg
where
assertionMsg = "Actual : " ++ show actual ++
"\nExpected : " ++ show expected
|
jstolarek/lattice-structure-hs
|
tests/Test/Utils.hs
|
Haskell
|
bsd-3-clause
| 2,737
|
module Main where
import Data.Monoid
input = ".^^.^^^..^.^..^.^^.^^^^.^^.^^...^..^...^^^..^^...^..^^^^^^..^.^^^..^.^^^^.^^^.^...^^^.^^.^^^.^.^^.^."
isTrap "^^." = '^' -- Its left and center tiles are traps, but its right tile is not.
isTrap ".^^" = '^' -- Its center and right tiles are traps, but its left tile is not.
isTrap "^.." = '^' -- Only its left tile is a trap.
isTrap "..^" = '^' -- Only its right tile is a trap.
isTrap _ = '.' -- None of the above, tile is safe
walk (a:b:c:ds) = isTrap [a,b,c] : walk (b:c:ds)
walk _ = []
inflate input = "." <> input <> "." -- add safe tiles on either end
nextRow thisRow = walk $ inflate thisRow
main = do print $ length $ filter (== '.') (concat $ take 40 rows)
print $ length $ filter (== '.') (concat $ take 400000 rows)
where rows = iterate nextRow input
|
shapr/adventofcode2016
|
src/Eighteen/Main.hs
|
Haskell
|
bsd-3-clause
| 850
|
module PrefAttachment (runPrefAttachment) where
import Graph
import Data.List
import System.Random
import Test.QuickCheck
import qualified Data.IntMap.Strict as Map
runPrefAttachment :: Int -> IO ((Graph Int),Int)
runPrefAttachment 1 = return ((createGraph 1),0)
runPrefAttachment num =
let
graph = createGraph num
in loop graph 0
loop :: (Graph Int) -> Int -> IO ((Graph Int),Int)
loop g edge_nr = do
v1 <- randomRIO (0,(length $ Map.keys g)-1)
v2 <- generate $ frequency $ map (\(a,b) -> (b,return a)) $ degrees g
if v1==v2
then loop g edge_nr
else do
let new_graph = addEdge g (v1,v2)
if verifyConnected new_graph
then return (new_graph,edge_nr+1)
else loop new_graph (edge_nr+1)
|
jbddc/sdc-graph
|
src/PrefAttachment.hs
|
Haskell
|
bsd-3-clause
| 726
|
{-
Euler discovered the remarkable quadratic formula:
n^2 + n + 41
It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 40^2 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 41^2 + 41 + 41 is clearly divisible by 41.
The incredible formula n^2 − 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, −79 and 1601, is −126479.
Considering quadratics of the form:
n^2 + an + b, where |a| < 1000 and |b| < 1000
where |n| is the modulus/absolute value of n
e.g. |11| = 11 and |−4| = 4
Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0.
-}
import qualified Data.List as List
import qualified Data.Ord as Ord
import qualified Zora.List as ZList
import qualified Zora.Math as ZMath
import Control.Applicative
num_primes_produced :: (Integer -> Integer) -> Int
num_primes_produced f =
length . takeWhile (ZMath.prime . f) $ [0..]
k :: Integer
k = 999
as :: [Integer]
as = [-k..k]
positive_small_primes :: [Integer]
positive_small_primes = takeWhile (<= k) ZMath.primes
quadratics :: [(Integer -> Integer, (Integer, Integer))]
quadratics = f <$> as <*> positive_small_primes
where
f :: Integer -> Integer -> (Integer -> Integer, (Integer, Integer))
f a b = ((\n -> n^2 + (a * n) + b), (a, b))
fs_with_results :: [(Int, (Integer, Integer))]
fs_with_results = map (ZList.map_fst (($) num_primes_produced))quadratics
max_with_index :: ((Int, (Integer, Integer)), Integer)
max_with_index = ZList.maximum_with_index fs_with_results
ab :: (Integer, Integer)
ab = snd . fst $ max_with_index
main :: IO ()
main = do
putStrLn . show $ fst ab * snd ab
|
bgwines/project-euler
|
src/solved/problem27.hs
|
Haskell
|
bsd-3-clause
| 1,843
|
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE DeriveGeneric #-}
module Main ( main ) where
import GHC.Generics ( Generic )
import Criterion.Main
import qualified Data.Binary as B
import qualified Data.Serialize as S
data SerializeMe a =
SerializeMe [[(a,[a])]] [[(a,[a])]] [[(a,[a])]] [[(a,[a])]] [[(a,[a])]] [[(a,[a])]] [[(a,[a])]]
deriving Generic
instance S.Serialize a => S.Serialize (SerializeMe a)
instance B.Binary a => B.Binary (SerializeMe a)
exampleData :: SerializeMe Double
exampleData = SerializeMe x x x x x x x
where
x :: [[(Double, [Double])]]
x = replicate 200 (replicate 4 (pi, replicate 40 pi))
main :: IO ()
main =
defaultMain
[ bench "cereal-encode-nf" $ nf S.encode exampleData
, bench "cereal-encodeLazy-nf" $ nf S.encodeLazy exampleData
, bench "binary-encode-nf" $ nf B.encode exampleData
]
|
ghorn/binary-counterexample
|
src/Main.hs
|
Haskell
|
bsd-3-clause
| 855
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
------------------------------------------------------------------------------
module Snap.Internal.Http.Server.Session
( httpSession
) where
------------------------------------------------------------------------------
import Blaze.ByteString.Builder (Builder, flush,
fromByteString)
import Blaze.ByteString.Builder.Char8 (fromChar, fromShow)
import Control.Applicative ((<$>), (<|>))
import Control.Arrow (first, second)
import Control.Exception (Exception, Handler (..),
SomeException (..), catches,
throwIO)
import Control.Monad (when)
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as S
import qualified Data.CaseInsensitive as CI
import Data.Int (Int64)
import Data.IORef (writeIORef)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import Data.Monoid (mconcat)
import Data.Typeable (Typeable)
import System.IO.Streams (InputStream)
import qualified System.IO.Streams as Streams
------------------------------------------------------------------------------
import Snap.Core (EscapeSnap (..))
import Snap.Internal.Http.Server.Parser (IRequest (..), parseCookie,
parseRequest,
parseUrlEncoded,
readChunkedTransferEncoding)
import Snap.Internal.Http.Server.Types (AcceptHook, DataFinishedHook,
ParseHook,
PerSessionData (..),
ServerConfig (..),
ServerHandler,
SessionFinishedHook,
SessionHandler,
UserHandlerFinishedHook)
import Snap.Internal.Http.Types (Method (..), Request (..),
getHeader)
import Snap.Internal.Parsing (unsafeFromInt)
import qualified Snap.Types.Headers as H
------------------------------------------------------------------------------
------------------------------------------------------------------------------
data TerminateSessionException = TerminateSessionException SomeException
deriving (Typeable, Show)
instance Exception TerminateSessionException
data BadRequestException = BadRequestException
deriving (Typeable, Show)
instance Exception BadRequestException
data LengthRequiredException = LengthRequiredException
deriving (Typeable, Show)
instance Exception LengthRequiredException
------------------------------------------------------------------------------
mAX_HEADERS_SIZE :: Int64
mAX_HEADERS_SIZE = 256 * 1024
------------------------------------------------------------------------------
httpSession :: hookState
-> ServerHandler hookState
-> ServerConfig hookState
-> PerSessionData
-> IO ()
httpSession !hookState !serverHandler !config !sessionData = begin
where
--------------------------------------------------------------------------
defaultTimeout = _defaultTimeout config
localAddress = _localAddress sessionData
localPort = _localPort config
localHostname = _localHostname config
readEnd = _readEnd sessionData
remoteAddress = _remoteAddress sessionData
remotePort = _remotePort sessionData
tickle = _twiddleTimeout sessionData
writeEnd = _writeEnd sessionData
isSecure = _isSecure config
forceConnectionClose = _forceConnectionClose sessionData
logError = _logError config
--------------------------------------------------------------------------
{-# INLINE begin #-}
begin :: IO ()
begin = do
-- parse HTTP request
receiveRequest >>= maybe (_onSessionFinished config hookState)
processRequest
--------------------------------------------------------------------------
{-# INLINE receiveRequest #-}
receiveRequest :: IO (Maybe Request)
receiveRequest = do
readEnd' <- Streams.throwIfProducesMoreThan mAX_HEADERS_SIZE readEnd
parseRequest readEnd' >>= maybe (return Nothing)
((Just <$>) . toRequest)
--------------------------------------------------------------------------
toRequest :: IRequest -> IO Request
toRequest !ireq = do
-- HTTP spec section 14.23: "All Internet-based HTTP/1.1 servers MUST
-- respond with a 400 (Bad Request) status code to any HTTP/1.1 request
-- message which lacks a Host header field."
--
-- Here we interpret this slightly more liberally: if an absolute URI
-- including a hostname is given in the request line, we'll take that
-- if there's no Host header.
--
-- For HTTP/1.0 requests, we pick the configured local hostname by
-- default.
host <- maybe (if isHttp11
then badRequestWithNoHost
else return localHostname)
return mbHost
-- Handle transfer-encoding: chunked, etc
readEnd' <- setupReadEnd
(readEnd'', postParams) <- parseForm readEnd'
let allParams = Map.unionWith (++) queryParams postParams
checkConnectionClose version hdrs
return $! Request host
remoteAddress
remotePort
localAddress
localPort
localHostname
isSecure
hdrs
readEnd''
mbCL
method
version
cookies
pathInfo
contextPath
uri
queryString
allParams
queryParams
postParams
where
----------------------------------------------------------------------
method = iMethod ireq
version = iHttpVersion ireq
isHttp11 = version >= (1, 1)
mbHost = H.lookup "host" hdrs <|> iHost ireq
localHost = fromMaybe localHostname $! iHost ireq
hdrs = toHeaders $! iRequestHeaders ireq
isChunked = (CI.mk <$> H.lookup "transfer-encoding" hdrs)
== Just "chunked"
mbCL = unsafeFromInt <$> H.lookup "content-length" hdrs
cookies = fromMaybe [] (H.lookup "cookie" hdrs >>= parseCookie)
contextPath = "/"
uri = iRequestUri ireq
queryParams = parseUrlEncoded queryString
emptyParams = Map.empty
----------------------------------------------------------------------
(pathInfo, queryString) = first dropLeadingSlash . second (S.drop 1)
$ S.break (== '?') uri
----------------------------------------------------------------------
{-# INLINE dropLeadingSlash #-}
dropLeadingSlash s = let f (a, s') = if a == '/' then s' else s
mbS = S.uncons s
in maybe s f mbS
----------------------------------------------------------------------
{-# INLINE setupReadEnd #-}
setupReadEnd = do
readEnd' <- if isChunked
then readChunkedTransferEncoding readEnd
else return readEnd
maybe noContentLength Streams.takeBytes mbCL readEnd'
----------------------------------------------------------------------
noContentLength :: InputStream ByteString
-> IO (InputStream ByteString)
noContentLength readEnd' = do
when (method `elem` [POST, PUT]) return411
Streams.takeBytes 0 readEnd'
----------------------------------------------------------------------
return411 = do
let (major, minor) = version
let resp = mconcat [ fromByteString "HTTP/"
, fromShow major
, fromChar '.'
, fromShow minor
, fromByteString " 411 Length Required\r\n\r\n"
, fromByteString "411 Length Required\r\n"
, flush
]
Streams.write (Just resp) writeEnd
Streams.write Nothing writeEnd
terminateSession LengthRequiredException
----------------------------------------------------------------------
parseForm readEnd' = if doIt
then getIt
else return (readEnd', emptyParams)
where
trimIt = fst . S.spanEnd (== ' ') . S.takeWhile (/= ';')
. S.dropWhile (== ' ')
mbCT = trimIt <$> H.lookup "content-type" hdrs
doIt = mbCT == Just "application/x-www-form-urlencoded"
mAX_POST_BODY_SIZE = 1024 * 1024
getIt = do
readEnd'' <- Streams.throwIfProducesMoreThan
mAX_POST_BODY_SIZE readEnd'
contents <- S.concat <$> Streams.toList readEnd''
let postParams = parseUrlEncoded contents
finalReadEnd <- Streams.fromList [contents]
return (finalReadEnd, postParams)
----------------------------------------------------------------------
checkConnectionClose version hdrs = do
-- For HTTP/1.1: if there is an explicit Connection: close, close
-- the socket.
--
-- For HTTP/1.0: if there is no explicit Connection: Keep-Alive,
-- close the socket.
let v = CI.mk <$> H.lookup "Connection" hdrs
when ((version == (1, 1) && v == Just "close") ||
(version == (1, 0) && v /= Just "keep-alive")) $
writeIORef forceConnectionClose True
--------------------------------------------------------------------------
{-# INLINE badRequestWithNoHost #-}
badRequestWithNoHost :: IO a
badRequestWithNoHost = do
let msg = mconcat [
fromByteString "HTTP/1.1 400 Bad Request\r\n\r\n"
, fromByteString "400 Bad Request: HTTP/1.1 request with no "
, fromByteString "Host header\r\n"
, flush
]
Streams.write (Just msg) writeEnd
Streams.write Nothing writeEnd
terminateSession BadRequestException
--------------------------------------------------------------------------
{-# INLINE checkExpect100Continue #-}
checkExpect100Continue req =
when (getHeader "Expect" req == Just "100-continue") $ do
let (major, minor) = rqVersion req
let hl = mconcat [ fromByteString "HTTP/"
, fromShow major
, fromChar '.'
, fromShow minor
, fromByteString " 100 Continue\r\n\r\n"
, flush
]
Streams.write (Just hl) writeEnd
--------------------------------------------------------------------------
{-# INLINE processRequest #-}
processRequest !req = do
-- successfully parsed a request, so restart the timer
tickle $ max defaultTimeout
-- check for Expect: 100-continue
checkExpect100Continue req
runServerHandler req
`catches` [ Handler escapeSnapHandler
, Handler $ catchUserException "user handler" req
]
undefined
--------------------------------------------------------------------------
{-# INLINE runServerHandler #-}
runServerHandler !req = do
undefined
--------------------------------------------------------------------------
escapeSnapHandler (EscapeHttp escapeHandler) = escapeHandler tickle
readEnd
writeEnd
escapeSnapHandler (TerminateConnection e) = terminateSession e
--------------------------------------------------------------------------
catchUserException :: ByteString -> Request -> SomeException -> IO ()
catchUserException phase req e = do
logError $ mconcat [
fromByteString "Exception leaked to httpSession during phase '"
, fromByteString phase
, fromByteString "': \n"
, requestErrorMessage req e
]
terminateSession e
------------------------------------------------------------------------------
toHeaders :: [(ByteString, ByteString)] -> H.Headers
toHeaders = H.fromList . map (first CI.mk)
------------------------------------------------------------------------------
terminateSession :: Exception e => e -> IO a
terminateSession = throwIO . TerminateSessionException . SomeException
------------------------------------------------------------------------------
requestErrorMessage :: Request -> SomeException -> Builder
requestErrorMessage req e =
mconcat [ fromByteString "During processing of request from "
, fromByteString $ rqRemoteAddr req
, fromByteString ":"
, fromShow $ rqRemotePort req
, fromByteString "\nrequest:\n"
, fromShow $ show req
, fromByteString "\n"
, msgB
]
where
msgB = mconcat [
fromByteString "A web handler threw an exception. Details:\n"
, fromShow e
]
|
afcowie/new-snap-server
|
src/Snap/Internal/Http/Server/Session.hs
|
Haskell
|
bsd-3-clause
| 14,889
|
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS -w #-}
module Prelude (print, Base.Int) where
import Fay.Types (Fay)
import Fay.FFI
import qualified "base" Prelude as Base
import "base" Prelude (Bool(True,False)
,(||),(&&),seq,Eq,(==),(/=))
--------------------------------------------------------------------------------
-- Fixities
infixr 9 .
infixl 1 >>, >>=
infixr 0 $
--------------------------------------------------------------------------------
-- Aliases of base
type String = Base.String
type Double = Base.Double
type Char = Base.Char
--------------------------------------------------------------------------------
-- Standard data types
-- | Maybe type.
data Maybe a = Just a | Nothing
instance Base.Read a => Base.Read (Maybe a)
instance Base.Show a => Base.Show (Maybe a)
--------------------------------------------------------------------------------
-- Monads
-- | Monomorphic bind for Fay.
(>>=) :: Fay a -> (a -> Fay b) -> Fay b
(>>=) = ffi "Fay$$bind(%1)(%2)"
-- | Monomorphic then for Fay.
(>>) :: Ptr (Fay a) -> Ptr (Fay b) -> Ptr (Fay b)
(>>) = ffi "Fay$$then(%1)(%2)"
-- | Monomorphic return for Fay.
return :: a -> Fay a
return = ffi "Fay$$return(%1)"
--------------------------------------------------------------------------------
-- Show
-- | Uses JSON.stringify.
show :: Automatic a -> String
show = ffi "JSON.stringify(%1)"
--------------------------------------------------------------------------------
-- Functions
(.) :: (t1 -> t) -> (t2 -> t1) -> t2 -> t
(f . g) x = f (g x)
($) :: (t1 -> t) -> t1 -> t
f $ x = f x
--------------------------------------------------------------------------------
-- IO
print :: Automatic a -> Fay ()
print = ffi "(function(x) { if (console && console.log) console.log(x) })(%1)"
putStrLn :: String -> Fay ()
putStrLn = ffi "(function(x) { if (console && console.log) console.log(x) })(%1)"
|
faylang/fay-prim
|
src/Prelude.hs
|
Haskell
|
bsd-3-clause
| 2,030
|
{-# LANGUAGE TemplateHaskell #-}
module Main where
import qualified Data.Map as M
import Network
import NetworkedGame.Packet
import NetworkedGame.Server
import Control.Concurrent
import Control.Monad
import Control.Lens
import Data.Maybe
import System.IO
import System.Exit
import AnimatedDangerzone.Types
import Graphics.Gloss
import Graphics.Gloss.Juicy
import Graphics.Gloss.Interface.IO.Game
import AnimatedDangerzone.Client.Config as C
data ClientState =
ClientState { _clientCid :: ConnectionId
, _clientWorld :: World
, _clientHandle :: Handle
}
data Tile =
TEnv Block
| TPlayer
deriving (Eq, Read, Show, Ord)
makeLenses ''ClientState
tileFiles :: [(Tile, FilePath)]
tileFiles =
[ (TEnv Air, "images/tiles/dc-dngn/dngn_unseen.png")
, (TEnv Rubble, "images/tiles/dc-dngn/floor/cobble_blood5.png")
, (TEnv Rock, "images/tiles/dc-dngn/floor/cobble_blood1.png")
, (TEnv Stones, "images/tiles/dc-dngn/floor/floor_vines0.png")
, (TEnv Lava, "images/tiles/dc-dngn/floor/lava0.png")
, (TEnv Ice, "images/tiles/dc-dngn/floor/ice0.png")
, (TPlayer, "images/tiles/player/base/human_m.png")
]
loadTileMap :: IO (M.Map Tile Picture)
loadTileMap = do
pairs <- forM tileFiles $ \(t, path) ->
do Just p <- loadJuicy path
return (t, p)
return $ M.fromList pairs
clientState :: Handle -> ConnectionId -> World -> ClientState
clientState h cid w =
ClientState { _clientCid = cid
, _clientWorld = w
, _clientHandle = h
}
getPlayer :: MVar ClientState -> IO Player
getPlayer mv = do
cs <- readMVar mv
return $ fromJust $ cs^.clientWorld.worldPlayers.at (cs^.clientCid)
main :: IO ()
main = do
tileMap <- loadTileMap
withClientArgs $ \opts _ -> do
h <- connectTo (opts^.optServerName)
(PortNumber (opts^.optPortNumber))
hPutPacket h $ mkPacket $ ClientHello (opts^.optPlayerName)
resp <- hGetPacketed h
myCid <- case resp of
Hello myCid -> return myCid
UsernameConflict -> do
putStrLn "User already connected; please choose a different username."
exitFailure
_ -> do putStrLn "Protocol error: got unexpected message"
exitFailure
NewPlayer _ _ <- hGetPacketed h
SetWorld initialWorld <- hGetPacketed h
wmvar <- newMVar $ clientState h myCid initialWorld
_ <- forkIO $ forever $ networkThread h wmvar
let dpy = InWindow "game" (700, 700) (0, 0)
playIO
dpy
white
60
()
(const $ worldPicture wmvar tileMap)
(handleEvent wmvar)
stepWorld
moveUp :: MVar ClientState -> IO ()
moveUp mv = movePlayer mv (_1 +~ 1)
moveDown :: MVar ClientState -> IO ()
moveDown mv = movePlayer mv (_1 -~ 1)
moveLeft :: MVar ClientState -> IO ()
moveLeft mv = movePlayer mv (_2 -~ 1)
moveRight :: MVar ClientState -> IO ()
moveRight mv = movePlayer mv (_2 +~ 1)
movePlayer :: MVar ClientState -> (Coord -> Coord) -> IO ()
movePlayer mv f = do
p <- getPlayer mv
let old = p^.playerCoord
sendMessage mv $ ClientMove $ f old
sendMessage :: MVar ClientState -> ClientMsg -> IO ()
sendMessage mv msg = do
cs <- readMVar mv
hPutPacket (cs^.clientHandle) $ mkPacket msg
handleEvent :: MVar ClientState -> Event -> () -> IO ()
handleEvent mv e _st = do
case e of
EventKey (SpecialKey KeyUp) Down _ _ -> moveUp mv
EventKey (SpecialKey KeyDown) Down _ _ -> moveDown mv
EventKey (SpecialKey KeyLeft) Down _ _ -> moveLeft mv
EventKey (SpecialKey KeyRight) Down _ _ -> moveRight mv
_ -> return ()
return ()
-- Later, animation
stepWorld :: Float -> () -> IO ()
stepWorld = const return
networkThread :: Handle -> MVar ClientState -> IO ()
networkThread h mv = do
p <- hGetPacketed h
putStrLn $ "Got server packet: " ++ show p
case p of
SetWorld w -> modifyMVar_ mv $ \cs -> return $ cs & clientWorld .~ w
MovePlayer cid coord -> modifyMVar_ mv $ \cs ->
return $ cs & clientWorld.worldPlayers.ix cid.playerCoord .~ coord
un -> putStrLn $ "Unsupported message: " ++ show un
worldPicture :: MVar ClientState -> M.Map Tile Picture -> IO Picture
worldPicture mv tileMap = do
cs <- readMVar mv
let w = cs^.clientWorld
tilePicture (r,c) Nothing = trans (r,c) (TEnv Air)
tilePicture (r,c) (Just b) = trans (r,c) (TEnv b)
playerPicture p = trans (p^.playerCoord) TPlayer
trans (r,c) t = Translate (toEnum $ c*32) (toEnum $ r*32) $ tileMap M.! t
envTiles = [ tilePicture (r,c) (w^.worldBlocks.at(r,c))
| c <- [-20..20], r <- [-20..20] ]
playerTiles = [ playerPicture p | p <- M.elems (w^.worldPlayers) ]
return $ Pictures $ envTiles ++ playerTiles
|
glguy/animated-dangerzone
|
src/GlossClient.hs
|
Haskell
|
bsd-3-clause
| 4,792
|
-- Copyright (c) 2014 Eric McCorkle. All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- 3. Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS''
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
-- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
-- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.
{-# OPTIONS_GHC -Wall -Werror #-}
-- | Defines a class of monads representing access to source code.
-- This is useful for implementing lexers, as well as implementing a
-- diagnostic message printer.
module Control.Monad.SourceFiles.Class(
MonadSourceFiles(..)
) where
import Control.Monad.Cont
import Control.Monad.Except
import Control.Monad.List
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Trans.Journal
import Control.Monad.Writer
import Data.Array
import Data.ByteString hiding (map)
import Data.Position.Filename
-- | Class of monads that have access to source code.
class Monad m => MonadSourceFiles m where
-- | Get all lines from the source file.
sourceFile :: Filename
-- ^ The path to the source file.
-> m (Array Word ByteString)
-- ^ An array of all lines in the source file.
sourceFileSpan :: Filename
-- ^ The path to the source file.
-> Word
-- ^ The starting line
-> Word
-- ^ The ending line
-> m [ByteString]
sourceFileSpan fpath start end =
do
fdata <- sourceFile fpath
return $! map (fdata !) [start..end]
instance MonadSourceFiles m => MonadSourceFiles (ContT r m) where
sourceFile = lift . sourceFile
instance (MonadSourceFiles m) => MonadSourceFiles (ExceptT e m) where
sourceFile = lift . sourceFile
instance (MonadSourceFiles m) => MonadSourceFiles (JournalT e m) where
sourceFile = lift . sourceFile
instance MonadSourceFiles m => MonadSourceFiles (ListT m) where
sourceFile = lift . sourceFile
instance MonadSourceFiles m => MonadSourceFiles (ReaderT r m) where
sourceFile = lift . sourceFile
instance MonadSourceFiles m => MonadSourceFiles (StateT s m) where
sourceFile = lift . sourceFile
instance (MonadSourceFiles m, Monoid w) => MonadSourceFiles (WriterT w m) where
sourceFile = lift . sourceFile
|
emc2/compiler-misc
|
src/Control/Monad/SourceFiles/Class.hs
|
Haskell
|
bsd-3-clause
| 3,514
|
-- | Elliptic Curve Arithmetic.
--
-- /WARNING:/ These functions are vulnerable to timing attacks.
{-# LANGUAGE ScopedTypeVariables #-}
module Crypto.ECC.Simple.Prim
( scalarGenerate
, scalarFromInteger
, pointAdd
, pointDouble
, pointBaseMul
, pointMul
, pointAddTwoMuls
, pointFromIntegers
, isPointAtInfinity
, isPointValid
) where
import Data.Maybe
import Crypto.Internal.Imports
import Crypto.Internal.Proxy
import Crypto.Number.ModArithmetic
import Crypto.Number.F2m
import Crypto.Number.Generate (generateBetween)
import Crypto.ECC.Simple.Types
import Crypto.Error
import Crypto.Random
-- | Generate a valid scalar for a specific Curve
scalarGenerate :: forall randomly curve . (MonadRandom randomly, Curve curve) => randomly (Scalar curve)
scalarGenerate =
Scalar <$> generateBetween 1 (n - 1)
where
n = curveEccN $ curveParameters (Proxy :: Proxy curve)
scalarFromInteger :: forall curve . Curve curve => Integer -> CryptoFailable (Scalar curve)
scalarFromInteger n
| n < 0 || n >= mx = CryptoFailed $ CryptoError_EcScalarOutOfBounds
| otherwise = CryptoPassed $ Scalar n
where
mx = case curveType (Proxy :: Proxy curve) of
CurveBinary (CurveBinaryParam b) -> b
CurvePrime (CurvePrimeParam p) -> p
--TODO: Extract helper function for `fromMaybe PointO...`
-- | Elliptic Curve point negation:
-- @pointNegate p@ returns point @q@ such that @pointAdd p q == PointO@.
pointNegate :: Curve curve => Point curve -> Point curve
pointNegate PointO = PointO
pointNegate point@(Point x y) =
case curveType point of
CurvePrime {} -> Point x (-y)
CurveBinary {} -> Point x (x `addF2m` y)
-- | Elliptic Curve point addition.
--
-- /WARNING:/ Vulnerable to timing attacks.
pointAdd :: Curve curve => Point curve -> Point curve -> Point curve
pointAdd PointO PointO = PointO
pointAdd PointO q = q
pointAdd p PointO = p
pointAdd p q
| p == q = pointDouble p
| p == pointNegate q = PointO
pointAdd point@(Point xp yp) (Point xq yq) =
case ty of
CurvePrime (CurvePrimeParam pr) -> fromMaybe PointO $ do
s <- divmod (yp - yq) (xp - xq) pr
let xr = (s ^ (2::Int) - xp - xq) `mod` pr
yr = (s * (xp - xr) - yp) `mod` pr
return $ Point xr yr
CurveBinary (CurveBinaryParam fx) -> fromMaybe PointO $ do
s <- divF2m fx (yp `addF2m` yq) (xp `addF2m` xq)
let xr = mulF2m fx s s `addF2m` s `addF2m` xp `addF2m` xq `addF2m` a
yr = mulF2m fx s (xp `addF2m` xr) `addF2m` xr `addF2m` yp
return $ Point xr yr
where
ty = curveType point
cc = curveParameters point
a = curveEccA cc
-- | Elliptic Curve point doubling.
--
-- /WARNING:/ Vulnerable to timing attacks.
--
-- This perform the following calculation:
-- > lambda = (3 * xp ^ 2 + a) / 2 yp
-- > xr = lambda ^ 2 - 2 xp
-- > yr = lambda (xp - xr) - yp
--
-- With binary curve:
-- > xp == 0 => P = O
-- > otherwise =>
-- > s = xp + (yp / xp)
-- > xr = s ^ 2 + s + a
-- > yr = xp ^ 2 + (s+1) * xr
--
pointDouble :: Curve curve => Point curve -> Point curve
pointDouble PointO = PointO
pointDouble point@(Point xp yp) =
case ty of
CurvePrime (CurvePrimeParam pr) -> fromMaybe PointO $ do
lambda <- divmod (3 * xp ^ (2::Int) + a) (2 * yp) pr
let xr = (lambda ^ (2::Int) - 2 * xp) `mod` pr
yr = (lambda * (xp - xr) - yp) `mod` pr
return $ Point xr yr
CurveBinary (CurveBinaryParam fx)
| xp == 0 -> PointO
| otherwise -> fromMaybe PointO $ do
s <- return . addF2m xp =<< divF2m fx yp xp
let xr = mulF2m fx s s `addF2m` s `addF2m` a
yr = mulF2m fx xp xp `addF2m` mulF2m fx xr (s `addF2m` 1)
return $ Point xr yr
where
ty = curveType point
cc = curveParameters point
a = curveEccA cc
-- | Elliptic curve point multiplication using the base
--
-- /WARNING:/ Vulnerable to timing attacks.
pointBaseMul :: Curve curve => Scalar curve -> Point curve
pointBaseMul n = pointMul n (curveEccG $ curveParameters (Proxy :: Proxy curve))
-- | Elliptic curve point multiplication (double and add algorithm).
--
-- /WARNING:/ Vulnerable to timing attacks.
pointMul :: Curve curve => Scalar curve -> Point curve -> Point curve
pointMul _ PointO = PointO
pointMul (Scalar n) p
| n == 0 = PointO
| n == 1 = p
| odd n = pointAdd p (pointMul (Scalar (n - 1)) p)
| otherwise = pointMul (Scalar (n `div` 2)) (pointDouble p)
-- | Elliptic curve double-scalar multiplication (uses Shamir's trick).
--
-- > pointAddTwoMuls n1 p1 n2 p2 == pointAdd (pointMul n1 p1)
-- > (pointMul n2 p2)
--
-- /WARNING:/ Vulnerable to timing attacks.
pointAddTwoMuls :: Curve curve => Scalar curve -> Point curve -> Scalar curve -> Point curve -> Point curve
pointAddTwoMuls _ PointO _ PointO = PointO
pointAddTwoMuls _ PointO n2 p2 = pointMul n2 p2
pointAddTwoMuls n1 p1 _ PointO = pointMul n1 p1
pointAddTwoMuls (Scalar n1) p1 (Scalar n2) p2 = go (n1, n2)
where
p0 = pointAdd p1 p2
go (0, 0 ) = PointO
go (k1, k2) =
let q = pointDouble $ go (k1 `div` 2, k2 `div` 2)
in case (odd k1, odd k2) of
(True , True ) -> pointAdd p0 q
(True , False ) -> pointAdd p1 q
(False , True ) -> pointAdd p2 q
(False , False ) -> q
-- | Check if a point is the point at infinity.
isPointAtInfinity :: Point curve -> Bool
isPointAtInfinity PointO = True
isPointAtInfinity _ = False
-- | Make a point on a curve from integer (x,y) coordinate
--
-- if the point is not valid related to the curve then an error is
-- returned instead of a point
pointFromIntegers :: forall curve . Curve curve => (Integer, Integer) -> CryptoFailable (Point curve)
pointFromIntegers (x,y)
| isPointValid (Proxy :: Proxy curve) x y = CryptoPassed $ Point x y
| otherwise = CryptoFailed $ CryptoError_PointCoordinatesInvalid
-- | check if a point is on specific curve
--
-- This perform three checks:
--
-- * x is not out of range
-- * y is not out of range
-- * the equation @y^2 = x^3 + a*x + b (mod p)@ holds
isPointValid :: Curve curve => proxy curve -> Integer -> Integer -> Bool
isPointValid proxy x y =
case ty of
CurvePrime (CurvePrimeParam p) ->
let a = curveEccA cc
b = curveEccB cc
eqModP z1 z2 = (z1 `mod` p) == (z2 `mod` p)
isValid e = e >= 0 && e < p
in isValid x && isValid y && (y ^ (2 :: Int)) `eqModP` (x ^ (3 :: Int) + a * x + b)
CurveBinary (CurveBinaryParam fx) ->
let a = curveEccA cc
b = curveEccB cc
add = addF2m
mul = mulF2m fx
isValid e = modF2m fx e == e
in and [ isValid x
, isValid y
, ((((x `add` a) `mul` x `add` y) `mul` x) `add` b `add` (squareF2m fx y)) == 0
]
where
ty = curveType proxy
cc = curveParameters proxy
-- | div and mod
divmod :: Integer -> Integer -> Integer -> Maybe Integer
divmod y x m = do
i <- inverse (x `mod` m) m
return $ y * i `mod` m
|
tekul/cryptonite
|
Crypto/ECC/Simple/Prim.hs
|
Haskell
|
bsd-3-clause
| 7,400
|
module Koan where
allEnrolled :: Bool
allEnrolled = False
|
Kheldar/hw-koans
|
koan/Koan.hs
|
Haskell
|
bsd-3-clause
| 59
|
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, DeriveDataTypeable, PatternGuards #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.Mosaic
-- Copyright : (c) 2009 Adam Vogt, 2007 James Webb
-- License : BSD-style (see xmonad/LICENSE)
--
-- Maintainer : vogt.adam<at>gmail.com
-- Stability : unstable
-- Portability : unportable
--
-- Based on MosaicAlt, but aspect ratio messages always change the aspect
-- ratios, and rearranging the window stack changes the window sizes.
--
-----------------------------------------------------------------------------
module XMonad.Layout.Mosaic (
-- * Usage
-- $usage
Aspect(..)
,mosaic
,changeMaster
,changeFocused
,Mosaic
)
where
import Prelude hiding (sum)
import XMonad(Typeable,
LayoutClass(doLayout, handleMessage, pureMessage, description),
Message, X, fromMessage, withWindowSet, Resize(..),
splitHorizontallyBy, splitVerticallyBy, sendMessage, Rectangle)
import qualified XMonad.StackSet as W
import Control.Arrow(second, first)
import Control.Monad(mplus)
import Data.Foldable(Foldable,foldMap, sum)
import Data.Function(on)
import Data.List(sortBy)
import Data.Monoid(Monoid,mempty, mappend)
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Layout.Mosaic
--
-- Then edit your @layoutHook@ by adding the Mosaic layout:
--
-- > myLayout = mosaic 2 [3,2] ||| Full ||| etc..
-- > main = xmonad $ defaultConfig { layoutHook = myLayout }
--
-- Unfortunately, infinite lists break serialization, so don't use them. And if
-- the list is too short, it is extended with @++ repeat 1@, which covers the
-- main use case.
--
-- To change the choice in aspect ratio and the relative sizes of windows, add
-- to your keybindings:
--
-- > , ((modm, xK_a), sendMessage Taller)
-- > , ((modm, xK_z), sendMessage Wider)
--
-- > , ((modm, xK_r), sendMessage Reset)
--
-- For more detailed instructions on editing the layoutHook see:
--
-- "XMonad.Doc.Extending#Editing_the_layout_hook"
data Aspect
= Taller
| Wider
| Reset
| SlopeMod ([Rational] -> [Rational])
deriving (Typeable)
instance Message Aspect
-- | The relative magnitudes (the sign is ignored) of the rational numbers in
-- the second argument determine the relative areas that the windows receive.
-- The first number represents the size of the master window, the second is for
-- the next window in the stack, and so on.
--
-- The list is extended with @++ repeat 1@, so @mosaic 1.5 []@ is like a
-- resizable grid.
--
-- The first parameter is the multiplicative factor to use when responding to
-- the 'Expand' message.
mosaic :: Rational -> [Rational] -> Mosaic a
mosaic = Mosaic Nothing
data Mosaic a = -- | True to override the aspect, current index, maximum index
Mosaic (Maybe(Bool,Rational,Int)) Rational [Rational] deriving (Read,Show)
instance LayoutClass Mosaic a where
description = const "Mosaic"
pureMessage (Mosaic Nothing _ _) _ = Nothing
pureMessage (Mosaic (Just(_,ix,mix)) delta ss) ms = fromMessage ms >>= ixMod
where ixMod Taller | round ix >= mix = Nothing
| otherwise = Just $ Mosaic (Just(False,succ ix,mix)) delta ss
ixMod Wider | round ix <= (0::Integer) = Nothing
| otherwise = Just $ Mosaic (Just(False,pred ix,mix)) delta ss
ixMod Reset = Just $ Mosaic Nothing delta ss
ixMod (SlopeMod f) = Just $ Mosaic (Just(False,ix,mix)) delta (f ss)
handleMessage l@(Mosaic _ delta _) ms
| Just Expand <- fromMessage ms = changeFocused (*delta) >> return Nothing
| Just Shrink <- fromMessage ms = changeFocused (/delta) >> return Nothing
| otherwise = return $ pureMessage l ms
doLayout (Mosaic state delta ss) r st = let
ssExt = zipWith const (ss ++ repeat 1) $ W.integrate st
rects = splits r ssExt
nls = length rects
fi = fromIntegral
nextIx (ov,ix,mix)
| mix <= 0 || ov = fromIntegral $ nls `div` 2
| otherwise = max 0 $ (*fi (pred nls)) $ min 1 $ ix / fi mix
rect = rects !! maybe (nls `div` 2) round (nextIx `fmap` state)
state' = fmap (\x@(ov,_,_) -> (ov,nextIx x,pred nls)) state
`mplus` Just (True,fromIntegral nls / 2,pred nls)
ss' = maybe ss (const ss `either` const ssExt) $ zipRemain ss ssExt
in return (zip (W.integrate st) rect, Just $ Mosaic state' delta ss')
zipRemain :: [a] -> [b] -> Maybe (Either [a] [b])
zipRemain (_:xs) (_:ys) = zipRemain xs ys
zipRemain [] [] = Nothing
zipRemain [] y = Just (Right y)
zipRemain x [] = Just (Left x)
-- | These sample functions are meant to be applied to the list of window sizes
-- through the 'SlopeMod' message.
changeMaster :: (Rational -> Rational) -> X ()
changeMaster = sendMessage . SlopeMod . onHead
-- | Apply a function to the Rational that represents the currently focused
-- window.
--
-- 'Expand' and 'Shrink' messages are responded to with @changeFocused
-- (*delta)@ or @changeFocused (delta/)@ where @delta@ is the first argument to
-- 'mosaic'.
--
-- This is exported because other functions (ex. @const 1@, @(+1)@) may be
-- useful to apply to the current area.
changeFocused :: (Rational -> Rational) -> X ()
changeFocused f = withWindowSet $ sendMessage . SlopeMod
. maybe id (mulIx . length . W.up)
. W.stack . W.workspace . W.current
where mulIx i = uncurry (++) . second (onHead f) . splitAt i
onHead :: (a -> a) -> [a] -> [a]
onHead f = uncurry (++) . first (fmap f) . splitAt 1
splits :: Rectangle -> [Rational] -> [[Rectangle]]
splits rect = map (reverse . map snd . sortBy (compare `on` fst))
. splitsL rect . makeTree snd . zip [1..]
. normalize . reverse . map abs
splitsL :: Rectangle -> Tree (Int,Rational) -> [[(Int,Rectangle)]]
splitsL _rect Empty = []
splitsL rect (Leaf (x,_)) = [[(x,rect)]]
splitsL rect (Branch l r) = do
let mkSplit f = f ((sumSnd l /) $ sumSnd l + sumSnd r) rect
sumSnd = sum . fmap snd
(rl,rr) <- map mkSplit [splitVerticallyBy,splitHorizontallyBy]
splitsL rl l `interleave` splitsL rr r
-- like zipWith (++), but when one list is shorter, its elements are duplicated
-- so that they match
interleave :: [[a]] -> [[a]] -> [[a]]
interleave xs ys | lx > ly = zc xs (extend lx ys)
| otherwise = zc (extend ly xs) ys
where lx = length xs
ly = length ys
zc = zipWith (++)
extend :: Int -> [a] -> [a]
extend n pat = do
(p,e) <- zip pat $ replicate m True ++ repeat False
[p | e] ++ replicate d p
where (d,m) = n `divMod` length pat
normalize :: Fractional a => [a] -> [a]
normalize x = let s = sum x in map (/s) x
data Tree a = Branch (Tree a) (Tree a) | Leaf a | Empty
instance Foldable Tree where
foldMap _f Empty = mempty
foldMap f (Leaf x) = f x
foldMap f (Branch l r) = foldMap f l `mappend` foldMap f r
instance Functor Tree where
fmap f (Leaf x) = Leaf $ f x
fmap f (Branch l r) = Branch (fmap f l) (fmap f r)
fmap _ Empty = Empty
instance Monoid (Tree a) where
mempty = Empty
mappend Empty x = x
mappend x Empty = x
mappend x y = Branch x y
makeTree :: (Num a1, Ord a1) => (a -> a1) -> [a] -> Tree a
makeTree _ [] = Empty
makeTree _ [x] = Leaf x
makeTree f xs = Branch (makeTree f a) (makeTree f b)
where ((a,b),_) = foldr go (([],[]),(0,0)) xs
go n ((ls,rs),(l,r))
| l > r = ((ls,n:rs),(l,f n+r))
| otherwise = ((n:ls,rs),(f n+l,r))
|
adinapoli/xmonad-contrib
|
XMonad/Layout/Mosaic.hs
|
Haskell
|
bsd-3-clause
| 7,814
|
module Options.OptimizationLevels where
import Types
optimizationLevelsOptions :: [Flag]
optimizationLevelsOptions =
[ flag { flagName = "-O0"
, flagDescription = "Disable optimisations (default)"
, flagType = DynamicFlag
, flagReverse = "-O"
}
, flag { flagName = "-O, -O1"
, flagDescription = "Enable level 1 optimisations"
, flagType = DynamicFlag
, flagReverse = "-O0"
}
, flag { flagName = "-O2"
, flagDescription = "Enable level 2 optimisations"
, flagType = DynamicFlag
, flagReverse = "-O0"
}
, flag { flagName = "-Odph"
, flagDescription =
"Enable level 2 optimisations, set "++
"``-fmax-simplifier-iterations=20`` "++
"and ``-fsimplifier-phases=3``."
, flagType = DynamicFlag
}
]
|
siddhanathan/ghc
|
utils/mkUserGuidePart/Options/OptimizationLevels.hs
|
Haskell
|
bsd-3-clause
| 870
|
module T5385a where
data T = Int ::: Int
|
urbanslug/ghc
|
testsuite/tests/rename/should_fail/T5385a.hs
|
Haskell
|
bsd-3-clause
| 42
|
import Data.List
import Control.Applicative
import Control.Arrow
import Control.Monad
import RankSelection
type Matrix a = (Int->Int->a, Int, Int)
-- The input is an matrix sorted in both row and column order
-- This selects the kth smallest element. (0th is the smallest)
selectMatrixRank :: Ord a => Int -> Matrix a -> a
selectMatrixRank k (f,n,m)
| k >= n*m || k < 0 = error "rank doesn't exist"
| otherwise = fst $ fst $ biselect k k (f', min n (k+1), min m (k+1))
where f' x y= (f x y, (x, y))
biselect :: Ord a => Int -> Int -> Matrix a -> (a,a)
biselect lb ub (f',n',m') = join (***) (selectRank values) (lb-ra, ub-ra)
where mat@(f,n,m)
| n' > m' = (flip f', m', n')
| otherwise = (f', n', m')
(a, b)
| n < 3 = (f 0 0, f (n-1) (m-1))
| otherwise = biselect lb' ub' halfMat
(lb', ub') = (lb `div` 2, min ((ub `div` 2) + n) (n * hm - 1))
(ra, values) = (rankInMatrix mat a, selectRange mat a b)
halfMat
| even m = (\x y->f x (if y < hm - 1 then 2 * y else 2 * y - 1), n, hm)
| odd m = (\x y->f x (2*y), n, hm)
hm = m `div` 2 + 1
-- the rank of an element in the matrix
rankInMatrix :: Ord a => Matrix a -> a -> Int
rankInMatrix mat a = sum (map (\(_,y)->1+y) $ frontier mat a)-1
-- select all elements x in the matrix such that a <= x <= b
selectRange :: Ord a => Matrix a -> a -> a -> [a]
selectRange mat@(f,_,_) a b = concatMap search (frontier mat b)
where search (x,y) = takeWhile (>=a) $ map (f x) [y,y-1..0]
frontier :: Ord a => Matrix a -> a -> [(Int,Int)]
frontier (f,n,m) b = step 0 (m-1)
where step i j
| i > n-1 || j < 0 = []
| f i j <= b = (i,j):step (i+1) j
| otherwise = step i (j-1)
-- toString (f, n, m) = show (n,m) ++ show [[f i j|i<-[0..n-1]]|j<-[0..m-1]]
--listVersion (f,n,m) = [f i j|i<-[0..n-1],j<-[0..m-1]]
--trace ("bisecting call "++show lb'++" "++ show ub'++ " elements "++ show a ++ " "++show b ++ toString (half mat)) $
mapf f x y= (f x y, (x, y))
matrix :: Matrix Int
matrix = (fff,4,4)
fff:: Int->Int->Int
fff i j = ([[0,1,1,1],
[1,2,3,4],
[3,3,4,5],
[10,11,12,13]]!!i)!!j
|
chaoxu/haskell-algorithm
|
MatrixRankSelection.hs
|
Haskell
|
mit
| 2,220
|
-- ------------------------------------------------------ --
-- Copyright © 2014 AlephCloud Systems, Inc.
-- ------------------------------------------------------ --
{-# LANGUAGE CPP #-}
{-# LANGUAGE UnicodeSyntax #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE IncoherentInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module BayHac2014.Cryptmail.Json.Instances ()
where
import Data.Monoid.Unicode
import Control.Applicative
import Data.Word
import qualified Data.Set as S
import Prelude.Unicode
import qualified BayHac2014.Cryptmail.Text as T
import BayHac2014.Cryptmail.Json.Types
-- ---------------------------------- --
-- Basic Values
instance ToJSON Value where
toJSON = id
{-# INLINE toJSON #-}
instance FromJSON Value where
parseJSON = pure
{-# INLINE parseJSON #-}
instance ToJSON () where
toJSON _ = Array []
{-# INLINE toJSON #-}
instance FromJSON () where
parseJSON = withArray "()" $ \case
[] → pure ()
_ → fail "Expected an empty array"
{-# INLINE parseJSON #-}
instance ToJSON String where
toJSON = String ∘ T.pack
{-# INLINE toJSON #-}
instance FromJSON String where
parseJSON = withString "String" pure
{-# INLINE parseJSON #-}
instance ToJSON T.Text where
toJSON = String
{-# INLINE toJSON #-}
instance FromJSON T.Text where
parseJSON = withText "Text" pure
{-# INLINE parseJSON #-}
instance ToJSON Bool where
toJSON = Bool
{-# INLINE toJSON #-}
instance FromJSON Bool where
parseJSON = withBool "Bool" pure
{-# INLINE parseJSON #-}
-- ---------------------------------- --
-- Functors (and alike)
instance ToJSON α ⇒ ToJSON (Maybe α) where
toJSON Nothing = Null
toJSON (Just a) = toJSON a
{-# INLINE toJSON #-}
instance FromJSON α ⇒ FromJSON (Maybe α) where
parseJSON Null = pure Nothing
parseJSON a = Just <$> parseJSON a
{-# INLINE parseJSON #-}
instance ToJSON α ⇒ ToJSON [α] where
toJSON = Array ∘ map toJSON
{-# INLINE toJSON #-}
instance FromJSON α ⇒ FromJSON [α] where
parseJSON = withArray "[α]" $ mapM parseJSON
{-# INLINE parseJSON #-}
instance (ToJSON α, ToJSON β) ⇒ ToJSON (α, β) where
toJSON (a, b) = Array $ [toJSON a, toJSON b]
{-# INLINE toJSON #-}
instance (FromJSON α, FromJSON β) ⇒ FromJSON (α, β) where
parseJSON = withArray "(a,b)" $ \case
[a,b] → (,) <$> parseJSON a <*> parseJSON b
l → fail $ "cannot unpack array of length " ⊕ show (length l) ⊕ " into a tupple"
{-# INLINE parseJSON #-}
instance (ToJSON α, ToJSON β, ToJSON γ) ⇒ ToJSON (α, β, γ) where
toJSON (a, b, c) = Array $ [toJSON a, toJSON b, toJSON c]
{-# INLINE toJSON #-}
instance (FromJSON α, FromJSON β, FromJSON γ) ⇒ FromJSON (α, β, γ) where
parseJSON = withArray "(α, β, γ)" $ \case
[a,b,c] → (,,) <$> parseJSON a <*> parseJSON b <*> parseJSON c
l → fail $ "cannot unpack array of length " ⊕ show (length l) ⊕ " into a tripple"
{-# INLINE parseJSON #-}
instance ToJSON α ⇒ ToJSON (S.Set α) where
toJSON = toJSON ∘ S.toList
{-# INLINE toJSON #-}
instance (Ord α, FromJSON α) ⇒ FromJSON (S.Set α) where
parseJSON = fmap S.fromList ∘ parseJSON
{-# INLINE parseJSON #-}
instance (ToJSON α, ToJSON β) ⇒ ToJSON (Either α β) where
toJSON (Left a) = object [jsleft .= a]
toJSON (Right b) = object [jsright .= b]
{-# INLINE toJSON #-}
instance (FromJSON α, FromJSON β) ⇒ FromJSON (Either α β) where
parseJSON (Object [(key, value)])
| key ≡ jsleft = Left <$> parseJSON value
| key ≡ jsright = Right <$> parseJSON value
parseJSON _ = fail ""
{-# INLINE parseJSON #-}
jsleft, jsright ∷ T.Text
jsleft = "Left"
jsright = "Right"
{-# INLINE jsleft #-}
{-# INLINE jsright #-}
-- ---------------------------------- --
-- Numbers
numToJson ∷ Integral α ⇒ α → Value
numToJson = Number ∘ fromInteger ∘ toInteger
{-# INLINE numToJson #-}
instance ToJSON Number where
toJSON = Number
{-# INLINE toJSON #-}
instance FromJSON Number where
parseJSON (Number n) = pure n
parseJSON Null = pure (D (0/0))
parseJSON v = typeMismatch "Number" v
{-# INLINE parseJSON #-}
instance ToJSON Integer where
toJSON = Number ∘ fromInteger
{-# INLINE toJSON #-}
instance FromJSON Integer where
parseJSON = withNumber "Integer" $ return ∘ floor
{-# INLINE parseJSON #-}
instance ToJSON Int where
toJSON = numToJson
{-# INLINE toJSON #-}
instance FromJSON Int where
parseJSON = withNumber "Integral" $ return ∘ floor
{-# INLINE parseJSON #-}
instance ToJSON Word8 where
toJSON = numToJson
{-# INLINE toJSON #-}
instance FromJSON Word8 where
parseJSON = withNumber "Word8" $ return ∘ floor
{-# INLINE parseJSON #-}
instance ToJSON Word16 where
toJSON = numToJson
{-# INLINE toJSON #-}
instance FromJSON Word16 where
parseJSON = withNumber "Word16" $ return ∘ floor
{-# INLINE parseJSON #-}
instance ToJSON Word32 where
toJSON = numToJson
{-# INLINE toJSON #-}
instance FromJSON Word32 where
parseJSON = withNumber "Word32" $ return ∘ floor
{-# INLINE parseJSON #-}
instance ToJSON Word64 where
toJSON = numToJson
{-# INLINE toJSON #-}
instance FromJSON Word64 where
parseJSON = withNumber "Word64" $ return ∘ floor
{-# INLINE parseJSON #-}
instance ToJSON Double where
toJSON = Number ∘ D
{-# INLINE toJSON #-}
instance FromJSON Double where
parseJSON (Number n) = case n of
D d → pure d
I i → pure (fromIntegral i)
parseJSON Null = pure (0/0)
parseJSON v = typeMismatch "Double" v
{-# INLINE parseJSON #-}
|
alephcloud/bayhac2014
|
src/BayHac2014/Cryptmail/Json/Instances.hs
|
Haskell
|
mit
| 6,101
|
{-# htermination min :: Int -> Int -> Int #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_min_5.hs
|
Haskell
|
mit
| 46
|
-- | Old compilers, will not compile with newer language changes.
-- =======================================================================================
-- | First compiler turns everything into a dynamic type. Uses a lot of unnecessary
-- | casting to work though.
compileDyn :: DL.Exp -> StaticExp Dynamic
compileDyn (DL.Lam str exp) =
To $ Lam str (compileDyn exp)
-- No need to To we already return a Dynamic after function application.
compileDyn (f DL.:@ exp) =
From (compileDyn f) :@ (compileDyn exp)
compileDyn (DL.Bin op exp1 exp2) =
To $ IntBin op sExp1 sExp2
where sExp1 = From $ compileDyn exp1
sExp2 = From $ compileDyn exp2
compileDyn (DL.Lit n) = To (IntLit n)
compileDyn (DL.Var str) = Var str
-- the "compileDyn exps" are both of type Dynamic so the entire expression has
-- type Dynamic.
compileDyn (DL.If cond exp1 exp2) =
If (compileDyn cond) (compileDyn exp1) (compileDyn exp2)
-- =======================================================================================
data Result where
Result :: (Typeable t) => StaticExp t -> Result
printResults :: Result -> IO()
printResults (Result exp) = putStrLn (show exp)
-- | The issue with `compileDyn` is the return type of all cases must be the same
-- | StaticExp t, so t must be Dynamic. Instead we wrap the results in type.
compileRes :: DL.Exp -> Result
-- The second argument of a Lam must be dynamic.
compileRes (DL.Lam str exp) = case (compileRes exp) of
Result exp' -> Result $ Lam str (ensureDyn exp')
compileRes (f DL.:@ exp) =
case (compileRes f, compileRes exp) of
(Result f', Result exp') ->
Result (castType f' :@ (ensureDyn exp') :: StaticExp Dynamic)
compileRes (DL.Bin op exp1 exp2) =
case (compileRes exp1, compileRes exp2) of
-- Bin requires the type of both operators to be the same and that's the
-- type of the whole expression. After compileRes there is no guarantee the
-- types are the same so we must explicitly cast them if they are the same.
(Result exp1', Result exp2') -> Result $ Bin op (castType exp1') (castType exp2')
compileRes (DL.Lit n) = Result (Lit n)
compileRes (DL.Var str) = Result (Var str)
compileRes (DL.If cond exp1 exp2) =
case (compileRes cond, compileRes exp1, compileRes exp2) of
-- We expect the type of both branches of an If to be the same, else it may not
-- necessarly be wrong as one branch may return a dynamic. So we wrap both sides
-- in dynamics.
(Result cond',
-- Get the type of both expressions to compare.
Result (exp1' :: StaticExp a),
Result (exp2' :: StaticExp b)) ->
case eqT (typeRep :: TypeRep a) (typeRep :: TypeRep b) of
Just Refl -> Result $ If (ensureDyn cond') exp1' exp2'
Nothing -> Result $ If (ensureDyn cond') (ensureDyn exp1') (ensureDyn exp2')
-- We want to cast from an 'a' to a 'b' but our types are wrapped in a
-- StaticExp so we use gcast!
-- gcast :: forall a b c. (Typeable a, Typeable b) => c a -> Maybe (c b)
-- | Given an StaticExp t1 we attempt to cast to a t2 if the types are the same.
-- | If it is a Dynamic we add a call to From and defer this check to run time.
-- | Otherwise we for sure have an error.
castType :: (Typeable t1, Typeable t2) => StaticExp t1 -> StaticExp t2
castType t = case gcast t of
Just i -> i
Nothing -> case gcast t of
Just i -> From i
Nothing -> error $ "castType: They type of " ++ show t ++
" does not match t2 or Dynamic."
-- | Given a typeable value check if it's Dynamic, else we add turn in into a Dynamic
-- | by wrapping it in a To.
ensureDyn :: forall t. Typeable t => StaticExp t -> StaticExp Dynamic
ensureDyn val = case (eqT (typeRep :: TypeRep t) (typeRep :: TypeRep Dynamic)) of
Just Refl -> val
Nothing -> To val
testCompileRes :: DL.Exp -> StaticExp Int
testCompileRes e = case compileRes e of
(Result e') -> castType e'
-- =======================================================================================
|
plclub/cis670-16fa
|
projects/DynamicLang/src/OldCompilers.hs
|
Haskell
|
mit
| 4,098
|
module Main where
import Game.Poker.Simple
main :: IO ()
main = putStrLn "Hello World"
|
tobynet/java-poker
|
app/Main.hs
|
Haskell
|
mit
| 88
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE QuasiQuotes #-}
{- |
Module : Language.Egison.Math.Expr
Licence : MIT
This module defines the internal representation of mathematic objects such as
polynominals, and some useful patterns.
-}
module Language.Egison.Math.Expr
( ScalarData (..)
, PolyExpr (..)
, TermExpr (..)
, Monomial
, SymbolExpr (..)
, Printable (..)
, pattern ZeroExpr
, pattern SingleSymbol
, pattern SingleTerm
, ScalarM (..)
, TermM (..)
, SymbolM (..)
, term
, termM
, symbol
, symbolM
, func
, funcM
, apply
, applyM
, quote
, negQuote
, negQuoteM
, equalMonomial
, equalMonomialM
, zero
, zeroM
, singleTerm
, singleTermM
, mathScalarMult
, mathNegate
) where
import Data.List (intercalate)
import Prelude hiding (foldr, mappend, mconcat)
import Control.Egison
import Control.Monad (MonadPlus (..))
import Language.Egison.IExpr (Index (..))
--
-- Data
--
data ScalarData
= Div PolyExpr PolyExpr
deriving Eq
newtype PolyExpr
= Plus [TermExpr]
data TermExpr
= Term Integer Monomial
-- We choose the definition 'monomials' without its coefficients.
-- ex. 2 x^2 y^3 is *not* a monomial. x^2 t^3 is a monomial.
type Monomial = [(SymbolExpr, Integer)]
data SymbolExpr
= Symbol Id String [Index ScalarData]
| Apply ScalarData [ScalarData]
| Quote ScalarData
| FunctionData ScalarData [ScalarData] [ScalarData] -- fnname argnames args
deriving Eq
type Id = String
-- Matchers
data ScalarM = ScalarM
instance Matcher ScalarM ScalarData
data TermM = TermM
instance Matcher TermM TermExpr
data SymbolM = SymbolM
instance Matcher SymbolM SymbolExpr
term :: Pattern (PP Integer, PP Monomial) TermM TermExpr (Integer, Monomial)
term _ _ (Term a mono) = pure (a, mono)
termM :: TermM -> TermExpr -> (Eql, Multiset (Pair SymbolM Eql))
termM TermM _ = (Eql, Multiset (Pair SymbolM Eql))
symbol :: Pattern (PP String) SymbolM SymbolExpr String
symbol _ _ (Symbol _ name []) = pure name
symbol _ _ _ = mzero
symbolM :: SymbolM -> p -> Eql
symbolM SymbolM _ = Eql
func :: Pattern (PP ScalarData, PP [ScalarData])
SymbolM SymbolExpr (ScalarData, [ScalarData])
func _ _ (FunctionData name _ args) = pure (name, args)
func _ _ _ = mzero
funcM :: SymbolM -> SymbolExpr -> (ScalarM, List ScalarM)
funcM SymbolM _ = (ScalarM, List ScalarM)
apply :: Pattern (PP String, PP [ScalarData]) SymbolM SymbolExpr (String, [ScalarData])
apply _ _ (Apply (SingleSymbol (Symbol _ fn _)) args) = pure (fn, args)
apply _ _ _ = mzero
applyM :: SymbolM -> p -> (Eql, List ScalarM)
applyM SymbolM _ = (Eql, List ScalarM)
quote :: Pattern (PP ScalarData) SymbolM SymbolExpr ScalarData
quote _ _ (Quote m) = pure m
quote _ _ _ = mzero
negQuote :: Pattern (PP ScalarData) SymbolM SymbolExpr ScalarData
negQuote _ _ (Quote m) = pure (mathNegate m)
negQuote _ _ _ = mzero
negQuoteM :: SymbolM -> p -> ScalarM
negQuoteM SymbolM _ = ScalarM
equalMonomial :: Pattern (PP Integer, PP Monomial) (Multiset (Pair SymbolM Eql)) Monomial (Integer, Monomial)
equalMonomial (_, VP xs) _ ys = case isEqualMonomial xs ys of
Just sgn -> pure (sgn, xs)
Nothing -> mzero
equalMonomial _ _ _ = mzero
equalMonomialM :: Multiset (Pair SymbolM Eql) -> p -> (Eql, Multiset (Pair SymbolM Eql))
equalMonomialM (Multiset (Pair SymbolM Eql)) _ = (Eql, Multiset (Pair SymbolM Eql))
zero :: Pattern () ScalarM ScalarData ()
zero _ _ (Div (Plus []) _) = pure ()
zero _ _ _ = mzero
zeroM :: ScalarM -> p -> ()
zeroM ScalarM _ = ()
singleTerm :: Pattern (PP Integer, PP Integer, PP Monomial) ScalarM ScalarData (Integer, Integer, Monomial)
singleTerm _ _ (Div (Plus [Term c mono]) (Plus [Term c2 []])) = pure (c, c2, mono)
singleTerm _ _ _ = mzero
singleTermM :: ScalarM -> p -> (Eql, Eql, Multiset (Pair SymbolM Eql))
singleTermM ScalarM _ = (Eql, Eql, Multiset (Pair SymbolM Eql))
instance ValuePattern ScalarM ScalarData where
value e () ScalarM v = if e == v then pure () else mzero
instance ValuePattern SymbolM SymbolExpr where
value e () SymbolM v = if e == v then pure () else mzero
pattern ZeroExpr :: ScalarData
pattern ZeroExpr = (Div (Plus []) (Plus [Term 1 []]))
pattern SingleSymbol :: SymbolExpr -> ScalarData
pattern SingleSymbol sym = Div (Plus [Term 1 [(sym, 1)]]) (Plus [Term 1 []])
-- Product of a coefficient and a monomial
pattern SingleTerm :: Integer -> Monomial -> ScalarData
pattern SingleTerm coeff mono = Div (Plus [Term coeff mono]) (Plus [Term 1 []])
instance Eq PolyExpr where
Plus xs == Plus ys =
match dfs ys (Multiset Eql)
[ [mc| #xs -> True |]
, [mc| _ -> False |] ]
instance Eq TermExpr where
Term a xs == Term b ys
| a == b = isEqualMonomial xs ys == Just 1
| a == -b = isEqualMonomial xs ys == Just (-1)
| otherwise = False
isEqualMonomial :: Monomial -> Monomial -> Maybe Integer
isEqualMonomial xs ys =
match dfs (xs, ys) (Pair (Multiset (Pair SymbolM Eql)) (Multiset (Pair SymbolM Eql)))
[ [mc| ((quote $s, $n) : $xss, (negQuote #s, #n) : $yss) ->
case isEqualMonomial xss yss of
Nothing -> Nothing
Just sgn -> return (if even n then sgn else - sgn) |]
, [mc| (($x, $n) : $xss, (#x, #n) : $yss) -> isEqualMonomial xss yss |]
, [mc| ([], []) -> return 1 |]
, [mc| _ -> Nothing |]
]
--
-- Arithmetic operations
--
mathScalarMult :: Integer -> ScalarData -> ScalarData
mathScalarMult c (Div m n) = Div (f c m) n
where
f c (Plus ts) = Plus (map (\(Term a xs) -> Term (c * a) xs) ts)
mathNegate :: ScalarData -> ScalarData
mathNegate = mathScalarMult (-1)
--
-- Pretty printing
--
class Printable a where
isAtom :: a -> Bool
pretty :: a -> String
pretty' :: Printable a => a -> String
pretty' e | isAtom e = pretty e
pretty' e = "(" ++ pretty e ++ ")"
instance Printable ScalarData where
isAtom (Div p (Plus [Term 1 []])) = isAtom p
isAtom _ = False
pretty (Div p1 (Plus [Term 1 []])) = pretty p1
pretty (Div p1 p2) = pretty'' p1 ++ " / " ++ pretty' p2
where
pretty'' :: PolyExpr -> String
pretty'' p@(Plus [_]) = pretty p
pretty'' p = "(" ++ pretty p ++ ")"
instance Printable PolyExpr where
isAtom (Plus []) = True
isAtom (Plus [Term _ []]) = True
isAtom (Plus [Term 1 [_]]) = True
isAtom _ = False
pretty (Plus []) = "0"
pretty (Plus (t:ts)) = pretty t ++ concatMap withSign ts
where
withSign (Term a xs) | a < 0 = " - " ++ pretty (Term (- a) xs)
withSign t = " + " ++ pretty t
instance Printable SymbolExpr where
isAtom Symbol{} = True
isAtom (Apply _ []) = True
isAtom Quote{} = True
isAtom _ = False
pretty (Symbol _ (':':':':':':_) []) = "#"
pretty (Symbol _ s []) = s
pretty (Symbol _ s js) = s ++ concatMap show js
pretty (Apply fn mExprs) = unwords (map pretty' (fn : mExprs))
pretty (Quote mExprs) = "`" ++ pretty' mExprs
pretty (FunctionData name _ _) = pretty name
instance Printable TermExpr where
isAtom (Term _ []) = True
isAtom (Term 1 [_]) = True
isAtom _ = False
pretty (Term a []) = show a
pretty (Term 1 xs) = intercalate " * " (map prettyPoweredSymbol xs)
pretty (Term (-1) xs) = "- " ++ intercalate " * " (map prettyPoweredSymbol xs)
pretty (Term a xs) = intercalate " * " (show a : map prettyPoweredSymbol xs)
prettyPoweredSymbol :: (SymbolExpr, Integer) -> String
prettyPoweredSymbol (x, 1) = show x
prettyPoweredSymbol (x, n) = pretty' x ++ "^" ++ show n
instance Show ScalarData where
show = pretty
instance Show PolyExpr where
show = pretty
instance Show TermExpr where
show = pretty
instance Show SymbolExpr where
show = pretty
instance {-# OVERLAPPING #-} Show (Index ScalarData) where
show (Sup i) = "~" ++ pretty' i
show (Sub i) = "_" ++ pretty' i
show (SupSub i) = "~_" ++ pretty' i
show (DF _ _) = ""
show (User i) = "|" ++ pretty' i
|
egison/egison
|
hs-src/Language/Egison/Math/Expr.hs
|
Haskell
|
mit
| 8,536
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.